Repository navigation
Expand file tree
/
Copy pathapi.js
More file actions
478 lines (401 loc) · 16 KB
/
Copy pathapi.js
File metadata and controls
478 lines (401 loc) · 16 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
const token = require("./createJWT.js");
const bcrypt = require("bcrypt");
const nodemailer = require("nodemailer");
const sgMail = require('@sendgrid/mail');
require('dotenv').config();
require('express');
require('mongodb');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
exports.setApp = function (app, client) {
// Add Card
// Incoming: userId, card
// Outgoing: error
/*app.post("/api/addcard", async (req, res) => {
const { userId, card, jwtToken } = req.body;
/////////////////////////////////////////////////
console.log("Received addCard request:");
console.log("userId:", userId);
console.log("card:", card);
console.log("jwtToken (raw):", jwtToken);
/////////////////////////////////////////////////
try {
console.log("Checking if token is expired...");
if (token.isExpired(jwtToken)) {
console.log("JWT is expired or invalid.");
console.log("Token expired");
return res.status(200).json({ error: "The JWT is no longer valid", jwtToken: "" });
} console.log("Token is valid");
}
catch (err) {
console.error("Error checking token expiration:", err);
return res.status(500).json({ error: "Token validation error", jwtToken: "" });
}
console.log("Before insertOne");
const db = client.db("PocketProfessors"); // change database name here (pockProf)
console.log("After insertOne");
let error = "";
try {
await db.collection("Cards").insertOne({ Card: card, UserId: userId });
console.log("Card inserted successfully");
} catch (e) {
console.error("Error inserting card:", e.message);
error = e.toString();
}
// these lines important cuz refreshing makes it an object
// so we need to convert it back to a string
let refreshedTokenObj = token.refresh(jwtToken);
let refreshedToken = refreshedTokenObj.accessToken;
res.status(200).json({ error: "", jwtToken: refreshedToken });
});
*/
// Login
// Incoming: login, password
// Outgoing: id, firstName, lastName, error
app.post("/api/login", async (req, res) => {
const { login, password } = req.body;
// console.log(`Login attempt for user: ${login}`);
try {
const db = client.db("PocketProfessors");
const results = await db.collection("Users").find({ Login: login }).toArray();
let id = -1;
let fn = "";
let ln = "";
let error = "";
let jwtToken = "";
let user = null
if (results.length > 0) {
user = results[0];
const isMatch = await bcrypt.compare(password, user.Password);
if (isMatch) {
id = user.userId || user._id?.toString();
fn = user.FirstName;
ln = user.LastName;
const tokenObj = token.createToken(fn, ln, id);
jwtToken = tokenObj.accessToken;
} else {
error = "Login/Password incorrect";
}
} else {
error = "Login/Password incorrect";
}
if (!user.IsVerified) {
return res.status(403).json({ id: -1, error: "Email not verified", jwtToken: "" });
}
if (jwtToken) {
// console.log("Generated JWT token:", jwtToken);
}
res.status(200).json({ id, firstName: fn, lastName: ln, jwtToken, error });
} catch (err) {
console.error("Login error:", err.message);
res
.status(500)
.json({ id: -1, firstName: "", lastName: "", jwtToken: "", error: "Server error" });
}
});
/*
// Search Cards
// Incoming: userId, search
// Outgoing: results[], error
app.post('/api/searchcards', async (req, res, next) =>
{
var error = '';
const { userId, search, jwtToken } = req.body;
try
{
if( token.isExpired(jwtToken))
{
var r = {error:'The JWT is no longer valid', jwtToken: ''};
res.status(200).json(r);
return;
}
}
catch(e)
{
console.log(e.message);
}
var _search = search.trim();
const db = client.db('PocketProfessors');
const results = await db.collection('Cards').find({"Card":{$regex:_search+'.*',
$options:'i'}}).toArray();
var _ret = [];
for( var i=0; i<results.length; i++ )
{
_ret.push( results[i].Card );
}
var refreshedToken = null;
try
{
let refreshedTokenObj = token.refresh(jwtToken);
let refreshedToken = refreshedTokenObj.accessToken;
}
catch(e)
{
console.log(e.message);
}
var ret = { results:_ret, error: error, jwtToken: refreshedToken };
res.status(200).json(ret);
});
*/
//Search All Cards Not Found
//Incoming:UserID, jwt
//OutGoing: All Cards In DataBase Not Found
app.post("/api/unfoundCards", async (req, res) => {
const { userID, jwtToken } = req.body;
try {
if (token.isExpired(jwtToken)) {
var r = { error: 'The JWT is no longer valid', jwtToken: '' };
res.status(200).json(r);
return;
}
}
catch (e) {
// console.log(e.message);
}
let missingCards = [];
let error = '';
try {
const db = client.db("PocketProfessors");
const userResults = await db.collection("UserCards").find({ UserId: userID }).toArray();
const userCardNames = new Set(userResults.map(doc => doc.Card));
const globalCardResults = await db.collection("Cards").distinct("Card");
missingCards = globalCardResults.filter(card => !userCardNames.has(card));
} catch (e) {
error = e.toString();
}
let refreshedToken = null;
try {
refreshedToken = token.refresh(jwtToken);
} catch (e) {
// console.log(e.message);
}
res.status(200).json({ missingCards, error, jwtToken: refreshedToken });
}); //End of UnfoundCards
//Search Found Cards API
//Incoming:UserID, jwt
//Outgoing: Found Cards
app.post("/api/foundCards", async (req, res) => {
const { userID, jwtToken } = req.body;
try {
if (token.isExpired(jwtToken)) {
var r = { error: 'The JWT is no longer valid', jwtToken: '' };
res.status(200).json(r);
return;
}
}
catch (e) {
// console.log(e.message);
}
let cards = [];
let error = '';
try {
const db = client.db("PocketProfessors");
const results = await db.collection("UserCards").find({ UserId: userID }).toArray();
cards = results.map(doc => doc.Card);
} catch (e) {
error = e.toString();
}
var refreshedToken = null;
try {
refreshedToken = token.refresh(jwtToken);
}
catch (e) {
// console.log(e.message);
}
res.status(200).json({ cards, error, jwtToken: refreshedToken });
});
//Updated Register
//Incoming:Login,Password,firstName,lastName,email
//Outgoing:Error,Success
app.post("/api/register", async (req, res) => {
const { login, password, firstName, lastName, email } = req.body;
try {
const db = client.db("PocketProfessors");
// Normalize login
const normalizedLogin = login.trim().toLowerCase();
// Check if login already exists
const existingUser = await db.collection("Users").findOne({ Login: normalizedLogin });
if (existingUser) {
return res.status(400).json({ success: false, error: "Username is already taken" });
}
const normalizedEmail = email.trim().toLowerCase();
const existingUserEmail = await db.collection("Users").findOne({ Email: normalizedEmail });
if (existingUserEmail) {
return res.status(400).json({ success: false, error: "Email is already taken" });
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Insert new user
await db.collection("Users").insertOne({
Login: normalizedLogin,
Password: hashedPassword,
FirstName: firstName,
LastName: lastName,
Email: email.trim().toLowerCase(),
VerificationCode: null,
CodeExpires: null,
IsVerified: false,
});
return res.status(200).json({ success: true, error: "" });
} catch (err) {
console.error("Registration error:", err.message);
return res.status(500).json({ success: false, error: "Server error" });
}
}); //End of Register
app.post("/api/Verify", async (req, res) => {
const { email } = req.body;
const db = client.db("PocketProfessors");
const verificationCode = Math.floor(100000 + Math.random() * 900000).toString();
const codeExpires = new Date(Date.now() + 15 * 60 * 1000);
try {
// Find user by email
const user = await db.collection("Users").findOne({ Email: email.toLowerCase() });
if (!user) {
return res.status(404).json({ success: false, error: "User not found" });
}
// Update user's code and expiration
await db.collection("Users").updateOne(
{ Email: email.toLowerCase() },
{
$set: {
VerificationCode: verificationCode,
CodeExpires: codeExpires,
},
}
);
const msg = {
to: email,
from: process.env.SENDGRID_FROM_EMAIL,
subject: 'Your PocketProf Verification Code',
text: `Your verification code is ${verificationCode}. It will expire in 15 minutes.`,
};
await sgMail.send(msg);
return res.status(200).json({ success: true, message: "Verification code sent" });
} catch (err) {
console.error("Error during verification process:", err.message);
return res.status(500).json({ success: false, error: "Server error" });
}
});
app.post("/api/updatePassword", async (req, res) => {
const { email, newpassword, verificationCode } = req.body;
if (!email || !newpassword || !verificationCode) {
return res.status(400).json({ success: false, error: "Missing fields" });
}
const db = client.db("PocketProfessors");
try {
const user = await db.collection("Users").findOne({ Email: email.toLowerCase() });
if (!user) {
return res.status(404).json({ success: false, error: "User not found" });
}
if (user.VerificationCode !== verificationCode) {
return res.status(400).json({ success: false, error: "Invalid verification code" });
}
if (user.CodeExpires && Date.now() > new Date(user.CodeExpires).getTime()) {
return res.status(400).json({ success: false, error: "Verification code expired" });
}
const hashedPassword = await bcrypt.hash(newpassword, 10);
await db.collection("Users").updateOne(
{ Email: email.toLowerCase() },
{
$set: { Password: hashedPassword },
$unset: { VerificationCode: "", CodeExpires: "" }
}
);
return res.status(200).json({ success: true, message: "Password updated!" });
} catch (err) {
console.error("Error confirming verification:", err.message);
return res.status(500).json({ success: false, error: "Server error" });
}
});
//Confirm Email Code
//Incoming:Verification Code, Email
//OutGoing:Error, Login page
app.post("/api/Confirm", async (req, res) => {
const { email, verificationCode } = req.body;
const db = client.db("PocketProfessors");
try {
const user = await db.collection("Users").findOne({ Email: email.toLowerCase() });
if (!user) {
return res.status(404).json({ success: false, error: "User not found" });
}
if (user.VerificationCode !== verificationCode) {
return res.status(400).json({ success: false, error: "Invalid verification code" });
}
// Check code expiration
if (user.CodeExpires && Date.now() > new Date(user.CodeExpires).getTime()) {
return res.status(400).json({ success: false, error: "Verification code expired" });
}
// Update user to verified and clear codes
await db.collection("Users").updateOne(
{ Email: email.toLowerCase() },
{ $set: { IsVerified: true }, $unset: { VerificationCode: "", CodeExpires: "" } }
);
return res.status(200).json({ success: true, message: "Email verified successfully" });
} catch (err) {
console.error("Error confirming verification:", err.message);
return res.status(500).json({ success: false, error: "Server error" });
}
});
// Open Pack
// Incoming: userId, jwtToken, packName
// Outgoing: jwtToken, addedCards, error
app.post('/api/openPack', async (req, res) => {
const { userId, jwtToken } = req.body;
// Validate JWT
try {
if (token.isExpired(jwtToken)) {
return res.status(200).json({ error: 'JWT expired', jwtToken: '' });
}
} catch (e) {
return res.status(500).json({ error: 'JWT validation failed', jwtToken: '' });
}
try {
const db = client.db("PocketProfessors");
const rarityWeights = {
1: 50,
2: 25,
3: 15,
4: 8,
5: 2
};
// Get all cards from the pack
const allCards = await db.collection('Cards').find({}).toArray();
const weightedPool = [];
// Create weighted pool
allCards.forEach(card => {
const weight = rarityWeights[card.Rarity] || 1;
for (let i = 0; i < weight; i++) {
weightedPool.push(card);
}
});
const newCards = [];
const selected = new Set();
const packSize = 3; // change if needed
while (newCards.length < packSize && weightedPool.length > 0) {
const randIndex = Math.floor(Math.random() * weightedPool.length);
const selectedCard = weightedPool[randIndex];
if (!selected.has(selectedCard.Card)) {
newCards.push(selectedCard);
selected.add(selectedCard.Card);
}
}
// Add cards to user's collection
const userCardsCollection = db.collection("UserCards");
const insertOps = newCards.map(card => ({
UserId: userId,
Card: card.Card,
Rarity: card.Rarity,
}));
await userCardsCollection.insertMany(insertOps);
// Return updated JWT and the new cards
const refreshedToken = token.refresh(jwtToken);
return res.status(200).json({
jwtToken: refreshedToken,
addedCards: newCards,
error: ''
});
} catch (err) {
console.error("Error opening pack:", err);
return res.status(500).json({ error: "Error opening pack", jwtToken: '' });
}
});
};