session.ts
2.49 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
/** 登录会话:令牌、用户信息和权限均属于访问控制范围。 */
export interface LoginSession {
token: string;
tokenType: 'Bearer' | string;
expireAt: string;
userId: number;
account: string;
name: string;
orgId: number;
dataScope: number;
roleCodes: string[];
permCodes: string[];
}
const SESSION_KEY = 'session';
/** 用户信息及权限的统一本地存储键。 */
const USER_INFO_KEY = 'uj-auth-user-info';
export function saveLoginSession(session: LoginSession) {
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
}
export function getLoginSession(): LoginSession | undefined {
const raw = localStorage.getItem(SESSION_KEY);
if (!raw) return undefined;
try {
const session = JSON.parse(raw) as LoginSession;
if (
!session.token ||
(session.expireAt && new Date(session.expireAt).getTime() <= Date.now())
) {
localStorage.removeItem(SESSION_KEY);
return undefined;
}
return session;
} catch {
localStorage.removeItem(SESSION_KEY);
return undefined;
}
}
export function getAuthorization() {
const session = getLoginSession();
return session ? `${session.tokenType || 'Bearer'} ${session.token}` : undefined;
}
export function saveUserInfo(info: unknown, fallbackPermCodes: string[] = []) {
const userInfo =
info && typeof info === 'object' && !Array.isArray(info)
? (info as Record<string, unknown>)
: {};
const permCodes = Array.isArray(userInfo.permCodes)
? userInfo.permCodes.filter((code): code is string => typeof code === 'string')
: fallbackPermCodes;
localStorage.setItem(USER_INFO_KEY, JSON.stringify({ ...userInfo, permCodes }));
}
/** 获取本地用户信息,权限按钮以其中的 permCodes 为唯一依据。 */
export function getUserInfo(): Record<string, unknown> | undefined {
const raw = localStorage.getItem(USER_INFO_KEY);
if (!raw) return undefined;
try {
const userInfo = JSON.parse(raw);
return userInfo && typeof userInfo === 'object' && !Array.isArray(userInfo)
? (userInfo as Record<string, unknown>)
: undefined;
} catch {
localStorage.removeItem(USER_INFO_KEY);
return undefined;
}
}
export function getUserPermCodes(): string[] {
const permCodes = getUserInfo()?.permCodes;
return Array.isArray(permCodes)
? permCodes.filter((code): code is string => typeof code === 'string')
: [];
}
export function clearLoginSession() {
localStorage.removeItem(SESSION_KEY);
localStorage.removeItem(USER_INFO_KEY);
}