cyywl_server/yudao-ui-admin-vue3/src/utils/auth.ts

102 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-07-18 19:06:37 +08:00
import { useCache } from '@/hooks/web/useCache'
import { TokenType } from '@/api/login/types'
2022-07-19 22:33:54 +08:00
import { decrypt, encrypt } from '@/utils/jsencrypt'
2022-07-18 19:06:37 +08:00
const { wsCache } = useCache()
const AccessTokenKey = 'ACCESS_TOKEN'
const RefreshTokenKey = 'REFRESH_TOKEN'
// 获取token
2022-07-19 22:33:54 +08:00
export const getAccessToken = () => {
2022-07-18 19:06:37 +08:00
// 此处与TokenKey相同此写法解决初始化时Cookies中不存在TokenKey报错
return wsCache.get('ACCESS_TOKEN')
}
// 刷新token
2022-07-19 22:33:54 +08:00
export const getRefreshToken = () => {
2022-07-18 19:06:37 +08:00
return wsCache.get(RefreshTokenKey)
}
// 设置token
2022-07-19 22:33:54 +08:00
export const setToken = (token: TokenType) => {
2022-07-18 19:06:37 +08:00
wsCache.set(RefreshTokenKey, token.refreshToken, { exp: token.expiresTime })
wsCache.set(AccessTokenKey, token.accessToken)
}
// 删除token
2022-07-19 22:33:54 +08:00
export const removeToken = () => {
2022-07-18 19:06:37 +08:00
wsCache.delete(AccessTokenKey)
wsCache.delete(RefreshTokenKey)
}
2022-07-19 22:33:54 +08:00
// ========== 账号相关 ==========
const UsernameKey = 'USERNAME'
const PasswordKey = 'PASSWORD'
const RememberMeKey = 'REMEMBER_ME'
export const getUsername = () => {
return wsCache.get(UsernameKey)
}
export const setUsername = (username: string) => {
wsCache.set(UsernameKey, username)
}
export const removeUsername = () => {
wsCache.delete(UsernameKey)
}
export const getPassword = () => {
const password = wsCache.get(PasswordKey)
return password ? decrypt(password) : undefined
}
export const setPassword = (password: string) => {
wsCache.set(PasswordKey, encrypt(password))
}
export const removePassword = () => {
wsCache.delete(PasswordKey)
}
export const getRememberMe = () => {
return wsCache.get(RememberMeKey) === 'true'
}
export const setRememberMe = (rememberMe: string) => {
wsCache.set(RememberMeKey, rememberMe)
}
export const removeRememberMe = () => {
wsCache.delete(RememberMeKey)
}
// ========== 租户相关 ==========
const TenantIdKey = 'TENANT_ID'
const TenantNameKey = 'TENANT_NAME'
export const getTenantName = () => {
return wsCache.get(TenantNameKey)
}
export const setTenantName = (username: string) => {
wsCache.set(TenantNameKey, username)
}
export const removeTenantName = () => {
wsCache.delete(TenantNameKey)
}
export const getTenantId = () => {
return wsCache.get(TenantIdKey)
}
export const setTenantId = (username: string) => {
wsCache.set(TenantIdKey, username)
}
export const removeTenantId = () => {
wsCache.delete(TenantIdKey)
}