Guest User

Untitled

a guest
May 17th, 2018
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. import {Injectable} from '@angular/core';
  2. import {BehaviorSubject} from 'rxjs/BehaviorSubject';
  3. import 'rxjs/add/operator/map';
  4. import {Observable} from 'rxjs/Observable';
  5.  
  6. import {CookieService} from 'ngx-cookie';
  7.  
  8. import {LoggerService} from './logger.service';
  9. import {ApiService} from './api.service';
  10.  
  11. import {User, LogoutInfo} from '../../model/user';
  12.  
  13. @Injectable()
  14. export class AuthService {
  15.  
  16. private currentUserSubject = new BehaviorSubject<User>(new User());
  17. private isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
  18.  
  19. private userUrl: string = 'user';
  20.  
  21. constructor(
  22. private cookieService: CookieService,
  23. private apiService: ApiService,
  24. private loggerService: LoggerService
  25. ) {}
  26.  
  27. currentUser(): Observable<User> {
  28. return this.currentUserSubject.asObservable();
  29. }
  30.  
  31. isAuthenticated(): Observable<boolean> {
  32. return this.isAuthenticatedSubject.asObservable();
  33. }
  34.  
  35. setAuthentication(user: User): void {
  36. this.currentUserSubject.next(user);
  37. this.isAuthenticatedSubject.next(true);
  38. this.loggerService.log(`Session set for ${user.contactName}.`);
  39. }
  40.  
  41. purgeAuthentication(): void {
  42. this.currentUserSubject.next(new User());
  43. this.isAuthenticatedSubject.next(false);
  44. this.loggerService.log('Session removed.');
  45. }
  46.  
  47. populate() {
  48.  
  49. return new Promise((resolve, reject) => {
  50.  
  51. if (this.cookieService.get('vedrax-index-ui-csrf')) {
  52. let url = `${this.userUrl}/current`;
  53. this.apiService.get<User>(url)
  54. .subscribe(
  55. res => {
  56. this.setAuthentication(res);
  57. resolve();
  58. },
  59. err => {
  60. this.loggerService.logObject(err);
  61. this.purgeAuthentication();
  62. resolve();
  63. });
  64. } else {
  65. this.purgeAuthentication();
  66. resolve();
  67. }
  68.  
  69. });
  70.  
  71. }
  72.  
  73. login(username: string, password: string): Observable<User> {
  74. let url = `${this.userUrl}/login`;
  75. return this.apiService.post<User>(url, {userName: username, password: password})
  76. .map(data => {
  77. this.setAuthentication(data);
  78. return data;
  79. });
  80. }
  81.  
  82. logout(): Observable<LogoutInfo> {
  83. let url = `${this.userUrl}/logout`;
  84. return this.apiService.get<LogoutInfo>(url)
  85. .map(data => {
  86. this.purgeAuthentication();
  87. return data;
  88. });
  89. }
  90.  
  91. }
Add Comment
Please, Sign In to add comment