feat: scaffold complete danable frontend architecture with all pages, layouts, stores, and 3 annotator modes
This commit is contained in:
commit
78848dd7d1
173 changed files with 18649 additions and 0 deletions
67
src/hooks/useAuth.ts
Normal file
67
src/hooks/useAuth.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
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'
|
||||
|
||||
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 = err instanceof Error ? err.message : 'Đăng nhập thất bại'
|
||||
setError(message)
|
||||
throw err
|
||||
} 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),
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue