SHARE
TWEET

Untitled

a guest Jul 11th, 2019 124 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class User {
  2. id?: number;
  3. name?: string;
  4. email?: string;
  5. password?: string;
  6. username?: string;
  7.  
  8. constructor() {}
  9.  }
  10.      
  11. import { Injectable } from '@angular/core';
  12. import { HttpClient, HttpErrorResponse } from '@angular/common/http';
  13. import { HttpHeaders } from '@angular/common/http';
  14. import { Router } from '@angular/router';
  15. import { BehaviorSubject, Observable, throwError } from 'rxjs';
  16. import { catchError, map, tap } from 'rxjs/operators';
  17. import { environment } from '../../environments/environment.prod';
  18. import { User } from '../models/user';
  19. // Setup headers
  20. const httpOptions = {
  21.   headers: new HttpHeaders({
  22. 'Content-Type': 'application/json'
  23.   })
  24. };
  25.  
  26. @Injectable({
  27.  providedIn: 'root'
  28. })
  29. export class AuthService {
  30.   public currentUser: User;
  31.   private readonly apiUrl = environment.apiUrl;
  32.   private registerUrl = this.apiUrl + '/register';
  33.   private loginUrl = this.apiUrl + '/login';
  34.  
  35.  constructor(
  36. private http: HttpClient,
  37. private router: Router)
  38.  
  39. onRegister(user: User): Observable<User> {
  40.  
  41. const request = JSON.stringify(
  42.   { name: user.name, username: user.username, email: user.email, password: user.password }
  43. );
  44.  
  45. return this.http.post(this.registerUrl, request, httpOptions)
  46.   .pipe(
  47.     map((response: User) => {
  48.       // Receive jwt token in the response
  49.       const token: string = response['access_token'];
  50.       // If we have a token, proceed
  51.       if (token) {
  52.         this.setToken(token);
  53.         this.getUser().subscribe();
  54.       }
  55.       return response;
  56.     }),
  57.     catchError(error => this.handleError(error))
  58.   );
  59.   }
  60.  
  61.   onLogin(user: User): Observable<User> {
  62.  
  63. const request = JSON.stringify(
  64.   { email: user.email, password: user.password }
  65. );
  66.  
  67. return this.http.post(this.loginUrl, request, httpOptions)
  68.   .pipe(
  69.     map((response: User) => {
  70.       // Receive jwt token in the response
  71.       const token: string = response['access_token'];
  72.       // If we have a token, proceed
  73.       if (token) {
  74.         this.setToken(token);
  75.         this.getUser().subscribe();
  76.       }
  77.       return response;
  78.     }),
  79.     catchError(error => this.handleError(error))
  80.   );
  81.   }
  82.  
  83.   onLogout(): Observable<User> {
  84. return this.http.post(this.apiUrl + '/logout', httpOptions).pipe(
  85.   tap(
  86.     () => {
  87.       localStorage.removeItem('token');
  88.       this.router.navigate(['/']);
  89.     }
  90.   )
  91. );
  92.   }
  93.  
  94.   setToken(token: string): void {
  95. return localStorage.setItem('token', token );
  96.  }
  97.  
  98.  getToken(): string {
  99. return localStorage.getItem('token');
  100. }
  101.  
  102.  private handleError(error: HttpErrorResponse) {
  103. if (error.error instanceof ErrorEvent) {
  104.   // A client-side error.
  105.   console.error('An error occurred:', error.error.message);
  106. } else {
  107.   // The backend error.
  108.     return throwError(error);
  109. }
  110. // return a custom error message
  111. return throwError('Ohps something wrong happen here; please try again later.');
  112.   }
  113. }
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