SHARE
TWEET

Untitled

a guest Jun 25th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable, Injector } from '@angular/core';
  2. import { Http, Headers, Response, RequestOptions } from '@angular/http';
  3. import { Observable, Subject, BehaviorSubject } from 'rxjs/Rx';
  4. import { LOGIN, API } from './../utils';
  5. import { StorageService } from './storage.service';
  6. import 'rxjs/add/operator/map';
  7. import { ResponseModel } from './../models/dto';
  8. import { urlFormEncode } from './../utils/index';
  9. import { responseToLoginResponse, loginResponseToResponseModel } from './../utils/converters';
  10. import { LoginUserModel, LoginResponse } from '../models/frontend.models';
  11. import { parseJwt } from '../utils/index';
  12. import { Router } from '@angular/router';
  13. import { ApplicationUserModel } from '../models/dto';
  14.  
  15. export enum SessionEvent {
  16.   LOGGED_IN,
  17.   LOGGED_OUT
  18. }
  19.  
  20. @Injectable()
  21. export class SessionService {
  22.  
  23.   eventStream = new BehaviorSubject<SessionEvent>(undefined);
  24.   lastEvent: SessionEvent = undefined;
  25.   private refreshingAccessToken: Observable<string>;
  26.   invalidate = false;
  27.  
  28.   protected get storageService(): StorageService {
  29.     return this.injector.get(StorageService);
  30.   }
  31.  
  32.   protected get http(): Http {
  33.     return this.injector.get(Http);
  34.   }
  35.  
  36.   constructor(protected injector: Injector, protected router: Router) {
  37.     this.eventStream.subscribe(val => {
  38.       if (val !== undefined) {
  39.         this.lastEvent = val;
  40.       }
  41.     });
  42.   }
  43.  
  44.   public getAccessToken(): Observable<string> {
  45.     if (this.refreshingAccessToken) {
  46.       return this.refreshingAccessToken;
  47.     }
  48.     return this.storageService.getAccessToken().flatMap(accessToken => {
  49.       let parsed = parseJwt(accessToken);
  50.       let now = new Date();
  51.       let expires = new Date(parsed.exp * 1000 - 30 * 60 * 1000);
  52.       if (now.getTime() < expires.getTime() && !this.invalidate) {
  53.         return Observable.of(accessToken);
  54.       } else {
  55.         this.invalidate = false;
  56.         const tmp = this.http.post(LOGIN, urlFormEncode({
  57.           'grant_type': 'refresh_token',
  58.           'refresh_token': this.storageService.getRefreshToken(),
  59.           'resource': API,
  60.           'scope': 'offline_access'
  61.         }), {
  62.           headers: new Headers({
  63.             'Content-Type': 'application/x-www-form-urlencoded',
  64.             'Authorization': 'Basic a2x3ZWJjbGllbnQ6NHZjcW04Tlk='
  65.           })
  66.         }).map(responseToLoginResponse).map(response => {
  67.           this.storageService.setAccessToken(response.access_token, response.refresh_token, true);
  68.           return response.access_token;
  69.         }).catch(err => {
  70.           this.storageService.removeAccessToken();
  71.           return Observable.of(undefined);
  72.         });
  73.         this.refreshingAccessToken = tmp.share();
  74.         return tmp.finally(() => {
  75.           delete this.refreshingAccessToken;
  76.         });
  77.       }
  78.     });
  79.   }
  80.  
  81.   public invalidateAccessToken() {
  82.     this.invalidate = true;
  83.   }
  84.  
  85.   public login(cridentials: LoginUserModel): Observable<LoginResponse> {
  86.     let subject = new Subject<LoginResponse>();
  87.     this.http.post(LOGIN, urlFormEncode({
  88.       'grant_type': 'password',
  89.       'username': cridentials.email,
  90.       'password': cridentials.password,
  91.       'resource': API,
  92.       'scope': 'offline_access'
  93.     }), {
  94.       headers: new Headers({
  95.         'Content-Type': 'application/x-www-form-urlencoded',
  96.         'Authorization': 'Basic a2x3ZWJjbGllbnQ6NHZjcW04Tlk='
  97.       })
  98.     }).finally(() => {
  99.       subject.complete();
  100.     }).subscribe((response: Response) => {
  101.       if (this.storageService.hasAccessToken()) {
  102.         this.logout();
  103.       }
  104.       let login = responseToLoginResponse(response);
  105.       this.storageService.setAccessToken(login.access_token, login.refresh_token, true);
  106.       this.emitLogin();
  107.       subject.next(login);
  108.       this.router.navigate(['/home']);
  109.     }, (errorResponse: any) => {
  110.       let error: ResponseModel = errorResponse;
  111.       if (errorResponse.error != null) {
  112.         error = loginResponseToResponseModel(errorResponse);
  113.       }
  114.       subject.error(error);
  115.     });
  116.     return subject;
  117.   }
  118.  
  119.   public emitLogin() {
  120.     this.eventStream.next(SessionEvent.LOGGED_IN);
  121.   }
  122.  
  123.   logout() {
  124.     this.eventStream.next(SessionEvent.LOGGED_OUT);
  125.   }
  126.  
  127.   public getLastEventSync() {
  128.     return this.lastEvent;
  129.   }
  130. }
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