UNPKG

@intuitionrobotics/user-account

Version:
151 lines 6.54 kB
import { Module, Second } from "@intuitionrobotics/ts-common"; import { BaseComponent, BrowserHistoryModule, StorageKey, ThunderDispatcher, ToastModule, XhrHttpModule } from "@intuitionrobotics/thunderstorm/frontend"; import { QueryParam_Email, QueryParam_JWT } from "../../shared/api.js"; import { BaseHttpRequest, HeaderKey_FunctionExecutionId, HeaderKey_JWT, HttpMethod } from "@intuitionrobotics/thunderstorm"; import { AUTHENTICATION_KEY, AUTHENTICATION_PREFIX } from "../../index.js"; export const StorageKey_UserEmail = new StorageKey(`storage-${QueryParam_Email}`); export const StorageKey_JWT = new StorageKey(`storage-${QueryParam_JWT}`); export const RequestKey_AccountCreate = "account-create"; export const RequestKey_AccountLogin = "account-login"; export const RequestKey_AccountLoginSAML = "account-login-saml"; export const RequestKey_ValidateSession = "account-validate"; export var LoggedStatus; (function (LoggedStatus) { LoggedStatus[LoggedStatus["VALIDATING"] = 0] = "VALIDATING"; LoggedStatus[LoggedStatus["LOGGED_OUT"] = 1] = "LOGGED_OUT"; LoggedStatus[LoggedStatus["LOGGED_IN"] = 2] = "LOGGED_IN"; })(LoggedStatus || (LoggedStatus = {})); const dispatch_onAccountsLoaded = new ThunderDispatcher("__onAccountsLoaded"); export class AccountModule_Class extends Module { status = LoggedStatus.VALIDATING; dispatchUI_loginChanged; accounts = []; constructor() { super("AccountModule"); XhrHttpModule.addDefaultResponseHandler((request) => { const status = request.getStatus(); if (status < 200 || status >= 300) return false; try { const functionExecutionId = request?.getResponseHeader?.(HeaderKey_FunctionExecutionId); XhrHttpModule.logDebug(`${request.key} Function execution id: ${functionExecutionId}`); const jwt = request.getResponseHeader(HeaderKey_JWT); if (jwt) StorageKey_JWT.set(jwt); } catch (e) { XhrHttpModule.logError(`${request.key} - Failed to retrieve headers from xhr call`, e); } return false; }); } onUnauthenticatedResponse = () => { this.logout(); }; getAccounts() { return this.accounts; } getLoggedStatus = () => this.status; isStatus = (status) => this.status === status; setLoggedStatus = (newStatus) => { if (this.status === newStatus) return; const pervStatus = this.status; this.status = newStatus; this.logInfo(`Login status changes: ${LoggedStatus[pervStatus]} => ${LoggedStatus[newStatus]}`); this.dispatchUI_loginChanged.dispatchUI(); this.dispatchUI_loginChanged.dispatchModule(); }; init() { XhrHttpModule.addDefaultHeader(AUTHENTICATION_KEY, () => `${AUTHENTICATION_PREFIX} ${StorageKey_JWT.get()}`); this.dispatchUI_loginChanged = new ThunderDispatcher("onLoginStatusUpdated"); const email = BaseComponent.getQueryParameter(QueryParam_Email); const jwt = BaseComponent.getQueryParameter(QueryParam_JWT); if (email && jwt) { StorageKey_JWT.set(jwt); StorageKey_UserEmail.set(email); BrowserHistoryModule.removeQueryParam(QueryParam_Email); BrowserHistoryModule.removeQueryParam(QueryParam_JWT); } if (StorageKey_JWT.get()) return AccountModule.validateToken(); this.logDebug("login out user.... "); this.setLoggedStatus(LoggedStatus.LOGGED_OUT); } create(request) { XhrHttpModule .createRequest(HttpMethod.POST, RequestKey_AccountCreate) .setRelativeUrl("/v1/account/create") .setJsonBody(request) .setLabel(`User register...`) .setOnError("Error registering user") .execute(async (response) => { ToastModule.toastSuccess(`Account successfully created with email: ${response.email}`); }); } login(request) { XhrHttpModule .createRequest(HttpMethod.POST, RequestKey_AccountLogin) .setRelativeUrl("/v1/account/login") .setJsonBody(request) .setLabel(`User login with password...`) .setOnError("Error login user") .execute(async (response) => { this.setLoginInfo(response); }); } setLoginInfo(response) { StorageKey_JWT.set(response.jwt); StorageKey_UserEmail.set(response.email); this.setLoggedStatus(LoggedStatus.LOGGED_IN); } loginSAML(request) { XhrHttpModule .createRequest(HttpMethod.GET, RequestKey_AccountLoginSAML) .setRelativeUrl("/v1/account/login-saml") .setUrlParams(request) .setLabel(`User login SAML...`) .setOnError('Error login user') .execute(async (response) => { if (!response.loginUrl) return; window.location.href = response.loginUrl; }); } validateToken = () => { XhrHttpModule .createRequest(HttpMethod.GET, RequestKey_ValidateSession) .setLabel(`Validate token...`) .setRelativeUrl("/v1/account/validate") .setOnError((request, _resError) => { if (request.getStatus() === 0) { ToastModule.toastError("Cannot reach Server... trying in 30 sec"); setTimeout(() => AccountModule.validateToken(), 30 * Second); return; } StorageKey_JWT.delete(); return AccountModule.setLoggedStatus(LoggedStatus.LOGGED_OUT); }) .execute(async () => { AccountModule.setLoggedStatus(LoggedStatus.LOGGED_IN); }); }; logout = (url) => { StorageKey_JWT.delete(); if (url) return window.location.href = url; this.setLoggedStatus(LoggedStatus.LOGGED_OUT); }; listUsers = () => { XhrHttpModule .createRequest(HttpMethod.GET, RequestKey_ValidateSession) .setLabel(`Fetching users...`) .setRelativeUrl("/v1/account/query") .execute(async (res) => { this.accounts = res.accounts.filter(account => account._id); dispatch_onAccountsLoaded.dispatchUI(); }); }; } export const AccountModule = new AccountModule_Class(); //# sourceMappingURL=AccountModule.js.map