Guest User

Untitled

a guest
Mar 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3.  
  4. @Injectable()
  5. export class AuthService {
  6.  
  7. public isAuthenticated = false;
  8.  
  9. constructor(private http: HttpClient) {
  10. }
  11.  
  12. setUserLoggedIn() {
  13. this.isAuthenticated = true;
  14. }
  15.  
  16. getUserLoggedIn() {
  17. return this.isAuthenticated;
  18. }
  19.  
  20. public setAuthenticated() {
  21.  
  22. this.http
  23. .get<any>(url, {withCredentials: true, observe: 'response'})
  24. .subscribe(
  25. (res) => {
  26. console.log('Status: Authenticated: ' + res.headers.get('status') );
  27. if ( res.headers.get('status') === '200') {
  28. this.setUserLoggedIn();
  29. }
  30. },
  31. err => {});
  32. }
  33. }
  34.  
  35. import { Injectable } from '@angular/core';
  36. import { CanActivate,
  37. ActivatedRouteSnapshot,
  38. RouterStateSnapshot,
  39. Router,
  40. ActivatedRoute} from '@angular/router';
  41. import { Observable } from 'rxjs/Observable';
  42. import { HttpClient } from '@angular/common/http';
  43. import { AuthService } from './service/auth.service';
  44.  
  45.  
  46. @Injectable()
  47. export class AuthguardGuard implements CanActivate {
  48. constructor(
  49. private user: AuthService,
  50. public router: Router,
  51. private http: HttpClient,
  52. private activatedRoute: ActivatedRoute) {
  53. }
  54.  
  55. canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  56.  
  57. if ( !this.user.isAuthenticated ) {
  58. console.log('Not authenticated!');
  59. this.router.navigate(['userLogin']);
  60. return false;
  61. }
  62. return true;
  63. }
  64. }
Add Comment
Please, Sign In to add comment