73 lines
2.0 KiB
TypeScript
73 lines
2.0 KiB
TypeScript
import Taro from '@tarojs/taro'
|
|
|
|
const TOKEN_KEY = 'token'
|
|
const TOKEN_TYPE_KEY = 'token_type'
|
|
const USER_ID_KEY = 'user_id'
|
|
const EXPIRES_IN_KEY = 'expires_in'
|
|
const TOKEN_EXPIRES_AT_KEY = 'token_expires_at'
|
|
const LOGIN_PAGE_URL = '/pages/login/index'
|
|
|
|
let redirectingToLogin = false
|
|
|
|
export interface StoredLoginSession {
|
|
access_token: string
|
|
token_type: string
|
|
expires_in: number
|
|
user_id: number
|
|
}
|
|
|
|
export function saveLoginSession(session: StoredLoginSession): void {
|
|
const expiresAt = Date.now() + Math.max(session.expires_in, 0) * 1000
|
|
Taro.setStorageSync(TOKEN_KEY, session.access_token)
|
|
Taro.setStorageSync(TOKEN_TYPE_KEY, session.token_type)
|
|
Taro.setStorageSync(USER_ID_KEY, session.user_id)
|
|
Taro.setStorageSync(EXPIRES_IN_KEY, session.expires_in)
|
|
Taro.setStorageSync(TOKEN_EXPIRES_AT_KEY, expiresAt)
|
|
}
|
|
|
|
export function clearLoginSession(): void {
|
|
Taro.removeStorageSync(TOKEN_KEY)
|
|
Taro.removeStorageSync(TOKEN_TYPE_KEY)
|
|
Taro.removeStorageSync(USER_ID_KEY)
|
|
Taro.removeStorageSync(EXPIRES_IN_KEY)
|
|
Taro.removeStorageSync(TOKEN_EXPIRES_AT_KEY)
|
|
}
|
|
|
|
function getTokenExpiresAt(): number {
|
|
const rawValue = Number(Taro.getStorageSync(TOKEN_EXPIRES_AT_KEY) || 0)
|
|
return Number.isFinite(rawValue) ? rawValue : 0
|
|
}
|
|
|
|
export function getToken(): string {
|
|
const token = Taro.getStorageSync(TOKEN_KEY) || ''
|
|
if (!token) return ''
|
|
|
|
const expiresAt = getTokenExpiresAt()
|
|
if (expiresAt > 0 && Date.now() >= expiresAt) {
|
|
clearLoginSession()
|
|
return ''
|
|
}
|
|
|
|
return token
|
|
}
|
|
|
|
export function getCurrentUserId(): number {
|
|
if (!getToken()) return 0
|
|
return Number(Taro.getStorageSync(USER_ID_KEY) || 0)
|
|
}
|
|
|
|
export function handleUnauthorized(options: { redirect?: boolean } = {}): void {
|
|
const { redirect = true } = options
|
|
clearLoginSession()
|
|
|
|
if (!redirect || redirectingToLogin) return
|
|
|
|
redirectingToLogin = true
|
|
setTimeout(() => {
|
|
Taro.reLaunch({ url: LOGIN_PAGE_URL })
|
|
setTimeout(() => {
|
|
redirectingToLogin = false
|
|
}, 600)
|
|
}, 120)
|
|
}
|