-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthContext.tsx
More file actions
182 lines (150 loc) · 4.96 KB
/
Copy pathAuthContext.tsx
File metadata and controls
182 lines (150 loc) · 4.96 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import { createContext, ReactNode, useEffect, useState } from "react";
import { CreateToastFnReturn } from "@chakra-ui/react";
import { AnimatePresence, motion } from "framer-motion";
import { LoadingScreen } from "../components/common/LoadingScreen";
import { AxiosInstance } from "axios";
import {
createUserWithEmailAndPassword,
getRedirectResult,
sendPasswordResetEmail,
signInWithEmailAndPassword,
signOut,
User,
UserCredential,
} from "firebase/auth";
import { NavigateFunction } from "react-router-dom";
import { auth } from "../utils/auth/firebase";
import { cookieKeys, setCookie } from "../utils/auth/cookie";
import { useBackendContext } from "./hooks/useBackendContext";
interface AuthContextProps {
currentUser: User | null;
signup: ({ email, password }: EmailPassword) => Promise<UserCredential>;
login: ({ email, password }: EmailPassword) => Promise<UserCredential>;
logout: () => Promise<void>;
resetPassword: ({ email }: Pick<EmailPassword, "email">) => Promise<void>;
handleRedirectResult: (
backend: AxiosInstance,
navigate: NavigateFunction,
toast: CreateToastFnReturn
) => Promise<void>;
}
export const AuthContext = createContext<AuthContextProps | null>(null);
interface EmailPassword {
email: string;
password: string;
}
export const AuthProvider = ({ children }: { children: ReactNode }) => {
const { backend } = useBackendContext();
const [currentUser, setCurrentUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const signup = async ({ email, password }: EmailPassword) => {
if (currentUser) {
signOut(auth);
}
const userCredential = await createUserWithEmailAndPassword(
auth,
email,
password
);
await backend.post("/users", {
email: email,
firebaseUid: userCredential.user.uid,
});
return userCredential;
};
const login = ({ email, password }: EmailPassword) => {
if (currentUser) {
signOut(auth);
}
return signInWithEmailAndPassword(auth, email, password);
};
const logout = () => {
return signOut(auth);
};
const resetPassword = ({ email }: Pick<EmailPassword, "email">) => {
return sendPasswordResetEmail(auth, email);
};
/**
* Helper function which keeps our DB and our Firebase in sync.
* If a user exists in Firebase, but does not exist in our DB, we create a new user.
*
* **If creating a DB user fails, we rollback by deleting the Firebase user.**
*/
const handleRedirectResult = async (
backend: AxiosInstance,
navigate: NavigateFunction,
toast: CreateToastFnReturn
) => {
try {
const result = await getRedirectResult(auth);
if (!result?.user) return;
const idToken = await result.user.getIdToken();
setCookie({ key: cookieKeys.ACCESS_TOKEN, value: idToken });
let response = await backend.get(`/users/firebase/${result.user.uid}`);
if (response.data.length === 0) {
try {
response = await backend.post("/users", {
email: result.user.email,
firebaseUid: result.user.uid,
firstName: result.user.displayName?.split(" ")[0] || "",
lastName: result.user.displayName?.split(" ").slice(1).join(" ") || "",
photoURL: result.user.photoURL ?? null,
});
} catch (e) {
await backend.delete(`/users/firebase/${result.user.uid}`);
const errorMessage = e instanceof Error ? e.message : "Unknown error";
toast({
title: "An error occurred",
description: `Account was not created: ${errorMessage}`,
status: "error",
});
return;
}
} else {
// Sync photoURL in case the user updated their Google profile picture
try {
await backend.put(`/users/firebase/${result.user.uid}`, {
photoURL: result.user.photoURL ?? null,
});
} catch (e) {
console.error("Failed to sync photoURL:", e);
}
}
const data = response.data;
const user = Array.isArray(data) ? data[0] : data;
if (!user) return;
navigate(
user.status === "pending" ? "/pending-approval" : "/quota-tracking",
{ replace: true }
);
} catch (error) {
console.error("Redirect result error:", error);
}
};
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
setCurrentUser(user);
setLoading(false);
});
return unsubscribe;
}, []);
return (
<AuthContext.Provider
value={{
currentUser,
signup,
login,
logout,
resetPassword,
handleRedirectResult,
}}
>
<AnimatePresence>{loading && <LoadingScreen key="loading" />}</AnimatePresence>
{!loading && (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.3 }}>
{children}
</motion.div>
)}
</AuthContext.Provider>
);
};