feat(小程序): 修复运行时与登录链路

This commit is contained in:
stu2not
2026-04-22 17:25:03 +08:00
parent 24b1d1025b
commit d7df6f565c
12 changed files with 297 additions and 426 deletions

View File

@@ -0,0 +1,72 @@
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)
}