-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.js
More file actions
303 lines (270 loc) · 10.4 KB
/
user.js
File metadata and controls
303 lines (270 loc) · 10.4 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Initialize Firebase
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.0/firebase-app.js";
import { getDatabase, ref, set, get } from "https://www.gstatic.com/firebasejs/11.6.0/firebase-database.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/11.6.0/firebase-analytics.js";
// Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyCj0K9NlYXt4yVq4uQjegDh0b5aE6HnH-k",
authDomain: "flappymird-cadb0.firebaseapp.com",
databaseURL: "https://flappymird-cadb0-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "flappymird-cadb0",
storageBucket: "flappymird-cadb0.firebasestorage.app",
messagingSenderId: "645077184491",
appId: "1:645077184491:web:5535e9a5f14babb07433ae",
measurementId: "G-X2R67H129Q"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const database = getDatabase(app);
let userHighScore = 0; // Variable to store the user's high score
// Check if a user is already logged in by checking localStorage
function checkForLoggedInUser() {
const username = localStorage.getItem('username');
if (username) {
displayUser(username); // Show the user's data if logged in
} else {
displayLoginOrRegister(); // Show options to login or register
}
}
// Display options to login or register
function displayLoginOrRegister() {
const userContainer = document.getElementById("user-container");
userContainer.innerHTML = `
<button onclick="showLogin()">Login</button>
<button onclick="showRegister()">Register</button>
`;
}
// Show login form
function showLogin() {
const username = prompt("Please enter your username:").trim();
if (username) {
const password = prompt("Please enter your password:").trim();
if (password) {
loginUser(username, password); // Attempt to log in
} else {
alert("Password is required!");
}
} else {
alert("Username is required!");
}
}
// Show register form
function showRegister() {
const username = prompt("Please enter your desired username:").trim();
if (username) {
checkIfUsernameExists(username); // Check if username exists before registration
} else {
alert("Username is required!");
}
}
// Check if the username already exists in the database
function checkIfUsernameExists(username) {
const userRef = ref(database, 'users/' + username);
get(userRef).then((snapshot) => {
if (snapshot.exists()) {
// If username exists, show an alert
alert("Username already exists! Please choose a different username.");
} else {
// If username does not exist, proceed with password prompt
const password = prompt("Please enter your password:").trim();
if (password) {
registerUser(username, password); // Proceed with registration if password is provided
} else {
alert("Password is required!");
}
}
}).catch((error) => {
console.error("Error checking username:", error);
alert("Error checking username: " + error.message);
});
}
// Register a new user with a username and password (plain text)
function registerUser(username, password) {
const userRef = ref(database, 'users/' + username);
userHighScore = 0; // Reset high score for new user
set(userRef, {
name: username,
password: password, // Plaintext password (not secure)
score: 0
}).then(() => {
console.log("User registered:", username);
localStorage.setItem('username', username); // Save username in localStorage for session persistence
displayUser(username); // Show user after registration
}).catch((error) => {
console.error("Error registering user:", error);
alert("Error registering user: " + error.message);
});
}
// Log in a user with username and password (plain text)
function loginUser(username, password) {
const userRef = ref(database, 'users/' + username);
get(userRef).then((snapshot) => {
if (snapshot.exists()) {
const user = snapshot.val();
if (user.password === password) {
// Password matches
userHighScore = user.score; // Set the user's high score
console.log("User logged in:", username);
localStorage.setItem('username', username); // Save username in localStorage for session persistence
displayUser(username); // Show user after login
} else {
alert("Incorrect password. Please try again.");
}
} else {
alert("User not found. Please register first.");
}
}).catch((error) => {
console.error("Error logging in:", error);
alert("Error logging in: " + error.message);
});
}
// Display user data and leaderboard (username and score)
function displayUser(username) {
const userRef = ref(database, 'users/' + username);
get(userRef).then((snapshot) => {
const userContainer = document.getElementById("user-container");
if (snapshot.exists()) {
const user = snapshot.val();
userContainer.innerHTML = `
<h3>Leaderboard</h3>
<div id="leaderboard"></div>
<button onclick="logout()">Logout</button>
`;
displayLeaderboard(user.name); // Show the leaderboard after user logs in
} else {
displayLoginOrRegister();
}
}).catch((error) => {
console.error("Error retrieving user data:", error);
});
}
// Display leaderboard with all users' scores
function displayLeaderboard(currentUser) {
const leaderboardRef = ref(database, 'users');
get(leaderboardRef).then((snapshot) => {
const leaderboardContainer = document.getElementById("leaderboard");
leaderboardContainer.innerHTML = ""; // Clear the current leaderboard
if (snapshot.exists()) {
const users = snapshot.val();
const sortedUsers = Object.values(users).sort((a, b) => b.score - a.score); // Sort by score
sortedUsers.forEach(user => {
const userElement = document.createElement("p");
userElement.classList.add("leaderboard-entry");
// Check if the user is the current logged-in user and append "(you)"
const displayName = user.name === currentUser ? `${user.name} (you)` : user.name;
userElement.textContent = `${displayName}: ${user.score}`;
leaderboardContainer.appendChild(userElement);
});
} else {
leaderboardContainer.innerHTML = "<p>No users found.</p>";
}
}).catch((error) => {
console.error("Error retrieving leaderboard data:", error);
});
}
// Logout the current user
function logout() {
localStorage.removeItem('username');
userHighScore = 0; // Reset high score on logout
checkForLoggedInUser(); // Recheck if user is logged in after logout
}
// Initialize the app and check for logged-in user
window.onload = function () {
checkForLoggedInUser();
};
// Make the functions globally available
window.showLogin = showLogin;
window.showRegister = showRegister;
window.logout = logout;
function getHighScore() {
return userHighScore
}
function setHighScore(newHighScore) {
userHighScore = newHighScore; // Update the high score variable
}
function fetchHighScore() {
const username = localStorage.getItem('username');
if (username) {
const userRef = ref(database, 'users/' + username);
get(userRef).then((snapshot) => {
if (snapshot.exists()) {
const user = snapshot.val();
userHighScore = user.score; // Set the user's high score
console.log("Fetched high score:", userHighScore);
} else {
console.log("User data not found.");
}
}).catch((error) => {
console.error("Error fetching high score:", error);
});
} else {
console.log("No user logged in.");
highScore = 0; // Reset high score if no user is logged in
}
}
window.getHighScore = getHighScore;
window.setHighScore = setHighScore;
window.fetchHighScore = fetchHighScore;
// user.js (Module)
function updateHighScore(newScore) {
const username = localStorage.getItem('username');
if (username) {
const userRef = ref(database, 'users/' + username);
// Update the score only if the new score is higher than the current score
get(userRef).then((snapshot) => {
if (snapshot.exists()) {
const user = snapshot.val();
if (newScore > user.score) {
// Update the score in the database
set(userRef, {
...user,
score: newScore
}).then(() => {
console.log("User's high score updated:", newScore);
updateLeaderboard(); // Update the leaderboard after updating the score
}).catch((error) => {
console.error("Error updating high score:", error);
alert("Error updating high score: " + error.message);
});
} else {
console.log("New scores is not higher than current score.");
}
} else {
console.log("User data not found.");
}
}).catch((error) => {
console.error("Error retrieving user data:", error);
});
} else {
console.log("No user logged in.");
}
}
// Make the function globally available
window.updateHighScore = updateHighScore;
// Refresh the leaderboard to show updated scores
function updateLeaderboard() {
const leaderboardRef = ref(database, 'users');
get(leaderboardRef).then((snapshot) => {
const leaderboardContainer = document.getElementById("leaderboard");
leaderboardContainer.innerHTML = ""; // Clear the current leaderboard
if (snapshot.exists()) {
const users = snapshot.val();
const sortedUsers = Object.values(users).sort((a, b) => b.score - a.score); // Sort by score
sortedUsers.forEach(user => {
const userElement = document.createElement("p");
userElement.classList.add("leaderboard-entry");
// Check if the user is the current logged-in user and append "(you)"
const displayName = user.name === localStorage.getItem('username') ? `${user.name} (you)` : user.name;
userElement.textContent = `${displayName}: ${user.score}`;
leaderboardContainer.appendChild(userElement);
});
} else {
leaderboardContainer.innerHTML = "<p>No users found.</p>";
}
}).catch((error) => {
console.error("Error retrieving leaderboard data:", error);
});
}
// Make the leaderboard update function globally available
window.updateLeaderboard = updateLeaderboard;