2024-03-17 17:28:45 +01:00
|
|
|
import { useNavigate } from "@tanstack/react-router"
|
|
|
|
import { 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-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-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)
|
|
|
|
navigate({ to: "/" })
|
2024-03-08 14:58:36 +01:00
|
|
|
}
|
2024-03-07 19:16:23 +01:00
|
|
|
|
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-03-08 14:58:36 +01:00
|
|
|
return { login, logout, user, isLoading }
|
2024-03-07 19:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-03-08 14:58:36 +01:00
|
|
|
export { isLoggedIn }
|
|
|
|
export default useAuth
|