2024-03-17 17:28:45 +01:00
|
|
|
import { useNavigate } from "@tanstack/react-router"
|
2024-04-01 22:53:33 -05:00
|
|
|
import { useState } from "react"
|
|
|
|
import { useMutation, useQuery } from "react-query"
|
2024-03-07 19:16:23 +01:00
|
|
|
|
2024-03-08 14:58:36 +01:00
|
|
|
import {
|
2024-03-28 20:22:28 -05:00
|
|
|
type Body_login_login_access_token as AccessToken,
|
2024-04-01 22:53:33 -05:00
|
|
|
type ApiError,
|
2024-03-28 21:15:11 -05:00
|
|
|
LoginService,
|
2024-03-28 20:22:28 -05:00
|
|
|
type UserOut,
|
2024-03-28 21:15:11 -05:00
|
|
|
UsersService,
|
2024-03-17 17:28:45 +01:00
|
|
|
} from "../client"
|
2024-03-07 19:16:23 +01:00
|
|
|
|
|
|
|
const isLoggedIn = () => {
|
2024-03-17 17:28:45 +01:00
|
|
|
return localStorage.getItem("access_token") !== null
|
2024-03-08 14:58:36 +01:00
|
|
|
}
|
2024-03-07 19:16:23 +01:00
|
|
|
|
|
|
|
const useAuth = () => {
|
2024-04-01 22:53:33 -05:00
|
|
|
const [error, setError] = useState<string | null>(null)
|
2024-03-08 14:58:36 +01:00
|
|
|
const navigate = useNavigate()
|
|
|
|
const { data: user, isLoading } = useQuery<UserOut | null, Error>(
|
2024-03-17 17:28:45 +01:00
|
|
|
"currentUser",
|
2024-03-08 14:58:36 +01:00
|
|
|
UsersService.readUserMe,
|
|
|
|
{
|
|
|
|
enabled: isLoggedIn(),
|
|
|
|
},
|
|
|
|
)
|
2024-03-07 19:16:23 +01:00
|
|
|
|
2024-03-08 14:58:36 +01:00
|
|
|
const login = async (data: AccessToken) => {
|
|
|
|
const response = await LoginService.loginAccessToken({
|
|
|
|
formData: data,
|
|
|
|
})
|
2024-03-17 17:28:45 +01:00
|
|
|
localStorage.setItem("access_token", response.access_token)
|
2024-03-08 14:58:36 +01:00
|
|
|
}
|
2024-03-07 19:16:23 +01:00
|
|
|
|
2024-04-01 22:53:33 -05:00
|
|
|
const loginMutation = useMutation(login, {
|
|
|
|
onSuccess: () => {
|
|
|
|
navigate({ to: "/" })
|
|
|
|
},
|
|
|
|
onError: (err: ApiError) => {
|
|
|
|
const errDetail = err.body.detail
|
|
|
|
setError(errDetail)
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
2024-03-08 14:58:36 +01:00
|
|
|
const logout = () => {
|
2024-03-17 17:28:45 +01:00
|
|
|
localStorage.removeItem("access_token")
|
|
|
|
navigate({ to: "/login" })
|
2024-03-08 14:58:36 +01:00
|
|
|
}
|
2024-03-07 19:16:23 +01:00
|
|
|
|
2024-04-01 22:53:33 -05:00
|
|
|
return {
|
|
|
|
loginMutation,
|
|
|
|
logout,
|
|
|
|
user,
|
|
|
|
isLoading,
|
|
|
|
error,
|
|
|
|
}
|
2024-03-07 19:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-03-08 14:58:36 +01:00
|
|
|
export { isLoggedIn }
|
|
|
|
export default useAuth
|