initial commit, boilerplate stuff

This commit is contained in:
khannurien
2026-03-15 17:15:46 +00:00
commit 6207a7549f
52 changed files with 4400 additions and 0 deletions

57
src/hooks/useAuth.ts Normal file
View File

@@ -0,0 +1,57 @@
import { useContext } from "react";
import { AuthContext } from "../contexts/AuthContext.ts";
import { type AuthResponse } from "../model.ts";
export const useAuth = () => {
const { authResponse, setAuthResponse } = useContext(AuthContext);
const login = (response: AuthResponse) => {
setAuthResponse(response);
localStorage.setItem("authResponse", JSON.stringify(response));
};
const logout = () => {
setAuthResponse(null);
localStorage.removeItem("authResponse");
};
const authFetch = async (input: RequestInfo, init: RequestInit = {}) => {
const token = authResponse?.token;
const res = await fetch(input, {
...init,
headers: {
...(init.headers ?? {}),
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
});
if (res.status === 401) {
logout();
}
return res;
};
return {
user: authResponse?.user ?? null,
token: authResponse?.token ?? null,
login,
logout,
authFetch,
};
};
export const useRequiredAuth = () => {
const { user, token, login, logout, authFetch } = useAuth();
if (!user) {
throw new Error(
"Invariant: useRequiredAuth called outside a protected route",
);
}
return { user, token, login, logout, authFetch };
};