aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/src/contexts/AuthContext.tsx
blob: 9b157cbb7d25a04a49b484d5f920679e22a8fa48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import {
	createContext,
	type ReactNode,
	useCallback,
	useContext,
	useEffect,
	useState,
} from "react";
import { api } from "../services/api-client";

type LoginResult = { success: true } | { success: false; error: string };

interface AuthContextType {
	isLoggedIn: boolean;
	isLoading: boolean;
	login: (username: string, password: string) => Promise<LoginResult>;
	logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
	const [isLoggedIn, setIsLoggedIn] = useState(false);
	const [isLoading, setIsLoading] = useState(true);

	const checkAuth = useCallback(async () => {
		const { data } = await api.GET("/api/auth/me");
		setIsLoggedIn(!!data);
		setIsLoading(false);
	}, []);

	useEffect(() => {
		checkAuth();
	}, [checkAuth]);

	const login = async (
		username: string,
		password: string,
	): Promise<LoginResult> => {
		const { data, error } = await api.POST("/api/auth/login", {
			body: { username, password },
		});

		if (error) {
			return { success: false, error: error.message };
		}

		if (data?.user) {
			setIsLoggedIn(true);
			return { success: true };
		}

		return { success: false, error: "Invalid username or password" };
	};

	const logout = async () => {
		await api.POST("/api/auth/logout");
		setIsLoggedIn(false);
	};

	return (
		<AuthContext.Provider value={{ isLoggedIn, isLoading, login, logout }}>
			{children}
		</AuthContext.Provider>
	);
}

export function useAuth() {
	const context = useContext(AuthContext);
	if (context === undefined) {
		throw new Error("useAuth must be used within an AuthProvider");
	}
	return context;
}