aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/src/contexts/AuthContext.tsx
blob: 9b53aa752c47a7df7a724ff3f09af32f6f0079ab (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
import { createContext, type ReactNode, useContext } from "react";
import { useMutation, useQuery } from "urql";
import {
	GetCurrentUserDocument,
	LoginDocument,
	LogoutDocument,
} from "../graphql/generated/graphql";

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

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

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

export function AuthProvider({ children }: { children: ReactNode }) {
	const [, executeLogin] = useMutation(LoginDocument);
	const [, executeLogout] = useMutation(LogoutDocument);
	const [currentUserResult, reexecuteCurrentUser] = useQuery({
		query: GetCurrentUserDocument,
	});

	const isLoggedIn = !!currentUserResult.data?.currentUser;
	const isLoading = currentUserResult.fetching;
	const error = currentUserResult.error?.message ?? null;

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

			if (result.error) {
				const errorMessage =
					result.error.graphQLErrors[0]?.message || result.error.message;
				return { success: false, error: errorMessage };
			}

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

			const errorMessage = "Invalid username or password";
			return { success: false, error: errorMessage };
		} catch (error) {
			const errorMessage =
				error instanceof Error ? error.message : "An unknown error occurred";
			console.error("Login failed:", error);
			return { success: false, error: errorMessage };
		}
	};

	const logout = async () => {
		try {
			await executeLogout({});
			// Refetch CurrentUser query to ensure session is cleared
			reexecuteCurrentUser({ requestPolicy: "network-only" });
		} catch (error) {
			console.error("Logout failed:", error);
			// Even on error, refetch to get the latest state
			reexecuteCurrentUser({ requestPolicy: "network-only" });
		}
	};

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