import { ChangePasswordFormData, EditableUserAttributes, ProfileData, ProfileFormData, UserApiData, UserCreateData, UserInfoPayload, UsersInfoResponse, } from '../../interfaces/user.interface' import { Api } from '../api' import { CONTENT_TYPES } from '.' export const USERS_API = '/service/users' export class Auth { api: Api constructor(api: Api) { this.api = api } // This endpoint is the original profile data but // it is wrapped by registration.getMyProfile that provides // additional data like email confirmation. async getMyProfile(useCache = true) { const user = await this.api.apisauce.get( `${USERS_API}/my-profile`, undefined, { cache: useCache ? undefined : false, id: `my-profile`, }, ) if ( !user.ok || !user.data || user.headers?.['content-type'].indexOf('text/html') !== -1 ) { throw new Error('Not logged in') } return user.data } async getUser(username: string): Promise { const userApi = await this.api.apisauce.get( `${USERS_API}/${username}`, {}, { headers: { Accept: 'application/json, text/plain, */*', }, }, ) if (!userApi.ok || !userApi.data) { throw new Error(`Unable to load user data for ${username}`) } return userApi.data } async getUsers( userData: UserInfoPayload, ) { const url = `${USERS_API}/info-about` const { data, ok } = await this.api.apisauce.post< UsersInfoResponse >(url, userData, { headers: { 'Content-type': CONTENT_TYPES.BATCH_USERS, Accept: 'application/json, text/plain, */*', }, }) if (!ok || !data) { throw new Error('Cannot load user data') } for (const uid in data) { if (data[uid] && typeof data[uid] === 'object' && "uid" in (data[uid] as Record)) { (data[uid] as { uid: string }).uid = uid } } return data } async login(username: string, password: string): Promise { const loginRequest = await this.api.apisauce.post('/login', { username, password, }) if ( !loginRequest.ok || loginRequest.headers?.['content-type']?.includes('text/html') ) { throw new Error('Incorrect credentials') } try { const user = await this.getMyProfile(false) return user } catch (e) { throw new Error('Login error') } } async updateUser(data: Partial | ChangePasswordFormData) { return this.api.apisauce.patch(`${USERS_API}`, data) } create(userData: UserCreateData) { return this.api.apisauce.post(`${USERS_API}`, userData, { headers: { 'Content-type': CONTENT_TYPES.USER_CREATE, }, }) } }