import type { User, LoginCredentials } from '~/types/models' export function useAuth() { const authStore = useAuthStore() const { get, post, delete: deleteRequest } = useApi() const router = useRouter() const fetchUser = async (): Promise => { try { const user = await get('/me') authStore.setUser(user) return user } catch { authStore.clearUser() return null } } const checkAuth = async (): Promise => { authStore.setLoading(true) try { const user = await fetchUser() return !!user } finally { authStore.setLoading(false) } } const login = async (credentials: LoginCredentials): Promise => { authStore.setLoading(true) authStore.setError(null) try { const response = await post<{ user: User }>('/login', credentials) authStore.setUser(response.user) const route = useRoute() const from = route.query.from as string if (from && !from.includes('/admin')) { await router.push(from) } else { await router.push('/') } return response.user } catch (err: any) { authStore.setError(err.data?.message || '登录失败') throw err } finally { authStore.setLoading(false) } } const logout = async (): Promise => { try { await deleteRequest('/logout') } finally { authStore.clearUser() await router.push('/login') } } const requireAuth = async (redirect = true): Promise => { if (authStore.isAuthenticated) { return true } if (authStore.isLoading) { await new Promise(resolve => setTimeout(resolve, 100)) return requireAuth(redirect) } if (redirect) { const route = useRoute() await router.push(`/login?from=${route.fullPath}`) } return false } const requireAdmin = async (): Promise => { const authenticated = await requireAuth() if (!authenticated) return false if (!authStore.isAdmin) { await router.push('/403') return false } return true } return { user: computed(() => authStore.user), isAuthenticated: computed(() => authStore.isAuthenticated), isAdmin: computed(() => authStore.isAdmin), isLoading: computed(() => authStore.isLoading), error: computed(() => authStore.error), login, logout, fetchUser, checkAuth, requireAuth, requireAdmin, } }