Files
patchpass/UI/src/context/AuthContext.tsx
T
Space-Banane 7e05dd918c
Deploy / Build (push) Successful in 28s
Deploy / Test & Lint (push) Failing after 29s
Deploy / Build and Push Docker Image (push) Has been skipped
Patchpass V1
2026-07-18 20:14:44 +02:00

58 lines
1.4 KiB
TypeScript

import { createContext, useCallback, useContext, useEffect, useState, ReactNode } from "react";
import { auth as authApi, global as globalApi } from "../api/client";
import type { GlobalSettings, User } from "../api/types";
type AuthContextValue = {
user: User | null;
loading: boolean;
settings: GlobalSettings | null;
setUser: (u: User | null) => void;
refresh: () => Promise<void>;
logout: () => Promise<void>;
};
const AuthContext = createContext<AuthContextValue>({
user: null,
loading: true,
settings: null,
setUser: () => {},
refresh: async () => {},
logout: async () => {},
});
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [settings, setSettings] = useState<GlobalSettings | null>(null);
const refresh = useCallback(async () => {
try {
const me = await authApi.me();
setUser(me);
} catch {
setUser(null);
}
}, []);
useEffect(() => {
(async () => {
globalApi.get().then(setSettings).catch(() => {});
await refresh();
setLoading(false);
})();
}, [refresh]);
const logout = useCallback(async () => {
await authApi.logout().catch(() => {});
setUser(null);
}, []);
return (
<AuthContext.Provider value={{ user, loading, settings, setUser, refresh, logout }}>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => useContext(AuthContext);