..
Viewing
auth.ts
56 lines (48 loc) • 1.8 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 | import {
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
sendEmailVerification,
type Auth,
} from "firebase/auth";
import { setDoc } from "firelordjs";
import { UserRef } from "$lib/firebase/refs";
import { AvatarMode } from "$lib/firebase/enums";
import type { FirebaseError } from "firebase/app";
export const authHandler = async (auth: Auth, event: SubmitEvent): Promise<FirebaseError | null> => {
const buttonType: HTMLButtonElement = (event.submitter as HTMLButtonElement);
const form: HTMLFormElement = (event.target as HTMLFormElement);
if (buttonType.value === "Login") {
return login(auth, form);
} else if (buttonType.value === "Register") {
return register(auth, form);
} else {
console.log("Invalid button type");
return null;
}
};
const login = async (auth: Auth, form: HTMLFormElement): Promise<FirebaseError | null> => {
const email: string = form.email.value;
const password: string = form.password.value;
try {
await signInWithEmailAndPassword(auth, email, password);
return null;
} catch (error: unknown) {
return error as FirebaseError;
}
}
const register = async (auth: Auth, form: HTMLFormElement): Promise<FirebaseError | null> => {
const email: string = form.email.value;
const password: string = form.password.value;
try {
await createUserWithEmailAndPassword(auth, email, password);
if (auth.currentUser !== null) {
await sendEmailVerification(auth.currentUser);
await setDoc(UserRef.doc(auth.currentUser.uid), {
avatarMode: AvatarMode.Gravatar,
});
}
return null;
} catch (error: unknown) {
return error as FirebaseError;
}
}
|
|