import { shareReplay, tap } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; import { Observable, forkJoin } from 'rxjs'; import { environment, CLIENT_ID } from '../../environments/environment'; const baseUrls = environment.baseUrls; const ACCESS_TOKEN_STORAGE_KEY = 'accessToken'; const REFRESH_TOKEN_STORAGE_KEY = 'refreshToken'; const PUBLIC_CERTIFICATE_KEY = 'publicCertificate'; const PUBLIC_CERTIFICATE_ALG = 'publicCertificateAlg'; export class AuthResponse { email: string; access_token: string; refresh_token?: string; } export interface PublicCertificate { alg: string; value: string; } @Injectable() export class AuthService { constructor(private http: HttpClient) {} private SERVICE_URL = `${baseUrls.serviceSecurity}/oauth/token`; private PUBLIC_CERTIFICATE_URL = `${baseUrls.serviceSecurity}/oauth/token_key`; /** * Authenticate user * @param username * @param password * @param clientId * @param accessId */ private _authenticate( username: string, password: string, clientId: string, accessId: string = '' ): Observable { const body = new HttpParams() .set('grant_type', 'password') .set('username', username) .set('password', password) .set('client_id', clientId) .set('access_id', accessId); const headers = new HttpHeaders().set( 'Content-Type', 'application/x-www-form-urlencoded' ); return this.http.post(this.SERVICE_URL, body, { headers }); } /** * Login and authenticate user with Client ID then set api token on success * @param email * @param password */ public login(username: string, password: string) { const authenticate$ = this._authenticate( username.toLocaleLowerCase().trim(), password, CLIENT_ID ); const certificate$ = this.http.get( this.PUBLIC_CERTIFICATE_URL ); return forkJoin(certificate$, authenticate$).pipe( tap(([certificate, authenticate]) => { localStorage.setItem('email', authenticate.email); localStorage.setItem( ACCESS_TOKEN_STORAGE_KEY, authenticate.access_token ); localStorage.setItem( REFRESH_TOKEN_STORAGE_KEY, authenticate.refresh_token ); localStorage.setItem(PUBLIC_CERTIFICATE_KEY, certificate.value); localStorage.setItem(PUBLIC_CERTIFICATE_ALG, certificate.alg); }), shareReplay() ); } }