-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
69 lines (60 loc) · 1.77 KB
/
Copy pathauth.js
File metadata and controls
69 lines (60 loc) · 1.77 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
import { auth, db } from "./firebase.js";
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
onAuthStateChanged,
signOut
} from "https://www.gstatic.com/firebasejs/12.6.0/firebase-auth.js";
import {
setDoc,
getDoc,
doc
} from "https://www.gstatic.com/firebasejs/12.6.0/firebase-firestore.js";
// LOGIN BUTTON
const loginBtn = document.getElementById("loginBtn");
const signupBtn = document.getElementById("signupBtn");
const message = document.getElementById("loginMsg");
// LOGIN
if (loginBtn) {
loginBtn.onclick = async () => {
const email = email.value;
const password = password.value;
try {
await signInWithEmailAndPassword(auth, email, password);
location.href = "index.html";
} catch (err) {
message.textContent = err.message;
}
};
}
// SIGNUP
if (signupBtn) {
signupBtn.onclick = async () => {
const email = email.value;
const password = password.value;
try {
const user = await createUserWithEmailAndPassword(auth, email, password);
// Create a database entry for this user
await setDoc(doc(db, "users", user.user.uid), {
correct: 0,
wrong: 0,
skill: 0,
life: 3
});
message.textContent = "Account created! You can now log in.";
} catch (err) {
message.textContent = err.message;
}
};
}
let currentUser = null;
// AUTO REDIRECT — Protect game page
onAuthStateChanged(async (user) => {
if (user) {
currentUser = user;
await loadStats(); // load their saved stats
} else {
currentUser = null;
console.log("No user logged in");
}
});