aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/src/contexts/AuthContext.tsx
blob: 4f973558e19a0b33b5dc16e4cdbfd31588022e74 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import {
	createContext,
	type ReactNode,
	useContext,
	useEffect,
	useState,
} from "react";
import { useMutation, useQuery } from "urql";
import {
	GetMeDocument,
	LoginDocument,
	LogoutDocument,
} from "../graphql/generated/graphql";

interface User {
	id: string;
	username: string;
}

interface AuthContextType {
	user: User | null;
	isLoading: boolean;
	login: (username: string, password: string) => Promise<boolean>;
	logout: () => Promise<void>;
}

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

export function AuthProvider({ children }: { children: ReactNode }) {
	const [user, setUser] = useState<User | null>(null);
	const [isLoading, setIsLoading] = useState(true);

	const [, executeLogin] = useMutation(LoginDocument);
	const [, executeLogout] = useMutation(LogoutDocument);
	const [meResult, reexecuteMe] = useQuery({ query: GetMeDocument });

	// Update user from Me query
	useEffect(() => {
		if (meResult.data?.me) {
			setUser(meResult.data.me);
		} else {
			setUser(null);
		}
		if (!meResult.fetching) {
			setIsLoading(false);
		}
	}, [meResult.data, meResult.fetching]);

	const login = async (
		username: string,
		password: string,
	): Promise<boolean> => {
		try {
			const result = await executeLogin({ username, password });

			if (result.data?.login?.user) {
				setUser(result.data.login.user);
				// Refetch Me query to ensure session is established
				reexecuteMe({ requestPolicy: "network-only" });
				return true;
			}

			return false;
		} catch (error) {
			console.error("Login failed:", error);
			return false;
		}
	};

	const logout = async () => {
		try {
			await executeLogout({});
		} catch (error) {
			console.error("Logout failed:", error);
		} finally {
			setUser(null);
			// Refetch Me query to ensure session is cleared
			reexecuteMe({ requestPolicy: "network-only" });
		}
	};

	return (
		<AuthContext.Provider value={{ user, 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;
}