anotation-frontend/src/hooks/useAuth.ts

76 lines
2.2 KiB
TypeScript

import { useState } from 'react'
import * as authService from '@/services/authService'
import { useAuthStore } from '@/stores/authStore'
import { LoginRequest, UserRole } from '@/types'
import { canApproveLabels, canCreateProject, canManageUsers } from '@/utils/permissions'
// Prefer the server's message (e.g. FastAPI `detail`) over axios' generic text.
function readServerMessage(err: unknown): string | null {
if (typeof err === 'object' && err !== null && 'response' in err) {
const detail = (err as { response?: { data?: { detail?: unknown } } }).response?.data?.detail
if (typeof detail === 'string' && detail.trim() !== '') return detail
}
return err instanceof Error ? err.message : null
}
export function useAuth() {
const { user, isAuthenticated, login: storeLogin, logout: storeLogout, setUser, setRole } = useAuthStore()
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const login = async (payload: LoginRequest) => {
setIsLoading(true)
setError(null)
try {
const response = await authService.login(payload)
storeLogin(response.user, response.accessToken)
return response
} catch (err) {
const message = readServerMessage(err) ?? 'Đăng nhập thất bại'
setError(message)
throw new Error(message)
} finally {
setIsLoading(false)
}
}
const loginWithSSO = async (provider: 'google' | 'microsoft' | 'sso' = 'sso') => {
setIsLoading(true)
setError(null)
try {
const response = await authService.loginWithSSO(provider)
storeLogin(response.user, response.accessToken)
return response
} finally {
setIsLoading(false)
}
}
const logout = async () => {
await authService.logout()
storeLogout()
}
const switchRole = async (role: UserRole) => {
const updated = await authService.switchUserRole(role)
setRole(role)
setUser(updated)
}
const role: UserRole = user?.role ?? 'admin'
return {
user,
role,
isAuthenticated,
isLoading,
error,
login,
loginWithSSO,
logout,
switchRole,
canManageUsers: canManageUsers(role),
canApproveLabels: canApproveLabels(role),
canCreateProject: canCreateProject(role),
}
}