Advertisement
Guest User

Untitled

a guest
Feb 27th, 2020
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable } from '@angular/core';
  2. import { HttpClient, HttpHeaders } from '@angular/common/http';
  3. import { tap } from 'rxjs/operators';
  4. import { EnvService } from './env.service';
  5. import { User } from '../models/user';
  6.  
  7. @Injectable({
  8.   providedIn: 'root'
  9. })
  10. export class AuthService {
  11.   isLoggedIn = false;
  12.   token:any;
  13.  
  14.   constructor(
  15.  
  16.     private http: HttpClient,
  17.     private storage: WindowLocalStorage,
  18.     private env: EnvService,
  19.  
  20.   ) { }
  21.  
  22.   login(email: String, password: String) {
  23.     return this.http.post(this.env.API_URL + 'auth/login',
  24.       {email: email, password: password}
  25.     ).pipe(
  26.       tap(token => {
  27.         this.storage.setItem('token', token)
  28.         .then(
  29.           () => {
  30.             console.log('Token Stored');
  31.           },
  32.           error => console.error('Error storing item', error)
  33.         );
  34.         this.token = token;
  35.         this.isLoggedIn = true;
  36.         return token;
  37.       }),
  38.     );
  39.   }
  40.   register(fName: String, lName: String, email: String, password: String) {
  41.     return this.http.post(this.env.API_URL + 'auth/register',
  42.       {fName: fName, lName: lName, email: email, password: password}
  43.     )
  44.   }
  45.   logout() {
  46.     const headers = new HttpHeaders({
  47.       'Authorization': this.token["token_type"]+" "+this.token["access_token"]
  48.     });
  49.     return this.http.get(this.env.API_URL + 'auth/logout', { headers: headers })
  50.     .pipe(
  51.       tap(data => {
  52.         this.storage.remove("token");
  53.         this.isLoggedIn = false;
  54.         delete this.token;
  55.         return data;
  56.       })
  57.     )
  58.   }
  59.   user() {
  60.     const headers = new HttpHeaders({
  61.       'Authorization': this.token["token_type"]+" "+this.token["access_token"]
  62.     });
  63.     return this.http.get<User>(this.env.API_URL + 'auth/user', { headers: headers })
  64.     .pipe(
  65.       tap(user => {
  66.         return user;
  67.       })
  68.     )
  69.   }
  70.   getToken() {
  71.     return this.storage.getItem('token').then(
  72.       data => {
  73.         this.token = data;
  74.         if(this.token != null) {
  75.           this.isLoggedIn=true;
  76.         } else {
  77.           this.isLoggedIn=false;
  78.         }
  79.       },
  80.       error => {
  81.         this.token = null;
  82.         this.isLoggedIn=false;
  83.       }
  84.     );
  85.   }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement