auth-deps.ts
3.19 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* 登录 / 登出协议的 host 能力装配。
*
* 内核独占的运行时(签名、axios、令牌、会话、权限 Context、store)集中在这里
* 注入给协议,业务实现只依赖 LoginDeps 这个稳定接口,不反向 import host。
* 登录组件与统一登出共用同一份装配,避免两处各写一套、行为漂移。
*/
import { auth, menu as menuApi, ensureSignReady } from '@/api';
import { setToken, clearToken } from '@/api/core/token';
import { clearLoginSession, saveLoginSession } from '@/access/session';
import { queryClient } from '@/queryClient';
import { useAppStore } from '@/store/useAppStore';
import type { LoginDeps } from '@venus/contracts';
export interface MessageSink {
(text: string, kind?: 'success' | 'error' | 'warning' | 'info'): void;
}
/**
* 装配 host 能力。applyAccess 与 setCurrentUser 在登录组件里由 Hook 提供;
* 登出场景不需要它们,故这里做成可选。
*/
export function createLoginDeps(options: {
navigate: (path: string) => void;
message: MessageSink;
applyAccess?: LoginDeps['applyAccess'];
setCurrentUser?: LoginDeps['setCurrentUser'];
}): LoginDeps {
const { navigate, message, applyAccess, setCurrentUser } = options;
return {
defaultReady: () => ensureSignReady(),
defaultRequest: (credentials) =>
auth.login({ account: credentials.account, password: credentials.password }),
defaultNormalize: (raw) => {
const r = (raw ?? {}) as Record<string, unknown>;
const arr = (v: unknown): string[] =>
Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
return {
token: String(r['token'] ?? ''),
tokenType: String(r['tokenType'] ?? 'Bearer'),
expireAt: String(r['expireAt'] ?? ''),
userId: (r['userId'] ?? 0) as string | number,
account: String(r['account'] ?? ''),
name: String(r['name'] ?? ''),
orgId: (r['orgId'] ?? 0) as string | number,
dataScope: Number(r['dataScope'] ?? 0),
roleCodes: arr(r['roleCodes']),
permCodes: arr(r['permCodes']),
loginToken: typeof r['loginToken'] === 'string' ? r['loginToken'] : undefined,
sessionId: typeof r['sessionId'] === 'string' ? r['sessionId'] : undefined,
needChangePassword: r['needChangePassword'] === true,
...r,
};
},
setToken,
saveSession: (session) => saveLoginSession(session),
clearCaches: () => {
menuApi.clearCache();
auth.clearCache();
},
applyAccess: applyAccess ?? (() => undefined),
setCurrentUser: setCurrentUser ?? ((user) => useAppStore.getState().login(user)),
navigate,
message,
clearLocal: () => {
useAppStore.getState().logout();
clearToken();
clearLoginSession();
queryClient.clear();
menuApi.clearCache();
auth.clearCache();
},
serverLogout: () => auth.logout(),
};
}
/** 把 antd App.useApp() 的 message 适配成协议用的简单签名。 */
export function toMessageSink(api: {
success: (text: string) => void;
error: (text: string) => void;
warning: (text: string) => void;
info: (text: string) => void;
}): MessageSink {
return (text, kind = 'info') => api[kind](text);
}