SHARE
TWEET

Untitled

a guest Jan 26th, 2019 112 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {Injectable} from '@angular/core';
  2. import {HttpClient} from '@angular/common/http';
  3. import {BehaviorSubject, Observable} from 'rxjs';
  4. import {map} from 'rxjs/operators';
  5.  
  6. import {environment} from '@environments/environment';
  7. import {User} from '@app/_models';
  8.  
  9. @Injectable({providedIn: 'root'})
  10. export class AuthenticationService {
  11.   public currentUser: Observable<User>;
  12.   private currentUserSubject: BehaviorSubject<User>;
  13.  
  14.   constructor(private http: HttpClient) {
  15.     if (localStorage.getItem('currentUser')) {
  16.       this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
  17.     } else {
  18.       this.currentUserSubject = new BehaviorSubject<User>(null);
  19.     }
  20.     this.currentUser = this.currentUserSubject.asObservable();
  21.   }
  22.   public get currentUserValue(): User {
  23.     return this.currentUserSubject.value;
  24.   }
  25.  
  26.   login(mail: string, password: string) {
  27.     return this.http.post<any>(`${environment.apiUrl}/auth/login`, {mail, password})
  28.       .pipe(map(user => {
  29.         // login successful if there's a jwt token in the response
  30.         if (user && user.jwtToken) {
  31.           // store user details and jwt token in local storage to keep user logged in between page refreshes
  32.           localStorage.setItem('currentUser', JSON.stringify(user));
  33.           this.currentUserSubject.next(user);
  34.           this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
  35.           this.currentUser = this.currentUserSubject.asObservable();
  36.         }
  37.  
  38.         return user;
  39.       }));
  40.   }
  41.  
  42.   logout() {
  43.     // remove user from local storage to log user out
  44.     localStorage.removeItem('currentUser');
  45.     this.currentUserSubject.next(null);
  46.     location.reload();
  47.   }
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top