import {get} from "../utils/request"; import {action, makeObservable, observable, runInAction} from "mobx"; import {RootStore} from "./RootStore"; import type {IUser} from "../models/user"; import {IStudent} from "../models/student"; import {Role} from "../models/role"; export class UserStore { rootStore: RootStore; @observable user: IUser = {authenticated: false}; @observable student?: IStudent; constructor(rootStore: RootStore) { makeObservable(this); this.rootStore = rootStore; } @action.bound updateCurrentUser(callback?: (user: IUser) => void) { this.rootStore.thinkStore.think('updateCurrentUser'); get('/user/current').then((response) => { runInAction(() => { this.user = response; }); if (response.authenticated && response.authorities.some(a => a.authority === Role.STUDENT)) { get('/student/current').then((student) => { runInAction(() => { this.student = student; }); }); } }).finally(() => { runInAction(() => { this.rootStore.thinkStore.completeOne('updateCurrentUser'); if (callback) { callback(this.user); } }); }); } isAdministrator() { return this.user.authenticated && this.user.authorities.some(a => a.authority === Role.ADMINISTRATOR); } init() { this.updateCurrentUser(); console.debug('UserStore initialized'); return this; } }