summaryrefslogtreecommitdiff
path: root/lib/auth.tsx
diff options
context:
space:
mode:
authorJustZvan <justzvan@justzvan.xyz>2026-02-06 13:22:33 +0100
committerJustZvan <justzvan@justzvan.xyz>2026-02-06 13:22:33 +0100
commit7eb8ccae48b0cc18a9dcaa9c3626a02df8e6d919 (patch)
tree57b7dd06ac9aa7053c671d916f7183e3b4fa9410 /lib/auth.tsx
feat: initial commit!
Diffstat (limited to 'lib/auth.tsx')
-rw-r--r--lib/auth.tsx81
1 files changed, 81 insertions, 0 deletions
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<void>;
+};
+
+const AuthContext = createContext<AuthContextType | null>(null);
+
+export function AuthProvider({ children }: { children: ReactNode }) {
+ const [state, setState] = useState<AuthState>({
+ 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 (
+ <AuthContext.Provider value={{ ...state, signIn, signUp, signOut }}>
+ {children}
+ </AuthContext.Provider>
+ );
+}
+
+export function useAuth() {
+ const context = useContext(AuthContext);
+ if (!context) {
+ throw new Error("useAuth must be used within an AuthProvider");
+ }
+ return context;
+}