Advertisement
coffeecode12

login

Apr 13th, 2020
2,208
0
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 { CookieService } from '../services/cookie.service';
  7. import { User } from '../models/auth.models';
  8. import { environment } from '../../../environments/environment'
  9.  
  10. @Injectable({ providedIn: 'root' })
  11. export class AuthenticationService {
  12.     user: User;
  13.  
  14.     constructor(private http: HttpClient, private cookieService: CookieService) {
  15.     }
  16.  
  17.     /**
  18.      * Returns the current user
  19.      */
  20.     public currentUser(): User {
  21.         if (!this.user) {
  22.             this.user = JSON.parse(this.cookieService.getCookie('currentUser'));
  23.         }
  24.         return this.user;
  25.     }
  26.  
  27.     /**
  28.      * Performs the auth
  29.      * @param username email of user
  30.      * @param password password of user
  31.      */
  32.     login(username: string, password: string) {
  33.         return this.http.post<any>(`${environment.urlServer}/login`,{ username, password })
  34.             .pipe(map(user => {
  35.                 // login successful if there's a jwt token in the response
  36.                 if (user && user.token) {
  37.                     this.user = user;
  38.                     // store user details and jwt in cookie
  39.                     this.cookieService.setCookie('currentUser', JSON.stringify(user), 1);
  40.                 }
  41.                 return user;
  42.             }));
  43.     }
  44.  
  45.     /**
  46.      * Logout the user
  47.      */
  48.     logout() {
  49.         // remove user from local storage to log user out
  50.         this.cookieService.deleteCookie('currentUser');
  51.         this.user = null;
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement