Files
xiaomai 07e5d42005 refactor: centralize validation, error handling, and formatting logic
Extract shared auth logic and validation rules to shared/auth.ts
Introduce utility functions for HTTP errors and user input parsing
Standardize error messages and date formatting across the app
2026-04-12 20:29:39 +08:00

53 lines
1.3 KiB
TypeScript

import { needsUserOnboarding, type AuthUser } from '~~/shared/auth'
export function useAuth() {
const user = useState<AuthUser | null>('auth:user', () => null)
const loaded = useState<boolean>('auth:loaded', () => false)
const loading = useState<boolean>('auth:loading', () => false)
const apiClient = useApiClient()
const isAuthenticated = computed(() => Boolean(user.value))
const isSuperAdmin = computed(() => user.value?.role === 'super_admin')
const needsOnboarding = computed(() => needsUserOnboarding(user.value))
async function fetchSession(force = false) {
if (loaded.value && !force) {
return user.value
}
loading.value = true
try {
const response = await apiClient<{ user: AuthUser | null }>('/api/auth/me')
user.value = response.user
loaded.value = true
return user.value
} finally {
loading.value = false
}
}
function setUser(nextUser: AuthUser | null) {
user.value = nextUser
loaded.value = true
}
function clearUser() {
user.value = null
loaded.value = true
}
return {
user,
loaded,
loading,
isAuthenticated,
isSuperAdmin,
needsOnboarding,
fetchSession,
refreshSession: () => fetchSession(true),
setUser,
clearUser
}
}