This commit is contained in:
2026-09-20 22:19:02 +08:00
parent 1e171ec81c
commit 4ed1faea5f
3 changed files with 71 additions and 20 deletions
+16 -19
View File
@@ -1,30 +1,15 @@
import { reactive } from 'vue'
import { resetPickingSession } from '@/stores/picking.js'
import { PLATFORM_API_ROOT } from '@/config/runtime.js'
import { decodeAccessToken } from '@/utils/jwt-claims.js'
export { decodeAccessToken } from '@/utils/jwt-claims.js'
const SESSION_KEY = 'pda-auth-session'
const LOGIN_PREFERENCE_KEY = 'pda-login-account-preference'
export const session = reactive({ currentUser: null, token: '', refreshToken: '', tenantId: '', apiBase: PLATFORM_API_ROOT })
function decodeBase64Url(value) {
const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')
if (typeof atob === 'function') return decodeURIComponent(Array.from(atob(padded), (char) => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`).join(''))
throw new Error('当前运行环境无法解析登录令牌')
}
export function decodeAccessToken(token) {
const payload = String(token || '').split('.')[1]
if (!payload) throw new Error('登录响应中的 accessToken 格式无效')
try {
return JSON.parse(decodeBase64Url(payload))
} catch (error) {
if (error.message === '当前运行环境无法解析登录令牌') throw error
throw new Error('登录响应中的 accessToken 无法解析')
}
}
export function isAccessTokenExpiring(token = session.token, skewSeconds = 30) {
try {
const expiresAt = Number(decodeAccessToken(token).exp || 0) * 1000
@@ -137,7 +122,19 @@ export function restoreSession() {
const claims = decodeAccessToken(saved.token)
if (claims.app_code !== 'PLATFORM') throw new Error('登录域无效')
if (claims.exp && claims.exp * 1000 <= Date.now() && !saved.refreshToken) throw new Error('登录状态已过期')
Object.assign(session, saved, { apiBase: saved.apiBase || PLATFORM_API_ROOT })
const savedUser = saved.currentUser || {}
Object.assign(session, saved, {
currentUser: {
...savedUser,
id: String(claims.user_id ?? savedUser.id ?? ''),
name: claims.username || savedUser.name || '仓库作业员',
role: Array.isArray(claims.roles) ? claims.roles.join('、') : (savedUser.role || ''),
roles: claims.roles || savedUser.roles || []
},
tenantId: claims.tenant_id == null ? (saved.tenantId || '') : String(claims.tenant_id),
apiBase: saved.apiBase || PLATFORM_API_ROOT
})
persistSession()
return true
} catch (_) {
signOut()