@synap/ngx-auth
v6.0.0
Published
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.3.8.
Downloads
26
Readme
SynapNgxAuth
This project was generated with Angular CLI version 7.3.8.
Intended for use with the SynapNestUsersModule on the server
Usage
(look at the test app for a working example)
Import the SynapNgxAuthModule
in your AppModule
:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ToastModule, ToastService } from 'ng-uikit-pro-standard';
import { SynapNgxAuthModule } from '@synap-libs/ngx-auth';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';
import { ROUTES } from './app.routes';
@NgModule({
declarations: [
AppComponent
],
imports: [
RouterModule,
RouterModule.forRoot(ROUTES),
ToastModule.forRoot({ enableHtml: true }),
// apiHost is required and requires that you have the `api` property in your environment config
// messagingService is optional - intended for use with a message service that has methods
// {success|warn|info|error}
SynapNgxAuthModule.forRoot({ apiHost: environment.api, messagingService: ToastService })
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Use the provided guards in your routes:
import { Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AlreadyLoggedInGuard, AuthGuard } from '@synap-libs/ngx-auth';
export const ROUTES:Routes = [
// Prevent account page (login/reset-password/etc) access if already logged in
{ path: 'login', component: LoginComponent, canActivate: [AlreadyLoggedInGuard] },
// Protect routes that require authentication
// `data.roles` allows restricting a route to users with specified roles
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard],
data: { roles: ['user'] }
},
// Default
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
];
Services provided
SynapNgxAuthService
Get the current user:
this.authService.currentUser.subscribe(u => this.user = u);
Log in/out:
Login()
{
this.loggingIn = true;
this.authSvc.Login(this.loginForm.value).subscribe(
r =>
{
if (r.success)
{
this.router.navigateByUrl('/admin').catch((e) => this.toastr.error(e.message));
this.loggingIn = false;
}
else
{
this.toastr.error(r.message);
this.loggingIn = false;
}
},
err =>
{
this.toastr.error(err.error.message);
this.loggingIn = false;
}
);
}
Logout()
{
this.authService.Logout().pipe(filter(r => r.success)).subscribe(() =>
{
this.router.navigate(['account', 'login']).catch();
});
}
SynapNgxUserService
This service provides methods for resetting a password. See the test-app for a working example.