aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/src/atoms/auth.ts
blob: dd6f06c7fb295eed743b64271bb40751c0821622 (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
import { atom, useSetAtom } from "jotai";
import { useEffect } from "react";
import type { components } from "../api/generated";
import { api } from "../services/api-client";

type User = components["schemas"]["User"];

export const userAtom = atom<User | null>(null);
export const authLoadingAtom = atom<boolean>(true);
export const isLoggedInAtom = atom<boolean>((get) => get(userAtom) !== null);

export const loginAtom = atom(
	null,
	async (
		_get,
		set,
		{ username, password }: { username: string; password: string },
	) => {
		const { data, error } = await api.POST("/api/auth/login", {
			body: { username, password },
		});
		if (error) {
			throw new Error(error.message);
		}
		set(userAtom, data.user);
	},
);

export const logoutAtom = atom(null, async (_get, set) => {
	await api.POST("/api/auth/logout");
	set(userAtom, null);
});

export function useAuthInit() {
	const setUser = useSetAtom(userAtom);
	const setAuthLoading = useSetAtom(authLoadingAtom);

	useEffect(() => {
		api.GET("/api/auth/me").then(({ data }) => {
			if (data) {
				setUser(data);
			}
			setAuthLoading(false);
		});
	}, [setUser, setAuthLoading]);
}