-
Notifications
You must be signed in to change notification settings - Fork 13
/
User.ts
67 lines (52 loc) · 1.5 KB
/
User.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { Guard } from '@authing/guard';
import { User } from '@kaiyuanshe/kys-service';
import { HTTPClient } from 'koajax';
import { makeObservable, observable } from 'mobx';
import { BaseListModel, toggle } from 'mobx-restful';
import { KYS_SERVICE_HOST } from './index';
const { localStorage } = globalThis;
export const guard = new Guard({
mode: 'modal',
appId: process.env.NEXT_PUBLIC_AUTHING_APP_ID!,
});
export class UserModel extends BaseListModel<User> {
constructor() {
super();
makeObservable(this);
if (!this.session) globalThis.localStorage?.clear();
}
baseURI = 'user';
@observable
session?: User = localStorage?.session && JSON.parse(localStorage.session);
client = new HTTPClient({
baseURI: KYS_SERVICE_HOST,
responseType: 'json',
}).use(({ request }, next) => {
if (this.session?.token)
request.headers = {
...request.headers,
Authorization: `Bearer ${this.session.token}`,
};
return next();
});
saveSession(user: User) {
localStorage.session = JSON.stringify(user);
return (this.session = user);
}
@toggle('uploading')
async signInAuthing(token: string) {
const { body } = await this.client.post<User>(
`${this.baseURI}/session/authing`,
{},
{ Authorization: `Bearer ${token}` },
);
return this.saveSession(body!);
}
@toggle('uploading')
async signOut() {
await guard.logout();
this.session = undefined;
localStorage.clear();
}
}
export default new UserModel();