import axios from 'axios'; import constants from '../constants'; const { API_ROOT, api_path } = constants; class UserLoginResponse { /** @type {string} */ session_key; /** @type {string} */ openid_login; /** @type {number} */ id; } class IAPIObject { /** * Local storage key used to save data. * @type {string} */ static storage_key = undefined; static _checkStorageSupport() { if (this.storage_key === undefined) { throw Error('This doesn\'t support local storage'); } } _getStorageKey() { return Object.getPrototypeOf(this).constructor.storage_key; } _IcheckStorageSupport() { if (this._getStorageKey() === undefined) { throw Error('This doesn\'t support local storage'); } } /** @returns {ThisType} */ static restoreFromLocalStorage() { _checkStorageSupport(); if (!window.sessionStorage.getItem(this.storage_key)) return false; return new APIToken(window.sessionStorage.getItem(this.storage_key)); } /** @returns {boolean} */ static isCached() { this._checkStorageSupport(); if (window.sessionStorage.getItem(this.storage_key)) { return true; } return false; } /** * Save this object to local storage * @throws {QuotaExceededError} * @returns {void} */ saveToLocalStorage() { this._IcheckStorageSupport(); window.sessionStorage.setItem(this._getStorageKey(), JSON.stringify(this)); } } class APIToken extends IAPIObject { static storage_key = 'pairent_api_key'; constructor(data) { super(); this.user = data.user; this.key = data.key; this.expires = data.expires; this.ip = data.ip; } /** @type {number} */ user; /** @type {string} */ key; /** A Unix timestamp (when the token will expire) * @type {number} */ expires; /** @type {string} */ ip; } class User extends IAPIObject { isLoggedIn() { return false; } static storage_key = 'pairent_user_data'; constructor(data) { super(); for (const key in data) { this[key] = data[key]; } } static restoreFromLocalStorage() { } /** * @param {string} id * @returns {User} */ static async getById(id) { const data = await axios.get(API_ROOT + '/api/user/get', { params: { id } }); if (data.data['error']) throw new Error(data.data['error']); return new User(data.data); } /** @param {import('oidc-client-ts').SigninResponse} response */ static async login(response) { if (response.error !== null) { throw new Error(response.error + ': ' + response.error_description); return; } const data = await axios.post(api_path('/api/auth/user/login'), response); if (data.status !== 200) { return false; } if (!data.data.error) { new APIToken(data.data.token).saveToLocalStorage(); new User(data.data.user_data).saveToLocalStorage(); } return data.data; } } export { User, UserLoginResponse }