add login / logout logic for user

This commit is contained in:
Julien Aldon
2026-02-17 17:31:29 +01:00
parent a8c8c489da
commit aca24ca560
14 changed files with 258 additions and 108 deletions

View File

@@ -0,0 +1,33 @@
import { createContext, useContext } from "react";
import { useCurrentUser } from "../api";
import type { UserLogged } from "../resources/users";
export type Auth = {
loggedUser: UserLogged | null;
isLoading: boolean;
}
const AuthContext = createContext<Auth | undefined>(undefined)
export function AuthProvider({ children }: {children: React.ReactNode}) {
const {data: loggedUser, isLoading} = useCurrentUser();
const value: Auth = {
loggedUser: loggedUser ?? null,
isLoading,
};
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)
}
export function useAuth(): Auth {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used inside AuthProvider");
}
return context;
}

View File

@@ -0,0 +1,20 @@
import { Group, Loader } from "@mantine/core";
import { Navigate, Outlet } from "react-router";
import { useAuth } from "../AuthProvider";
export function ProtectedRoute() {
const { loggedUser, isLoading } = useAuth();
if (!loggedUser && isLoading)
return (
<Group align="center" justify="center" h="80vh" w="100%">
<Loader color="pink" />
</Group>
);
if (!loggedUser?.logged) {
return <Navigate to="/" replace />;
}
return <Outlet />;
}