From 7eb8ccae48b0cc18a9dcaa9c3626a02df8e6d919 Mon Sep 17 00:00:00 2001 From: JustZvan Date: Fri, 6 Feb 2026 13:22:33 +0100 Subject: feat: initial commit! --- lib/auth.tsx | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 lib/auth.tsx (limited to 'lib/auth.tsx') diff --git a/lib/auth.tsx b/lib/auth.tsx new file mode 100644 index 0000000..b05c6a7 --- /dev/null +++ b/lib/auth.tsx @@ -0,0 +1,81 @@ +import { + createContext, + ReactNode, + useContext, + useEffect, + useState, +} from "react"; +import { apiClient } from "../api/client"; + +type AuthState = { + isLoading: boolean; + isAuthenticated: boolean; +}; + +type AuthContextType = AuthState & { + signIn: ( + email: string, + password: string, + ) => Promise<{ success: boolean; reason?: string }>; + signUp: ( + email: string, + password: string, + ) => Promise<{ success: boolean; reason?: string }>; + signOut: () => Promise; +}; + +const AuthContext = createContext(null); + +export function AuthProvider({ children }: { children: ReactNode }) { + const [state, setState] = useState({ + isLoading: true, + isAuthenticated: false, + }); + + useEffect(() => { + // Check if user is already authenticated + const checkAuth = async () => { + await apiClient.initialize(); + setState({ + isLoading: false, + isAuthenticated: apiClient.isAuthenticated(), + }); + }; + checkAuth(); + }, []); + + const signIn = async (email: string, password: string) => { + const result = await apiClient.signIn(email, password); + if (result.success) { + setState({ isLoading: false, isAuthenticated: true }); + } + return { success: result.success, reason: result.reason }; + }; + + const signUp = async (email: string, password: string) => { + const result = await apiClient.signUp(email, password); + if (result.success) { + setState({ isLoading: false, isAuthenticated: true }); + } + return { success: result.success, reason: result.reason }; + }; + + const signOut = async () => { + await apiClient.signOut(); + setState({ isLoading: false, isAuthenticated: false }); + }; + + return ( + + {children} + + ); +} + +export function useAuth() { + const context = useContext(AuthContext); + if (!context) { + throw new Error("useAuth must be used within an AuthProvider"); + } + return context; +} -- cgit v1.2.3