-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.js
More file actions
94 lines (83 loc) · 2.5 KB
/
auth.js
File metadata and controls
94 lines (83 loc) · 2.5 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
import {
getAuth,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut,
} from "firebase/auth";
import { getFirestore, doc, setDoc, getDoc } from "firebase/firestore";
import { app } from "./firebase";
import CryptoJS from "crypto-js";
const auth = getAuth(app);
const db = getFirestore(app);
const generateHashedEmail = (username) => {
const fakeEmail = `${username.replace(/\s+/g, "")}@example.com`;
const hashedEmail = CryptoJS.SHA256(fakeEmail).toString() + "@hashed.com";
console.log('Generated hashed email:', hashedEmail);
return hashedEmail;
};
export const signUp = async (username, password) => {
try {
const hashedEmail = generateHashedEmail(username);
console.log('Attempting to create user with:', hashedEmail);
const userCredential = await createUserWithEmailAndPassword(
auth,
hashedEmail,
password
);
const user = userCredential.user;
console.log('User created successfully:', user.uid);
// Store the username and hashed email in Firestore
await setDoc(doc(db, "users", user.uid), {
username: username,
hashedEmail: hashedEmail,
});
console.log('User document created in Firestore');
return user;
} catch (error) {
console.error("Error signing up: ", error);
console.error("Error code:", error.code);
console.error("Error message:", error.message);
throw error;
}
};
export const signIn = async (username, password) => {
try {
const hashedEmail = generateHashedEmail(username);
console.log('Attempting to sign in with:', hashedEmail);
const userCredential = await signInWithEmailAndPassword(
auth,
hashedEmail,
password
);
console.log('Sign in successful:', userCredential.user);
return userCredential.user;
} catch (error) {
console.error("Error signing in: ", error);
console.error("Error code:", error.code);
console.error("Error message:", error.message);
throw error;
}
};
export const signOutUser = async () => {
try {
await signOut(auth);
} catch (error) {
console.error("Error signing out: ", error);
throw error;
}
};
export const getCurrentUser = () => {
return new Promise((resolve, reject) => {
const unsubscribe = auth.onAuthStateChanged((user) => {
unsubscribe();
resolve(user);
}, reject);
});
};
export const getUsername = async (userId) => {
const userDoc = await getDoc(doc(db, "users", userId));
if (userDoc.exists()) {
return userDoc.data().username;
}
return null;
};