-
Notifications
You must be signed in to change notification settings - Fork 28
/
auth.tsx
80 lines (66 loc) · 2.24 KB
/
auth.tsx
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
import { getBus } from "piercing-library";
import { createContext, useContext, useEffect, useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import {
deleteCurrentUser,
getUserData,
saveCurrentUser,
setUserData,
} from "shared";
import { initialPlaceholderTodoList } from "./initialPlaceholderTodoList";
export type LoginMessage = { username: string };
export type AuthenticationMessage = { username: string | null };
const AuthContext = createContext<AuthenticationMessage | undefined>(undefined);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const navigate = useNavigate();
const [user, setUser] = useState(
getBus().latestValue<AuthenticationMessage>("authentication")
);
useEffect(() => {
return getBus().listen<LoginMessage>("login", async (user) => {
setUser(user);
await addUserDataIfMissing(user.username);
await saveCurrentUser(user.username);
getBus().dispatch("authentication", user);
navigate("/", {
replace: true,
});
});
}, []);
useEffect(() => {
return getBus().listen("logout", () => {
setUser({ username: null });
deleteCurrentUser();
getBus().dispatch("authentication", { username: null });
navigate("/login");
});
}, []);
return <AuthContext.Provider value={user}>{children}</AuthContext.Provider>;
}
export function useAuth() {
return useContext(AuthContext);
}
export function RequireAuth({ children }: { children: React.ReactNode }) {
const auth = useAuth();
assertDefined(auth);
return !auth.username ? <Navigate to={"/login"} replace /> : <>{children}</>;
}
export function RequireNotAuth({ children }: { children: React.ReactNode }) {
const auth = useAuth();
assertDefined(auth);
return auth.username ? <Navigate to={"/"} replace /> : <>{children}</>;
}
async function addUserDataIfMissing(user: string) {
const data = getUserData(user);
if (!data) {
const newDataStr = JSON.stringify({
todoLists: [initialPlaceholderTodoList],
});
setUserData(user, newDataStr);
}
}
function assertDefined<T>(value: T | undefined): asserts value is T {
if (value === undefined) {
throw new Error("Programming error: Value should not be undefined");
}
}