151 lines
5.0 KiB
TypeScript
151 lines
5.0 KiB
TypeScript
import { computed, ref } from 'vue'
|
|||
|
|
import { defineStore } from 'pinia'
|
||
|
|
import type { CurrentUser } from '@chongchong/shared'
|
||
|
|
import { http, registerAuthRefreshHandler, unwrapApiResponse, type ApiEnvelope } from '@/api/http'
|
||
|
|
import { listPlatformPermissions, type PlatformPermissionResource } from '@/api/platformIam'
|
||
|
|
import { decodeJwtClaims } from '@/utils/jwt'
|
||
|
|
|
||
|
|
const TOKEN_KEY = 'cc-admin-token'
|
||
|
|
const REFRESH_TOKEN_KEY = 'cc-admin-refresh-token'
|
||
|
|
const PERMISSION_CODES_KEY = 'cc-admin-permission-codes'
|
||
|
|
|
||
|
|
interface LoginResponse {
|
||
|
|
tokenType: string
|
||
|
|
accessToken: string
|
||
|
|
expiresIn: number
|
||
|
|
refreshToken: string
|
||
|
|
refreshExpiresIn: number
|
||
|
|
}
|
||
|
|
|
||
|
|
function sessionFromToken(token: string) {
|
||
|
|
const claims = decodeJwtClaims(token)
|
||
|
|
if (claims.app_code !== 'PLATFORM') throw new Error('账号不属于当前应用端')
|
||
|
|
if (claims.exp && claims.exp * 1000 <= Date.now()) throw new Error('登录状态已过期,请重新登录')
|
||
|
|
return {
|
||
|
|
user: {
|
||
|
|
id: String(claims.user_id ?? ''),
|
||
|
|
name: claims.username || '平台用户',
|
||
|
|
account: claims.username || '',
|
||
|
|
roles: claims.roles ?? [],
|
||
|
|
} satisfies CurrentUser,
|
||
|
|
permissions: claims.permissions ?? [],
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export const useAuthStore = defineStore('admin-auth', () => {
|
||
|
|
const token = ref(localStorage.getItem(TOKEN_KEY) || '')
|
||
|
|
const refreshToken = ref(localStorage.getItem(REFRESH_TOKEN_KEY) || '')
|
||
|
|
const user = ref<CurrentUser | null>(null)
|
||
|
|
const permissions = ref<string[]>([])
|
||
|
|
const permissionResources = ref<PlatformPermissionResource[]>([])
|
||
|
|
const isServerSession = ref(false)
|
||
|
|
|
||
|
|
if (token.value) {
|
||
|
|
try {
|
||
|
|
const session = sessionFromToken(token.value)
|
||
|
|
const cachedPermissions = JSON.parse(localStorage.getItem(PERMISSION_CODES_KEY) || '[]') as unknown
|
||
|
|
if (!Array.isArray(cachedPermissions)) throw new Error('权限缓存格式无效')
|
||
|
|
user.value = session.user
|
||
|
|
permissions.value = session.permissions.filter((code) => cachedPermissions.includes(code))
|
||
|
|
isServerSession.value = true
|
||
|
|
} catch {
|
||
|
|
token.value = ''
|
||
|
|
refreshToken.value = ''
|
||
|
|
localStorage.removeItem(TOKEN_KEY)
|
||
|
|
localStorage.removeItem(REFRESH_TOKEN_KEY)
|
||
|
|
localStorage.removeItem(PERMISSION_CODES_KEY)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
const isAuthenticated = computed(() => Boolean(token.value))
|
||
|
|
const permissionCodes = computed<ReadonlySet<string>>(() => new Set(permissions.value))
|
||
|
|
|
||
|
|
async function applySession(result: LoginResponse) {
|
||
|
|
const session = sessionFromToken(result.accessToken)
|
||
|
|
token.value = result.accessToken
|
||
|
|
refreshToken.value = result.refreshToken
|
||
|
|
user.value = session.user
|
||
|
|
isServerSession.value = true
|
||
|
|
localStorage.setItem(TOKEN_KEY, token.value)
|
||
|
|
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken.value)
|
||
|
|
try {
|
||
|
|
permissionResources.value = await listPlatformPermissions()
|
||
|
|
const activeResourceCodes = new Set(permissionResources.value
|
||
|
|
.filter((resource) => resource.status === 'ACTIVE')
|
||
|
|
.map((resource) => resource.permissionCode))
|
||
|
|
permissions.value = session.permissions.filter((code) => activeResourceCodes.has(code))
|
||
|
|
localStorage.setItem(PERMISSION_CODES_KEY, JSON.stringify(permissions.value))
|
||
|
|
} catch (error) {
|
||
|
|
clearSession()
|
||
|
|
throw error
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function clearSession() {
|
||
|
|
token.value = ''
|
||
|
|
refreshToken.value = ''
|
||
|
|
user.value = null
|
||
|
|
permissions.value = []
|
||
|
|
permissionResources.value = []
|
||
|
|
isServerSession.value = false
|
||
|
|
localStorage.removeItem(TOKEN_KEY)
|
||
|
|
localStorage.removeItem(REFRESH_TOKEN_KEY)
|
||
|
|
localStorage.removeItem(PERMISSION_CODES_KEY)
|
||
|
|
}
|
||
|
|
|
||
|
|
async function login(account: string, password: string) {
|
||
|
|
const response = await http.post<ApiEnvelope<LoginResponse>, ApiEnvelope<LoginResponse>>(
|
||
|
|
'/auth/login',
|
||
|
|
{ username: account, password },
|
||
|
|
)
|
||
|
|
const result = unwrapApiResponse<LoginResponse>(response)
|
||
|
|
await applySession(result)
|
||
|
|
}
|
||
|
|
|
||
|
|
async function refreshSession() {
|
||
|
|
if (!refreshToken.value) throw new Error('刷新令牌不存在,请重新登录')
|
||
|
|
try {
|
||
|
|
const response = await http.post<ApiEnvelope<LoginResponse>, ApiEnvelope<LoginResponse>>(
|
||
|
|
'/auth/refresh',
|
||
|
|
{ refreshToken: refreshToken.value },
|
||
|
|
)
|
||
|
|
const result = unwrapApiResponse<LoginResponse>(response)
|
||
|
|
await applySession(result)
|
||
|
|
} catch (error) {
|
||
|
|
clearSession()
|
||
|
|
throw error
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
registerAuthRefreshHandler(async () => {
|
||
|
|
await refreshSession()
|
||
|
|
if (!token.value) throw new Error('登录状态刷新失败')
|
||
|
|
return token.value
|
||
|
|
})
|
||
|
|
|
||
|
|
function logout() {
|
||
|
|
const accessToken = token.value
|
||
|
|
const tokenToRevoke = refreshToken.value
|
||
|
|
clearSession()
|
||
|
|
if (accessToken && tokenToRevoke) {
|
||
|
|
void http.post('/auth/logout', { refreshToken: tokenToRevoke }, {
|
||
|
|
headers: { Authorization: `Bearer ${accessToken}` },
|
||
|
|
}).catch(() => undefined)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return {
|
||
|
|
token,
|
||
|
|
refreshToken,
|
||
|
|
user,
|
||
|
|
permissions,
|
||
|
|
permissionResources,
|
||
|
|
isServerSession,
|
||
|
|
permissionCodes,
|
||
|
|
isAuthenticated,
|
||
|
|
login,
|
||
|
|
refreshSession,
|
||
|
|
logout,
|
||
|
|
}
|
||
|
|
})
|