Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable } from '@angular/core';
  2.  
  3. export interface Credentials {
  4.   token: string;
  5. }
  6.  
  7. const credentialsKey = 'credentials';
  8.  
  9. /**
  10.  * Provides storage for authentication credentials.
  11.  * The Credentials interface should be replaced with proper implementation.
  12.  */
  13. @Injectable({
  14.   providedIn: 'root'
  15. })
  16. export class CredentialsService {
  17.  
  18.   // tslint:disable-next-line:variable-name
  19.   private _credentials: Credentials | null = null;
  20.  
  21.   constructor() {
  22.     const savedCredentials = sessionStorage.getItem(credentialsKey) || localStorage.getItem(credentialsKey);
  23.     if (savedCredentials) {
  24.       this._credentials = JSON.parse(savedCredentials);
  25.     }
  26.   }
  27.  
  28.   /**
  29.    * Checks is the user is authenticated.
  30.    * @return True if the user is authenticated.
  31.    */
  32.   isAuthenticated(): boolean {
  33.     return !!this.credentials;
  34.   }
  35.  
  36.   /**
  37.    * Gets the user credentials.
  38.    * @return The user credentials or null if the user is not authenticated.
  39.    */
  40.   get credentials(): Credentials | null {
  41.     return this._credentials;
  42.   }
  43.  
  44.   /**
  45.    * Sets the user credentials.
  46.    * The credentials may be persisted across sessions by setting the `remember` parameter to true.
  47.    * Otherwise, the credentials are only persisted for the current session.
  48.    * @param credentials The user credentials.
  49.    * @param remember True to remember credentials across sessions.
  50.    */
  51.   setCredentials(credentials?: Credentials, remember?: boolean) {
  52.     this._credentials = credentials || null;
  53.  
  54.     if (credentials) {
  55.       const storage = remember ? localStorage : sessionStorage;
  56.       storage.setItem(credentialsKey, JSON.stringify(credentials));
  57.     } else {
  58.       sessionStorage.removeItem(credentialsKey);
  59.       localStorage.removeItem(credentialsKey);
  60.     }
  61.   }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement