forked from Starlight-Dev-Team/fanbook-bot-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.ts
70 lines (65 loc) · 2.05 KB
/
config.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
68
69
70
import type { Profile, Session } from '@starlight-dev-team/fanbook-api-sdk/dist/types';
import { defineServiceConfig } from '~~/utils/config';
import type { Config } from '~~/utils/config';
type EnvType =
| 'prod' // 正式环境
| 'pre'; // 灰度环境
const configs: Record<EnvType, Config> = {
prod: defineServiceConfig({}),
pre: defineServiceConfig({
auth: {
maxAge: 5 * 60 * 1000, // 5 min
async isAuthorized() {
try {
await configs.pre.auth?.getProfile();
return true;
} catch {
return false;
}
},
async getProfile() {
const token = useCookie('token').value;
if (!token) throw new Error('No token given');
const req = await useFetch('https://gubfpx.laf.dev/profile', {
method: 'post',
body: {
token,
},
mode: 'cors',
});
const data = toRaw(req.data.value as any);
if (data.error === true) { // 请求返回错误
throw new Error(data.reason ?? 'Request failed');
}
return data as Profile;
},
async redirect() {
await navigateTo('https://a1.fanbook.mobi/open/oauth2/authorize?response_type=code&client_id=474159040155488256', {
external: true,
});
},
async requestAuth() {
if (useRoute().query.code === undefined) {
throw new Error('No given code');
}
const req = await useFetch('https://gubfpx.laf.dev/token', {
method: 'post',
body: {
code: useRoute().query.code,
},
mode: 'cors',
});
const data = toRaw(req.data.value as any);
if (req.error.value) throw new Error('Remote failed');
const session = data as Session;
useCookie('token').value = session.accessToken;
return session.accessToken;
},
},
}),
};
const env = ((): EnvType => {
if (location.origin.includes('pre.fb-bot.')) return 'pre';
else return 'prod';
})();
export const useServiceConfig = () => configs[env];