Guest User

Untitled

a guest
Dec 23rd, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. @Injectable()
  2. export class LoggedInGuard implements CanLoad, CanActivate {
  3. constructor(private signinService: SigninService, private router: Router) { }
  4.  
  5. checkAuthentication(path: string): boolean {
  6. const loggedin = this.signinService.isLoggedin();
  7. if (!loggedin) {
  8. this.router.navigate([ this.signinService.handleLogin(`/${ path }`) ]);
  9. }
  10. return loggedin;
  11. }
  12.  
  13. canLoad(route: Route): boolean {
  14. return this.checkAuthentication(route.path);
  15. }
  16.  
  17. canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  18. return this.checkAuthentication(route.routeConfig.path);
  19. }
  20.  
  21. }
  22.  
  23. @Injectable({
  24. providedIn: 'root'
  25. })
  26. export class SigninService {
  27.  
  28. private baseUrl: string;
  29. private user: User;
  30. private lastUrl: string;
  31.  
  32. constructor(private http: HttpClient, private router: Router) {
  33. this.baseUrl = `${environment.url}/auth/signin`;
  34. this.router.events
  35. .filter(e => e instanceof NavigationEnd)
  36. .subscribe((e: NavigationEnd) => this.lastUrl = e.url);
  37. }
  38.  
  39. public isLoggedin(): boolean {
  40. return this.user !== undefined && localStorage.getItem('token') !== undefined;
  41. }
  42.  
  43. public login(username: string, password: string): Observable<User> {
  44. const params = new HttpParams()
  45. .set('username', username)
  46. .set('password', password);
  47. return this.http.post<User>(`${this.baseUrl}`, params).do((user: User) => this.user = user);
  48. }
  49.  
  50. public logout(): void {
  51. localStorage.clear();
  52. this.user = undefined;
  53. this.handleLogin('/');
  54. }
  55.  
  56. public handleLogin(path: string = this.lastUrl) {
  57. this.router.navigate(['/signin', btoa(path)]);
  58. }
  59.  
  60. public get UserDetail(): User {
  61. return this.user;
  62. }
  63.  
  64.  
  65. }
  66.  
  67. public login(): void {
  68. console.log(this.signinForm);
  69. this.signinService.login(this.signinForm.value.username, this.signinForm.value.password ).subscribe((user: User) => {
  70. this.user = user;
  71. localStorage.setItem('token', this.user.token.token);
  72. this.isSuccess = true;
  73. this.message = 'Usuário encontrado. Aguarde um momento!';
  74. }, (err: HttpErrorResponse) => {
  75. this.isSuccess = false;
  76. this.message = err.error.error.message;
  77. console.error(err);
  78. }, () => {
  79. this.router.navigate([ atob(this.navigateTo) ]);
  80. });
  81. }
Add Comment
Please, Sign In to add comment