Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 1x 3x 3x 2x 1x 1x 1x 1x 3x 2x 2x 1x 1x 3x | import { useNavigate } from 'react-router-dom'
import { useMutation } from '@tanstack/react-query'
import { api, getApiErrorMessage } from '@core/lib/api'
interface LoginCredentials {
email: string
password: string
}
interface LoginResult {
success: boolean
error?: string
}
/**
* Handles the administrative login flow using the backend auth module.
* Manages token storage and navigation on successful authentication.
*/
export const useLogin = () => {
const navigate = useNavigate()
const mutation = useMutation({
mutationFn: async (credentials: LoginCredentials) => {
const res = await api.post('/auth/login', credentials)
return res.data
},
onSuccess: (data) => {
localStorage.setItem('token', data.accessToken)
localStorage.setItem('user', JSON.stringify(data.user))
navigate('/admin')
},
})
const login = async (credentials: LoginCredentials): Promise<LoginResult> => {
try {
await mutation.mutateAsync(credentials)
return { success: true }
} catch (err) {
return { success: false, error: getApiErrorMessage(err, 'Login failed') }
}
}
return {
login,
error: mutation.error ? getApiErrorMessage(mutation.error, 'Login failed') : null,
isLoading: mutation.isPending,
}
}
|