Initial MRP foundation scaffold
This commit is contained in:
70
client/src/auth/AuthProvider.tsx
Normal file
70
client/src/auth/AuthProvider.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import type { AuthUser } from "@mrp/shared";
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { api } from "../lib/api";
|
||||
|
||||
interface AuthContextValue {
|
||||
token: string | null;
|
||||
user: AuthUser | null;
|
||||
isReady: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
const tokenKey = "mrp.auth.token";
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [token, setToken] = useState<string | null>(() => window.localStorage.getItem(tokenKey));
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setUser(null);
|
||||
setIsReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
api.me(token)
|
||||
.then((nextUser) => {
|
||||
setUser(nextUser);
|
||||
})
|
||||
.catch(() => {
|
||||
window.localStorage.removeItem(tokenKey);
|
||||
setToken(null);
|
||||
})
|
||||
.finally(() => setIsReady(true));
|
||||
}, [token]);
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({
|
||||
token,
|
||||
user,
|
||||
isReady,
|
||||
async login(email, password) {
|
||||
const result = await api.login({ email, password });
|
||||
setToken(result.token);
|
||||
setUser(result.user);
|
||||
window.localStorage.setItem(tokenKey, result.token);
|
||||
},
|
||||
logout() {
|
||||
window.localStorage.removeItem(tokenKey);
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
},
|
||||
}),
|
||||
[isReady, token, user]
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error("useAuth must be used within AuthProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user