auth-jwt.service.ts 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. import { Observable } from 'rxjs';
  4. import { map } from 'rxjs/operators';
  5. import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
  6. import { SERVER_API_URL } from 'app/app.constants';
  7. @Injectable({ providedIn: 'root' })
  8. export class AuthServerProvider {
  9. constructor(private http: HttpClient, private $localStorage: LocalStorageService, private $sessionStorage: SessionStorageService) {}
  10. getToken() {
  11. return this.$localStorage.retrieve('authenticationToken') || this.$sessionStorage.retrieve('authenticationToken');
  12. }
  13. login(credentials): Observable<any> {
  14. const data = {
  15. username: credentials.username,
  16. password: credentials.password,
  17. rememberMe: credentials.rememberMe
  18. };
  19. return this.http.post(SERVER_API_URL + 'api/authenticate', data, { observe: 'response' }).pipe(map(authenticateSuccess.bind(this)));
  20. function authenticateSuccess(resp) {
  21. const bearerToken = resp.headers.get('Authorization');
  22. if (bearerToken && bearerToken.slice(0, 7) === 'Bearer ') {
  23. const jwt = bearerToken.slice(7, bearerToken.length);
  24. this.storeAuthenticationToken(jwt, credentials.rememberMe);
  25. return jwt;
  26. }
  27. }
  28. }
  29. loginWithToken(jwt, rememberMe) {
  30. if (jwt) {
  31. this.storeAuthenticationToken(jwt, rememberMe);
  32. return Promise.resolve(jwt);
  33. } else {
  34. return Promise.reject('auth-jwt-service Promise reject'); // Put appropriate error message here
  35. }
  36. }
  37. storeAuthenticationToken(jwt, rememberMe) {
  38. if (rememberMe) {
  39. this.$localStorage.store('authenticationToken', jwt);
  40. } else {
  41. this.$sessionStorage.store('authenticationToken', jwt);
  42. }
  43. }
  44. logout(): Observable<any> {
  45. return new Observable(observer => {
  46. this.$localStorage.clear('authenticationToken');
  47. this.$sessionStorage.clear('authenticationToken');
  48. observer.complete();
  49. });
  50. }
  51. }