File

src/app/providers/services/auth.service.ts

Index

Properties
Methods
Accessors

Constructor

constructor(http: HttpClient, router: Router, storage: StorageService, sessionStore: SessionStore, helper: JwtHelperService)
Parameters :
Name Type Optional
http HttpClient No
router Router No
storage StorageService No
sessionStore SessionStore No
helper JwtHelperService No

Methods

Private fallbackToken
fallbackToken()
Returns : string
getToken
getToken()
Returns : string
login
login(credentials: Credentials)
Parameters :
Name Type Optional
credentials Credentials No
Returns : Observable<boolean>
logout
logout()
Returns : void

Properties

Private token
token: string
Type : string

Accessors

authenticated
getauthenticated()
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Observable, of } from 'rxjs';
import { catchError, first, map } from 'rxjs/operators';
import { AUTH_API, JWT_KEY } from '../../app.constants';
import { AuthResponse } from '../../models/auth-response';
import { Credentials } from '../../models/credentials';
import { IJwt } from '../../models/i-jwt';
import { SessionStore } from '../stores/session.store';
import { StorageService } from './storage.service';

@Injectable()
export class AuthService {
  private token: string;

  constructor(
    private http: HttpClient,
    private router: Router,
    private storage: StorageService,
    private sessionStore: SessionStore,
    private helper: JwtHelperService
  ) {}

  get authenticated(): boolean {
    try {
      const rawToken = this.getToken();
      const isExpired = this.helper.isTokenExpired(rawToken);
      return !isExpired;
    } catch (error) {
      return false;
    }
  }

  login(credentials: Credentials): Observable<boolean> {
    return this.http.post<AuthResponse>(`${AUTH_API}/login`, credentials).pipe(
      map(res => {
        const authenticated = res.token && res.token.length > 0;
        if (authenticated) {
          this.storage.set(JWT_KEY, res.token);
          const jwt = this.helper.decodeToken(res.token) as IJwt;
          this.sessionStore.createSession(jwt);
        }
        return authenticated;
      }),
      catchError(err => {
        return of(false);
      })
    );
  }

  logout(): void {
    this.sessionStore.session$.pipe(first()).subscribe(session => {
      if (session.sso) {
        this.router.navigate(['/sso']);
        return;
      }
      this.router.navigate(['/login']);
    });
  }

  getToken(): string {
    return this.token ? this.token : this.fallbackToken();
  }

  private fallbackToken(): string {
    return this.storage.get(JWT_KEY);
  }
}

result-matching ""

    No results matching ""