initial commit, boilerplate stuff
This commit is contained in:
57
src/hooks/useAuth.ts
Normal file
57
src/hooks/useAuth.ts
Normal 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 };
|
||||
};
|
||||
Reference in New Issue
Block a user