import { Injectable } from "@angular/core" ; import { LoginState } from "../session-states/login-state.enum" ; import { DatabaseUser , encryptPassword , LocalUser , passwordEqualsEncrypted , } from "./local-user" ; import { Database } from "../../database/database" ; import { SessionService } from "./session.service" ; /**
 * Responsibilities:
 * - Manage local authentication
 * - Save users in local storage
 */ @ Injectable ( ) export class LocalSession extends SessionService { private currentDBUser : DatabaseUser ; constructor ( private database ) { super ( ) ; } param username param password public async login ( username , password ) { const user = JSON . parse ( window . localStorage . getItem ( username ) ) ; if ( user ) { if ( passwordEqualsEncrypted ( password , user . encryptedPassword ) ) { this . currentDBUser = user ; this . loginState . next ( LoginState . LOGGED_IN ) ; } else { this . loginState . next ( LoginState . LOGIN_FAILED ) ; } } else { this . loginState . next ( LoginState . UNAVAILABLE ) ; } return this . loginState . value ; } param user param password public saveUser ( user , password ) { const localUser = { name : user . name , roles : user . roles , encryptedPassword : encryptPassword ( password ) , } ; window . localStorage . setItem ( localUser . name , JSON . stringify ( localUser ) ) ; if ( this . getCurrentUser ( ) ?. name === localUser . name ) { this . currentDBUser = localUser ; } } param username public removeUser ( username ) { window . localStorage . removeItem ( username ) ; } public checkPassword ( username , password ) { const user = JSON . parse ( window . localStorage . getItem ( username ) ) ; return user && passwordEqualsEncrypted ( password , user . encryptedPassword ) ; } public getCurrentUser ( ) { return this . currentDBUser ; } /**
     * Resets the login state and current user (leaving it in local storage to allow later local login)
     */ public logout ( ) { this . currentDBUser = undefined ; this . loginState . next ( LoginState . LOGGED_OUT ) ; } getDatabase ( ) { return this . database ; } sync ( ) { return Promise . reject ( new Error ( "Cannot sync local session" ) ) ; } }