import axios from 'axios'; import constants from '../constants'; import { IAPIObject } from './IAPIObject'; const { API_ROOT, api_path } = constants; class UserLoginResponse { /** @type {string} */ session_key; /** @type {string} */ openid_login; /** @type {number} */ id; } 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 }