58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
import {get} from "../utils/request";
|
|
import {action, computed, 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<IUser>('/user/current').then((response) => {
|
|
runInAction(() => {
|
|
this.user = response;
|
|
});
|
|
if (response.authenticated && response.authorities.some(a => a.authority === Role.STUDENT)) {
|
|
get<IStudent>('/student/current').then((student) => {
|
|
runInAction(() => {
|
|
this.student = student;
|
|
});
|
|
});
|
|
}
|
|
}).finally(() => {
|
|
runInAction(() => {
|
|
this.rootStore.thinkStore.completeOne('updateCurrentUser');
|
|
if (callback) {
|
|
callback(this.user);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
@computed
|
|
get isAdministrator() {
|
|
return this.user.authenticated && this.user.authorities.some(a => a.authority === Role.ADMINISTRATOR);
|
|
}
|
|
|
|
@computed
|
|
get authenticated() {
|
|
return this.user.authenticated
|
|
}
|
|
|
|
init() {
|
|
this.updateCurrentUser();
|
|
console.debug('UserStore initialized');
|
|
return this;
|
|
}
|
|
}
|