Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Injectable()
- export class LoggedInGuard implements CanLoad, CanActivate {
- constructor(private signinService: SigninService, private router: Router) { }
- checkAuthentication(path: string): boolean {
- const loggedin = this.signinService.isLoggedin();
- if (!loggedin) {
- this.router.navigate([ this.signinService.handleLogin(`/${ path }`) ]);
- }
- return loggedin;
- }
- canLoad(route: Route): boolean {
- return this.checkAuthentication(route.path);
- }
- canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
- return this.checkAuthentication(route.routeConfig.path);
- }
- }
- @Injectable({
- providedIn: 'root'
- })
- export class SigninService {
- private baseUrl: string;
- private user: User;
- private lastUrl: string;
- constructor(private http: HttpClient, private router: Router) {
- this.baseUrl = `${environment.url}/auth/signin`;
- this.router.events
- .filter(e => e instanceof NavigationEnd)
- .subscribe((e: NavigationEnd) => this.lastUrl = e.url);
- }
- public isLoggedin(): boolean {
- return this.user !== undefined && localStorage.getItem('token') !== undefined;
- }
- public login(username: string, password: string): Observable<User> {
- const params = new HttpParams()
- .set('username', username)
- .set('password', password);
- return this.http.post<User>(`${this.baseUrl}`, params).do((user: User) => this.user = user);
- }
- public logout(): void {
- localStorage.clear();
- this.user = undefined;
- this.handleLogin('/');
- }
- public handleLogin(path: string = this.lastUrl) {
- this.router.navigate(['/signin', btoa(path)]);
- }
- public get UserDetail(): User {
- return this.user;
- }
- }
- public login(): void {
- console.log(this.signinForm);
- this.signinService.login(this.signinForm.value.username, this.signinForm.value.password ).subscribe((user: User) => {
- this.user = user;
- localStorage.setItem('token', this.user.token.token);
- this.isSuccess = true;
- this.message = 'Usuário encontrado. Aguarde um momento!';
- }, (err: HttpErrorResponse) => {
- this.isSuccess = false;
- this.message = err.error.error.message;
- console.error(err);
- }, () => {
- this.router.navigate([ atob(this.navigateTo) ]);
- });
- }
Add Comment
Please, Sign In to add comment