67 lines
1.8 KiB
TypeScript
67 lines
1.8 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'
|
|
|
|
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),
|
|
}
|
|
}
|