提交 | 用户 | 时间
|
314507
|
1 |
import { useCache, CACHE_KEY } from '@/hooks/web/useCache' |
8e4ab7
|
2 |
import {TokenType} from '@/api/login/types' |
314507
|
3 |
import { decrypt, encrypt } from '@/utils/jsencrypt' |
H |
4 |
|
|
5 |
const { wsCache } = useCache() |
|
6 |
|
|
7 |
const AccessTokenKey = 'ACCESS_TOKEN' |
|
8 |
const RefreshTokenKey = 'REFRESH_TOKEN' |
8e4ab7
|
9 |
const TenantId = 'tenantId' |
314507
|
10 |
|
H |
11 |
// 获取token |
|
12 |
export const getAccessToken = () => { |
|
13 |
// 此处与TokenKey相同,此写法解决初始化时Cookies中不存在TokenKey报错 |
|
14 |
return wsCache.get(AccessTokenKey) ? wsCache.get(AccessTokenKey) : wsCache.get('ACCESS_TOKEN') |
|
15 |
} |
|
16 |
|
|
17 |
// 刷新token |
|
18 |
export const getRefreshToken = () => { |
|
19 |
return wsCache.get(RefreshTokenKey) |
|
20 |
} |
|
21 |
|
|
22 |
// 设置token |
|
23 |
export const setToken = (token: TokenType) => { |
|
24 |
wsCache.set(RefreshTokenKey, token.refreshToken) |
|
25 |
wsCache.set(AccessTokenKey, token.accessToken) |
8e4ab7
|
26 |
wsCache.set(TenantId, import.meta.env.VITE_TENANT_ID) |
314507
|
27 |
} |
H |
28 |
|
|
29 |
// 删除token |
|
30 |
export const removeToken = () => { |
|
31 |
wsCache.delete(AccessTokenKey) |
|
32 |
wsCache.delete(RefreshTokenKey) |
|
33 |
} |
|
34 |
|
|
35 |
/** 格式化token(jwt格式) */ |
|
36 |
export const formatToken = (token: string): string => { |
|
37 |
return 'Bearer ' + token |
|
38 |
} |
|
39 |
// ========== 账号相关 ========== |
|
40 |
|
|
41 |
export type LoginFormType = { |
|
42 |
username: string |
|
43 |
password: string |
|
44 |
rememberMe: boolean |
|
45 |
} |
|
46 |
|
|
47 |
export const getLoginForm = () => { |
|
48 |
const loginForm: LoginFormType = wsCache.get(CACHE_KEY.LoginForm) |
|
49 |
if (loginForm) { |
|
50 |
loginForm.password = decrypt(loginForm.password) as string |
|
51 |
} |
|
52 |
return loginForm |
|
53 |
} |
|
54 |
|
|
55 |
export const setLoginForm = (loginForm: LoginFormType) => { |
|
56 |
loginForm.password = encrypt(loginForm.password) as string |
|
57 |
wsCache.set(CACHE_KEY.LoginForm, loginForm, { exp: 30 * 24 * 60 * 60 }) |
|
58 |
} |
|
59 |
|
|
60 |
export const removeLoginForm = () => { |
|
61 |
wsCache.delete(CACHE_KEY.LoginForm) |
|
62 |
} |
|
63 |
|
|
64 |
// ========== 租户相关 ========== |
|
65 |
|
|
66 |
export const getTenantId = () => { |
|
67 |
return wsCache.get(CACHE_KEY.TenantId) |
|
68 |
} |
|
69 |
|
|
70 |
export const setTenantId = (username: string) => { |
|
71 |
wsCache.set(CACHE_KEY.TenantId, username) |
|
72 |
} |