56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
import { STORAGE_KEYS } from './config'
|
|
|
|
export interface TokenData {
|
|
accessToken: string
|
|
refreshToken: string
|
|
expireTime: number
|
|
}
|
|
|
|
export function getAccessToken(): string {
|
|
return wx.getStorageSync(STORAGE_KEYS.ACCESS_TOKEN) || ''
|
|
}
|
|
|
|
export function getRefreshToken(): string {
|
|
return wx.getStorageSync(STORAGE_KEYS.REFRESH_TOKEN) || ''
|
|
}
|
|
|
|
export function getExpireTime(): number {
|
|
return wx.getStorageSync(STORAGE_KEYS.EXPIRE_TIME) || 0
|
|
}
|
|
|
|
export function setTokens(data: TokenData): void {
|
|
wx.setStorageSync(STORAGE_KEYS.ACCESS_TOKEN, data.accessToken)
|
|
wx.setStorageSync(STORAGE_KEYS.REFRESH_TOKEN, data.refreshToken)
|
|
wx.setStorageSync(STORAGE_KEYS.EXPIRE_TIME, data.expireTime)
|
|
}
|
|
|
|
export function clearTokens(): void {
|
|
wx.removeStorageSync(STORAGE_KEYS.ACCESS_TOKEN)
|
|
wx.removeStorageSync(STORAGE_KEYS.REFRESH_TOKEN)
|
|
wx.removeStorageSync(STORAGE_KEYS.EXPIRE_TIME)
|
|
}
|
|
|
|
export function isLoggedIn(): boolean {
|
|
return !!getAccessToken()
|
|
}
|
|
|
|
// token 过期提前量(秒):提前 30s 视为过期,避免请求在途时刚好失效
|
|
const EXPIRE_LEAD_SECONDS = 30
|
|
|
|
/**
|
|
* access token 是否已过期(仅用于请求前预刷新,不参与登录态判定)
|
|
* expire_time 单位兼容秒与毫秒:数值大于 1e12 视为毫秒时间戳。
|
|
*/
|
|
export function isTokenExpired(): boolean {
|
|
const expireTime = getExpireTime()
|
|
if (!expireTime) return false // 未记录过期时间时不臆测,交给后端判定
|
|
|
|
const isMillisecond = expireTime > 1e12
|
|
const expireMs = isMillisecond ? expireTime : expireTime * 1000
|
|
return Date.now() + EXPIRE_LEAD_SECONDS * 1000 >= expireMs
|
|
}
|
|
|
|
export function clearUserInfo(): void {
|
|
wx.removeStorageSync(STORAGE_KEYS.USER_INFO)
|
|
}
|