import { AuthTokens, JWTIDToken, AuthStorageProxyType } from './types'; import { isEmpty } from './util'; const authKey = 'CIAM_AUTH_STORAGE'; const userKey = 'CIAM_USER_STORAGE'; export class BaseAuthProxy { private auth?: AuthTokens | null; private user?: JWTIDToken | null; constructor() { this.auth = null; this.user = null; } setAuth(auth: AuthTokens): void { if (typeof localStorage !== 'undefined') { window.localStorage.setItem(authKey, JSON.stringify(auth)); } else { this.auth = auth; } } getAuth(): AuthTokens { return typeof localStorage !== 'undefined' ? JSON.parse(window.localStorage.getItem(authKey) || '{}') : this.auth; } clearAuth(): void { if (typeof localStorage !== 'undefined') { localStorage.removeItem(authKey); } else { this.auth = null; } } getToken(): string | null { const auth: AuthTokens = this.getAuth(); if (isEmpty(auth)) return null; return auth?.access_token; } getUser() { return typeof localStorage !== 'undefined' ? JSON.parse(window.localStorage.getItem(userKey) || '{}') : this.user; } setUser(user: JWTIDToken) { if (typeof localStorage !== 'undefined') { window.localStorage.setItem(userKey, JSON.stringify(user)); } else { this.user = user; } } clearUser() { if (typeof localStorage !== 'undefined') { localStorage.removeItem(userKey); } else { this.user = null; } } clear() { this.clearAuth(); this.clearUser(); } } function createAuthLocal(): AuthStorageProxyType { return new BaseAuthProxy(); } export default createAuthLocal;