TDMS/web/src/store/UserStore.ts
2025-02-09 10:59:44 +03:00

78 lines
2.3 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 {Authorities} from "../models/authorities";
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 (this.isStudent) {
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 === Authorities.ADMINISTRATOR.code);
}
@computed
get isStudent() {
return this.user.authenticated && this.user.authorities.some(a => a === Authorities.STUDENT.code);
}
@computed
get isTeacher() {
return this.user.authenticated && this.user.authorities.some(a => a === Authorities.TEACHER.code);
}
@computed
get isCommissionMember() {
return this.user.authenticated && this.user.authorities.some(a => a === Authorities.COMMISSION_MEMBER.code);
}
@computed
get isSecretary() {
return this.user.authenticated && this.user.authorities.some(a => a === Authorities.SECRETARY.code);
}
@computed
get authenticated() {
return this.user.authenticated
}
init() {
this.updateCurrentUser();
console.debug('UserStore initialized');
return this;
}
}