djAuth.ts
4.81 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import { KJUR } from 'jsrsasign';
import type { AxiosAdapter } from 'axios';
import { createRopClient } from './index';
import { loadDjLoginConfig, type DjLoginConfig } from './djConfig';
/** 与当前项目的 uj_token / session 分开保存,避免两个系统相互覆盖。 */
export const DJ_SESSION_STORAGE_KEY = 'uj_dj_session';
export const DJ_ACCOUNT_STORAGE_KEY = 'uj_dj_account';
interface DjAccountOption {
sessionId?: string;
loginAccout?: string;
loginAccount?: string;
merchantNo?: string | number;
}
interface DjLoginData extends Record<string, unknown> {
sessionId?: string;
loginToken?: string;
accountList?: DjAccountOption[];
}
interface DjSelectionData {
sessionId?: string;
}
export interface DjLoginServiceConfig extends DjLoginConfig {
adapter?: AxiosAdapter;
}
export interface DjLoginSession {
sessionId: string;
account: Record<string, unknown>;
}
function setLocal(key: string, value: string): void {
try {
localStorage.setItem(key, value);
} catch {
// 隐私模式等无法写入本地存储时,不影响当前页面继续使用会话。
}
}
function getLocal(key: string): string | null {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function removeLocal(key: string): void {
try {
localStorage.removeItem(key);
} catch {
/* ignore */
}
}
export function getDjSessionId(): string | null {
return getLocal(DJ_SESSION_STORAGE_KEY);
}
export function getDjAccount(): Record<string, unknown> | null {
const raw = getLocal(DJ_ACCOUNT_STORAGE_KEY);
if (!raw) return null;
try {
const value: unknown = JSON.parse(raw);
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
} catch {
return null;
}
}
export function clearDjLoginStorage(): void {
removeLocal(DJ_SESSION_STORAGE_KEY);
removeLocal(DJ_ACCOUNT_STORAGE_KEY);
}
function hashPassword(password: string): string {
return KJUR.crypto.Util.hashString(password, 'md5').toLowerCase();
}
function assertRopConfig(config: DjLoginServiceConfig): void {
if (!config.appKey || !config.secret) {
throw new Error('嘀加登录缺少应用标识或签名配置,请检查配置中心返回内容');
}
}
function extractSessionId(data: DjLoginData): string | undefined {
return data.sessionId || data.accountList?.[0]?.sessionId;
}
/**
* 创建嘀加登录服务。登录账号固定由独立环境配置读取,不使用当前项目登录表单的账号密码。
*/
export function createDjLoginService(config: DjLoginServiceConfig) {
const clientConfig = {
baseURL: config.baseURL,
appKey: config.appKey,
secret: config.secret,
adapter: config.adapter,
};
async function login(): Promise<DjLoginSession> {
assertRopConfig(config);
const loginClient = createRopClient(clientConfig);
const loginData = await loginClient.post<DjLoginData>({
method: 'dj.api.user.login',
userName: config.account,
password: hashPassword(config.password),
});
let sessionId = extractSessionId(loginData);
if (!sessionId && loginData.accountList?.length) {
const selected = loginData.accountList[0];
const loginAccount = selected.loginAccout ?? selected.loginAccount;
const merchantId = Number(selected.merchantNo);
if (!loginData.loginToken || !loginAccount || !Number.isFinite(merchantId)) {
throw new Error('嘀加登录返回了多个商户,但缺少选择商户所需信息');
}
const selectedData = await loginClient.post<DjSelectionData>({
method: 'dj.api.user.login.select',
loginAccount,
merchantId,
loginToken: loginData.loginToken,
});
sessionId = selectedData.sessionId;
}
if (!sessionId) throw new Error('嘀加登录成功但未返回会话信息');
const sessionClient = createRopClient({
...clientConfig,
getSessionId: () => sessionId,
});
const userInfo = await sessionClient.post<Record<string, unknown>>({
method: 'dj.api.user.info',
});
const account = { ...loginData, userInfo };
setLocal(DJ_SESSION_STORAGE_KEY, sessionId);
setLocal(DJ_ACCOUNT_STORAGE_KEY, JSON.stringify(account));
return { sessionId, account };
}
return { login };
}
let runtimeConfig: Promise<DjLoginServiceConfig> | null = null;
async function getRuntimeConfig(): Promise<DjLoginServiceConfig> {
if (!runtimeConfig) runtimeConfig = loadDjLoginConfig();
try {
return await runtimeConfig;
} catch (error) {
// 网络短暂失败后允许下一次登录重新拉取配置。
runtimeConfig = null;
throw error;
}
}
/** 当前 React 登录页使用的默认嘀加登录服务。 */
export const djLogin = {
async login(): Promise<DjLoginSession> {
return createDjLoginService(await getRuntimeConfig()).login();
},
};