Files
rustfs-console/composables/useAuth.ts
T
overtrue 0598f8065f refactor: 修复 API 客户端 composables 滥用和硬编码路径问题
- 修复 lib/api-client.ts 中在类方法中直接调用 composables 的问题
- 添加 ApiErrorHandler 错误处理器,通过依赖注入方式处理 401 错误
- 创建路由工具函数 utils/routes.ts,统一管理路由路径
- 修复 composables/useAuth.ts 中的硬编码路径,使用工具函数
- 修复 components/copy-input.vue 的生命周期问题,在 onMounted 中创建 ClipboardJS 实例
- 修复 plugins/03.s3.ts 中的错误处理,使用 navigateTo 替代直接操作 window.location
- 修复 pages/config.vue 中的硬编码路径
- 添加 composables/useFormValidation.ts、useAsyncOperation.ts、useErrorHandler.ts 工具函数(供后续使用)
- 添加 types/api.ts 类型定义
2025-10-31 22:50:59 +08:00

71 lines
1.7 KiB
TypeScript

import type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@aws-sdk/types'
import { getStsToken } from '~/lib/sts'
import type { SiteConfig } from '~/types/config'
import { getLoginRoute } from '~/utils/routes'
interface Credentials {
AccessKeyId?: string
SecretAccessKey?: string
SessionToken?: string
Expiration?: string
}
export function useAuth() {
const store = useLocalStorage('auth.credentials', {})
const setCredentials = (credentials: Credentials) => {
store.value = credentials
}
const getCredentials = () => {
if (!isValidCredentials(store.value)) {
return
}
return store.value
}
const isExpired = (expiration: string) => (expiration ? new Date(expiration) < new Date() : false)
const isValidCredentials = (credentials: Credentials) => {
return (
!!credentials?.AccessKeyId &&
!!credentials?.SecretAccessKey &&
!!credentials?.SessionToken &&
credentials?.Expiration &&
!isExpired(credentials.Expiration)
)
}
const login = async (
credentials: AwsCredentialIdentity | AwsCredentialIdentityProvider,
customConfig?: SiteConfig
) => {
const credentialsResponse = await getStsToken(credentials, 'arn:aws:iam::*:role/Admin', customConfig)
setCredentials({
...credentialsResponse,
Expiration: credentialsResponse.Expiration?.toISOString(),
})
return credentialsResponse
}
const logout = () => {
store.value = {}
}
const logoutAndRedirect = () => {
logout()
window.location.href = getLoginRoute()
}
return {
login,
logout,
logoutAndRedirect,
credentials: ref<Credentials | undefined>(getCredentials()),
isAuthenticated: ref(isValidCredentials(store.value)),
}
}