source: pages/api/postgre/index.js@ e903234

main
Last change on this file since e903234 was e903234, checked in by anastasovv <simon@…>, 23 months ago

Added an admin panel, and the admin can now answer complaints

  • Property mode set to 100644
File size: 36.2 KB
Line 
1import { v4 as uuidv4 } from 'uuid';
2
3import axios from 'axios';
4
5require('dotenv').config();
6
7const crypto = require('crypto');
8
9const nodemailer = require('nodemailer');
10
11import { progressRoundTillTheEnd } from '../poker/tableSpecific';
12
13const Pool = require('pg').Pool
14const pool = new Pool({
15 connectionString: `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}/${process.env.POSTGRES_DB}`
16});
17
18export default function handler(req, res) {
19 /**
20 * GET method
21 */
22 if (req.method === 'GET') {
23 /**
24 * /---------------------- GET ----------------------/
25 * If the player won credits, update them in the database.
26 * Also, update the stats in the database.
27 * @action give_credits
28 * @param session_id
29 * @param credits
30 */
31 if (req.query?.action === 'add_credits' && req.query?.session_id && req.query?.credits) {
32 const session_id = req.query.session_id
33 const session = sessions.find(session => session.id === session_id)
34
35 if (session) {
36 session.lastActivity = Date.now();
37
38 if (parseInt(req.query.credits) > 0) {
39 session.credits = session.credits + parseInt(req.query.credits)
40
41 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
42 if (error) throw error;
43 });
44 }
45
46 if (req.query?.dont_update_stats) {
47 // continue
48 } else {
49 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
50 if (error) throw error;
51
52 if (results.rows.length > 0) {
53 const stats = results.rows[0]
54
55 if (parseInt(req.query.credits) > 0) {
56 pool.query('UPDATE stats SET money_earned = $1 WHERE username = $2', [parseInt(stats.money_earned) + parseInt(req.query.credits), session.username], (error, results) => {
57 if (error) throw error;
58 });
59 }
60
61 if (req.query?.game === 'blackjack') {
62 if (req.query?.outcome === 'player_busted' || req.query?.outcome === 'player_lost') {
63 pool.query('UPDATE stats SET blackjack_games = $1 WHERE username = $2', [parseInt(stats.blackjack_games) + 1, session.username], (error, results) => {
64 if (error) throw error;
65 });
66 }
67 else if (req.query?.outcome === 'dealer_busted' || req.query?.outcome === 'player_won') {
68 pool.query('UPDATE stats SET blackjack_games = $1, blackjack_won_games = $2 WHERE username = $3', [parseInt(stats.blackjack_games) + 1, parseInt(stats.blackjack_won_games) + 1, session.username], (error, results) => {
69 if (error) throw error;
70 });
71 }
72 }
73 else if (req.query?.game === 'roulette') {
74 if (req.query?.outcome === 'lost') {
75 pool.query('UPDATE stats SET roulette_games = $1 WHERE username = $2', [parseInt(stats.roulette_games) + 1, session.username], (error, results) => {
76 if (error) throw error;
77 });
78 }
79 else if (req.query?.outcome === 'won') {
80 pool.query('UPDATE stats SET roulette_games = $1, roulette_won_games = $2 WHERE username = $3', [parseInt(stats.roulette_games) + 1, parseInt(stats.roulette_won_games) + 1, session.username], (error, results) => {
81 if (error) throw error;
82 });
83 }
84 }
85 else if (req.query?.game === 'poker') {
86 if (req.query?.outcome === 'lost') {
87 pool.query('UPDATE stats SET poker_games = $1 WHERE username = $2', [parseInt(stats.poker_games) + 1, session.username], (error, results) => {
88 if (error) throw error;
89 });
90 }
91 else if (req.query?.outcome === 'won') {
92 pool.query('UPDATE stats SET poker_games = $1, poker_won_games = $2 WHERE username = $3', [parseInt(stats.poker_games) + 1, parseInt(stats.poker_won_games) + 1, session.username], (error, results) => {
93 if (error) throw error;
94 });
95 }
96 }
97 }
98 });
99 }
100
101 update_sessions_to_database();
102
103 res.json({
104 success: true,
105 credits: session.credits,
106 })
107
108 return ;
109 }
110
111 res.json({
112 success: false,
113 })
114 }
115
116 /**
117 * /---------------------- GET ----------------------/
118 * The player lost credits, update this in the database.
119 * @action take_credits
120 * @param session_id
121 * @param credits
122 */
123 if (req.query?.action === 'take_credits' && req.query?.session_id && req.query?.credits) {
124 const session_id = req.query.session_id
125 const session = sessions.find(session => session.id === session_id)
126
127 let takeWhatYouCan = false;
128 if (req.query?.takeWhatYouCan === "true") takeWhatYouCan = true;
129
130 if (session) {
131 session.lastActivity = Date.now();
132
133 if (session.credits < parseInt(req.query.credits)) {
134 if (takeWhatYouCan) {
135 session.credits = 0;
136 }
137 else {
138 res.json({
139 success: false,
140 });
141
142 return ;
143 }
144 }
145 else {
146 session.credits = session.credits - parseInt(req.query.credits)
147 }
148
149 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
150 if (error) throw error;
151 });
152
153 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
154 if (error) throw error;
155
156 if (results.rows.length > 0) {
157 const stats = results.rows[0]
158
159 pool.query('UPDATE stats SET money_bet = $1 WHERE username = $2', [parseInt(stats.money_bet) + parseInt(req.query.credits), session.username], (error, results) => {
160 if (error) throw error;
161 });
162 }
163 });
164
165 update_sessions_to_database();
166
167 res.json({
168 success: true,
169 credits: session.credits,
170 })
171 return ;
172 }
173
174 res.json({
175 success: false,
176 })
177 }
178
179 /**
180 * /---------------------- GET ----------------------/
181 * /--------------------- ADMIN ----------------------/
182 * Get complaints from the players and show them to the admin
183 * @action get_complaints_as_admin
184 * @param admin_id
185 */
186 if (req.query?.action === 'get_complaints_as_admin' && req.query?.admin_id) {
187 const admin_id = req.query.admin_id
188 const adminSession = adminSessions.find(adminSession => adminSession.id === admin_id)
189
190 if (adminSession) {
191 pool.query('SELECT * FROM complaints', (error, results) => {
192 if (error) throw error;
193
194 if (results.rows.length > 0) {
195 res.json({
196 success: true,
197 complaints: results.rows,
198 })
199 }
200 else {
201 res.json({
202 success: false,
203 })
204 }
205 });
206
207 return ;
208 }
209
210 res.json({
211 success: false,
212 })
213 }
214
215 /**
216 * /---------------------- GET ----------------------/
217 * Get stats for the player, so we can display them in the front end.
218 * @action get_stats
219 * @param session_id
220 */
221 if (req.query?.action === 'get_stats' && req.query?.session_id) {
222 const session_id = req.query.session_id
223 const session = sessions.find(session => session.id === session_id)
224
225 if (session) {
226 session.lastActivity = Date.now();
227
228 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
229 if (error) throw error;
230
231 if (results.rows.length > 0) {
232 res.json({
233 success: true,
234 stats: results.rows[0],
235 })
236 }
237 else {
238 res.json({
239 success: false,
240 })
241 }
242 });
243
244 return ;
245 }
246
247 res.json({
248 success: false,
249 })
250 }
251
252 /**
253 * /---------------------- GET ----------------------/
254 * Activates an user account if not activated.
255 * @action activate_account
256 * @param emailActivationId
257 */
258 if (req.query?.action === 'activate_account' && req.query?.emailActivationId) {
259 pool.query('SELECT * FROM users WHERE email_activation_id = $1', [req.query.emailActivationId], (error, results) => {
260 if (error) throw error;
261
262 if (results.rows.length > 0) {
263 pool.query('UPDATE users SET activated = $1 WHERE email_activation_id = $2', [true, req.query.emailActivationId], (error, results) => {
264 if (error) throw error;
265
266 res.json({
267 success: true,
268 })
269 });
270 }
271 else {
272 res.json({
273 success: false,
274 })
275 }
276 });
277 }
278
279 /**
280 * /---------------------- GET ----------------------/
281 * Checks if the player is logged in, and returns his session if so.
282 * @action check_if_logged_in
283 * @param session_id
284 */
285 if (req.query?.action === 'check_if_logged_in' && req.query?.session_id) {
286 const session_id = req.query.session_id
287 const session = sessions.find(session => session.id === session_id)
288
289 if (session) {
290 res.json({
291 success: true,
292 displayName: session.displayName,
293 username: session.username,
294 session_id: session.id,
295 credits: session.credits,
296 })
297 return ;
298 }
299
300 res.json({
301 success: false,
302 })
303 }
304
305 /**
306 * /---------------------- GET ----------------------/
307 * Takes the credits in the player's session, and updates the database.
308 * Logs the player out and kills the session.
309 * @action logout
310 * @param session_id
311 */
312 if (req.query?.action === 'logout' && req.query?.session_id) {
313 const session_id = req.query.session_id
314 const session = sessions.find(session => session.id === session_id)
315
316 if (session) {
317 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
318 if (error) throw error;
319 });
320
321 sessions.splice(sessions.indexOf(session), 1);
322 update_sessions_to_database();
323
324 // remove player from games:
325 if (rooms[session_id] !== undefined) {
326 delete rooms[session_id];
327 update_rooms_to_database();
328 }
329
330 if (game.players?.map(e=>e.session_id).indexOf(session_id) !== -1) {
331 game.players?.splice(game.players?.map(e=>e.session_id).indexOf(session_id), 1);
332 update_game_to_database();
333 }
334
335 tables.forEach(table => {
336 table.players?.forEach(player => {
337 if (player.id === session_id) {
338 player.isGhost = true;
339 }
340 })
341 })
342 update_tables_to_database();
343 }
344
345 res.json({
346 success: true,
347 message: 'Successfully logged out',
348 })
349 }
350 }
351
352 /**
353 * POST method
354 */
355 if (req.method === 'POST') {
356 const { body } = req;
357
358 /**
359 * /---------------------- POST ----------------------/
360 * Deposits money from credit card to game account.
361 * @action register
362 * @param session_id
363 * @param data
364 */
365 if (body?.action === 'deposit') {
366 // checks
367 if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
368 res.json({
369 success: false,
370 message: 'You are not logged in. Please log in first.',
371 });
372 return ;
373 }
374 if (body?.data?.name == "undefined" || body?.data?.name == "null" || body?.data?.name == "") {
375 res.json({
376 success: false,
377 message: 'Name field cannot be empty',
378 });
379 return ;
380 }
381 if (body?.data?.card == "undefined" || body?.data?.card == "null" || body?.data?.card == "") {
382 res.json({
383 success: false,
384 message: 'Card numbers field cannot be empty',
385 });
386 return ;
387 }
388 if (body?.data?.expire == "undefined" || body?.data?.expire == "null" || body?.data?.expire == "") {
389 res.json({
390 success: false,
391 message: 'Expiration date field cannot be empty',
392 });
393 return ;
394 }
395 if (body?.data?.ccv == "undefined" || body?.data?.ccv == "null" || body?.data?.ccv == "") {
396 res.json({
397 success: false,
398 message: 'CCV field cannot be empty',
399 });
400 return ;
401 }
402 if (body?.data?.amount == "undefined" || body?.data?.amount == "null" || body?.data?.amount == "") {
403 res.json({
404 success: false,
405 message: 'Amount field cannot be empty',
406 });
407 return ;
408 }
409 if (parseInt(body?.data?.amount) > 5000) {
410 res.json({
411 success: false,
412 message: 'Failed to deposit. Insufficient credit on card.',
413 });
414 return ;
415 }
416
417 let session = sessions.find(session => session.id === body?.session_id)
418
419 if (session) {
420 if (parseInt(body.data.amount) > 0) {
421 session.credits = session.credits + parseInt(body.data.amount)
422
423 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
424 if (error) throw error;
425
426 res.json({
427 success: true,
428 credits: session.credits
429 })
430
431 update_sessions_to_database();
432 });
433 }
434 }
435 }
436
437 /**
438 * /---------------------- POST ----------------------/
439 * Withdraws money from game account to personal account.
440 * @action register
441 * @param session_id
442 * @param data
443 */
444 if (body?.action === 'withdraw') {
445 // checks
446 if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
447 res.json({
448 success: false,
449 message: 'You are not logged in. Please log in first.',
450 });
451 return ;
452 }
453 if (body?.data?.citibank == "undefined" || body?.data?.citibank == "null" || body?.data?.citibank == "") {
454 res.json({
455 success: false,
456 message: 'Bank name field cannot be empty',
457 });
458 return ;
459 }
460 if (body?.data?.iban == "undefined" || body?.data?.iban == "null" || body?.data?.iban == "") {
461 res.json({
462 success: false,
463 message: 'IBAN code field cannot be empty',
464 });
465 return ;
466 }
467 if (body?.data?.bic == "undefined" || body?.data?.bic == "null" || body?.data?.bic == "") {
468 res.json({
469 success: false,
470 message: 'BIC code field cannot be empty',
471 });
472 return ;
473 }
474 if (body?.data?.beneficiary == "undefined" || body?.data?.beneficiary == "null" || body?.data?.beneficiary == "") {
475 res.json({
476 success: false,
477 message: 'Beneficiary name field cannot be empty',
478 });
479 return ;
480 }
481 if (body?.data?.address == "undefined" || body?.data?.address == "null" || body?.data?.address == "") {
482 res.json({
483 success: false,
484 message: 'Bank address field cannot be empty',
485 });
486 return ;
487 }
488 if (body?.data?.amount == "undefined" || body?.data?.amount == "null" || body?.data?.amount == "") {
489 res.json({
490 success: false,
491 message: 'Amount field cannot be empty',
492 });
493 return ;
494 }
495
496 let session = sessions.find(session => session.id === body?.session_id)
497
498 if (session) {
499 if (parseInt(body.data.amount) > 0) {
500 session.credits = Math.max(session.credits - parseInt(body.data.amount), 0)
501
502 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
503 if (error) throw error;
504
505 res.json({
506 success: true,
507 credits: session.credits
508 })
509
510 update_sessions_to_database();
511 });
512 }
513 }
514 }
515
516 /**
517 * /---------------------- POST ----------------------/
518 * /---------------------- ADMIN ----------------------/
519 * Sends an answer to a complaint.
520 * @action send_complaint_answer_as_admin
521 * @param admin_id
522 * @param complaint
523 */
524 if (body?.action === 'send_complaint_answer_as_admin') {
525 // checks
526 if (body?.admin_id == "undefined" || body?.admin_id == "null" || body?.admin_id == "") {
527 res.json({
528 success: false,
529 message: 'You are not logged in. Please log in first.',
530 });
531 return ;
532 }
533 if (body?.complaint.by == "undefined" || body?.complaint.by == "null" || body?.complaint.by == "") {
534 res.json({
535 success: false,
536 message: 'You cannot send the answer to noone.',
537 });
538 return ;
539 }
540 if (body?.complaint.description == "undefined" || body?.complaint.description == "null" || body?.complaint.description == "") {
541 res.json({
542 success: false,
543 message: 'You cannot answer an empty complaint.',
544 });
545 return ;
546 }
547 if (body?.complaint.answer == "undefined" || body?.complaint.answer == "null" || body?.complaint.answer == "") {
548 res.json({
549 success: false,
550 message: 'You cannot submit an empty answer.',
551 });
552 return ;
553 }
554
555 let adminSession = adminSessions.find(adminSession => adminSession.id === body.admin_id)
556
557 if (adminSession) {
558 pool.query('UPDATE complaints SET answer = $1, answered = $2 WHERE by = $3', [body.complaint.answer, true, body.complaint.by], (error, complaintResults) => {
559 if (error) throw error;
560
561 pool.query('SELECT * FROM complaints', (error, results) => {
562 if (error) throw error;
563
564 res.json({
565 success: true,
566 complaints: results.rows,
567 })
568 });
569
570 sendMailForComplaintAnswered(body.complaint);
571 });
572 }
573 }
574
575 /**
576 * /---------------------- POST ----------------------/
577 * Sends a complaint.
578 * @action complain
579 * @param session_id
580 * @param description
581 */
582 if (body?.action === 'complain') {
583 // checks
584 if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
585 res.json({
586 success: false,
587 message: 'You are not logged in. Please log in first.',
588 });
589 return ;
590 }
591 if (body?.description == "undefined" || body?.description == "null" || body?.description == "") {
592 res.json({
593 success: false,
594 message: 'You cannot submit an empty complaint.',
595 });
596 return ;
597 }
598
599 let session = sessions.find(session => session.id === body.session_id)
600
601 if (session) {
602 // date, by, description, answered
603 const date = new Date();
604 pool.query('INSERT INTO complaints (date, by, description, answered, answer) VALUES ($1, $2, $3, $4, $5)', [date, session.username, body.description, false, ''], (error, complaintResults) => {
605 if (error) throw error;
606
607 res.json({
608 success: true,
609 })
610 });
611 }
612 }
613
614 /**
615 * /---------------------- POST ----------------------/
616 * Checks if the entered account info is good, and registers a new user in the database if so.
617 * @action register
618 * @param username
619 * @param displayName
620 * @param password
621 */
622 if (body?.action === 'register') {
623 // checks
624 if (body?.email == "undefined" || body?.email == "null" || body?.email == "") {
625 res.json({
626 success: false,
627 message: 'Email is required',
628 });
629 return ;
630 }
631 if (!body?.email?.includes('@') || body?.email?.indexOf('@', body?.email?.indexOf('@')+1) !== -1) {
632 res.json({
633 success: false,
634 message: 'Not a valid email',
635 });
636 return ;
637 }
638 if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
639 res.json({
640 success: false,
641 message: 'Username is required',
642 });
643 return ;
644 }
645 if (/[^a-zA-Z]/g.test(body?.username)) {
646 res.json({
647 success: false,
648 message: 'Username must contain only letters',
649 })
650 return ;
651 }
652 if (body?.displayName == "undefined" || body?.displayName == "null" || body?.displayName == "") {
653 res.json({
654 success: false,
655 message: 'Display name is required',
656 });
657 return ;
658 }
659 if (body?.displayName?.toLowerCase() === "guest") {
660 res.json({
661 success: false,
662 message: 'Display name cannot be guest',
663 });
664 return ;
665 }
666 if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
667 res.json({
668 success: false,
669 message: 'Password is required',
670 });
671 return ;
672 }
673
674 // everything's okay
675 body.username = body.username.toLowerCase()
676
677 // hash password
678 const salt = crypto.randomBytes(16).toString('hex');
679 const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
680
681 // check if user already exists
682 pool.query('SELECT * FROM users WHERE username = $1', [body.username], (error, results) => {
683 if (error) throw error;
684
685 if (results.rows.length > 0) {
686 res.json({
687 success: false,
688 message: 'Username already exists',
689 });
690 return ;
691 }
692
693 const emailActivationId = uuidv4();
694
695 // store user in database
696 pool.query('INSERT INTO users (username, password, salt, email, email_activation_id, activated) VALUES ($1, $2, $3, $4, $5, $6)', [body.username, hashedPassword, salt, body.email, emailActivationId, false], (error, usersResults) => {
697 if (error) throw error;
698
699 pool.query('INSERT INTO players (username, display_name, credits) VALUES ($1, $2, $3)', [body.username, body.displayName, 1000], (error, playersResults) => {
700 if (error) throw error;
701
702 pool.query('INSERT INTO stats (username, blackjack_games, roulette_games, poker_games, blackjack_won_games, roulette_won_games, poker_won_games, money_bet, money_earned) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)', [body.username, 0, 0, 0, 0, 0, 0, 0, 0], (error, statsResults) => {
703 if (error) throw error;
704
705 sendMailForActivation(body.displayName, body.email, emailActivationId);
706
707 res.json({
708 success: true,
709 message: 'Registration successful',
710 });
711 return ;
712 });
713 });
714 });
715 });
716 }
717
718 /**
719 * /---------------------- POST ----------------------/
720 * Checks if the entered account info is good, and logs the user in if so.
721 * @action login
722 * @param username
723 * @param password
724 */
725 if (body?.action === 'login') {
726 // checks
727 if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
728 res.json({
729 success: false,
730 message: 'Username is required',
731 });
732 return ;
733 }
734 if (/[^a-zA-Z]/g.test(body?.username)) {
735 res.json({
736 success: false,
737 message: 'Username must contain only letters',
738 })
739 return ;
740 }
741 if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
742 res.json({
743 success: false,
744 message: 'Password is required',
745 });
746 return ;
747 }
748
749 // everything's okay
750 body.username = body.username.toLowerCase();
751
752 // check if user exists
753 pool.query('SELECT * FROM users WHERE username = $1', [body.username], (error, usersResults) => {
754 if (error) throw error;
755
756 if (usersResults.rows.length === 0) {
757 res.json({
758 success: false,
759 message: 'User does not exist. Try Registering instead.',
760 });
761 return ;
762 }
763 else {
764 if (usersResults.rows.length > 0) {
765 const user = usersResults.rows[0];
766
767 const salt = user.salt;
768 const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
769
770 if (hashedPassword === user.password) {
771 if (user.activated === "false") {
772 res.json({
773 success: false,
774 message: 'Account not activated. Check your email.',
775 })
776
777 return ;
778 }
779
780 pool.query('SELECT * FROM players WHERE username = $1', [body.username], (error, playersResults) => {
781 if (playersResults.rows.length > 0) {
782 let session = sessions.find(session => session.username === playersResults.rows[0].username)
783
784 if (session) {
785 // Already logged in
786 res.json({
787 success: true,
788 message: 'Login successful',
789 session: session,
790 })
791 }
792 else {
793 // create a session
794 session = {
795 id: uuidv4(),
796 displayName: playersResults.rows[0].display_name,
797 username: playersResults.rows[0].username,
798 credits: playersResults.rows[0].credits,
799 lastActivity: Date.now(),
800 }
801
802 sessions.push(session);
803
804 update_sessions_to_database();
805
806 res.json({
807 success: true,
808 message: 'Login successful',
809 session: session,
810 })
811 }
812
813 return ;
814 }
815 });
816 }
817 else {
818 res.json({
819 success: false,
820 message: 'Username and password do not match.',
821 });
822 }
823 }
824 }
825 });
826 }
827
828 /**
829 * /---------------------- POST ----------------------/
830 * /---------------------- ADMIN ----------------------/
831 * Checks if the entered account info is good, and logs the admin in if so.
832 * @action login_as_admin
833 * @param username
834 * @param password
835 */
836 if (body?.action === 'login_as_admin') {
837 // checks
838 if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
839 res.json({
840 success: false,
841 message: 'Username is required',
842 });
843 return ;
844 }
845 if (/[^a-zA-Z]/g.test(body?.username)) {
846 res.json({
847 success: false,
848 message: 'Username must contain only letters',
849 })
850 return ;
851 }
852 if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
853 res.json({
854 success: false,
855 message: 'Password is required',
856 });
857 return ;
858 }
859
860 // everything's okay
861 body.username = body.username.toLowerCase();
862
863 // check if user exists
864 pool.query('SELECT * FROM admins WHERE username = $1', [body.username], (error, adminsResults) => {
865 if (error) throw error;
866
867 if (adminsResults.rows.length === 0) {
868 res.json({
869 success: false,
870 message: 'Admin does not exist.',
871 });
872 return ;
873 }
874 else {
875 if (adminsResults.rows.length > 0) {
876 const user = adminsResults.rows[0];
877
878 const salt = user.salt;
879 const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
880
881 if (hashedPassword === user.password) {
882 let adminSession = adminSessions.find(session => session.username === adminsResults.rows[0].username)
883
884 if (adminSession) {
885 // Already logged in
886 res.json({
887 success: true,
888 message: 'Login successful',
889 session: adminSession,
890 })
891 }
892 else {
893 // create a session
894 adminSession = {
895 id: uuidv4(),
896 username: adminsResults.rows[0].username,
897 }
898
899 adminSessions.push(adminSession);
900
901 res.json({
902 success: true,
903 message: 'Login successful',
904 session: adminSession,
905 })
906 }
907
908 return ;
909 }
910 else {
911 res.json({
912 success: false,
913 message: 'Username and password do not match.',
914 });
915 }
916 }
917 }
918 });
919 }
920 }
921}
922
923// Mailing
924const transporter = nodemailer.createTransport({
925 service: 'gmail',
926 auth: {
927 user: process.env.GOOGLE_EMAIL,
928 pass: process.env.GOOGLE_APP_PASSWORD,
929 }
930})
931
932function sendMailForActivation(displayName, userEmail, emailActivationId) {
933 const message = {
934 from: process.env.GOOGLE_EMAIL,
935 to: userEmail,
936 subject: "Caessino - Activate your account",
937 html: `
938 <h4>Hello, ${displayName}</h4>
939 <p>Thank you for creating an account at Caessino. Just one more step and you can start enjoying the games!</p>
940 <p>To activate your account please follow this link: <a target="_blank" href="${process.env.HOME_URL}/activate/${emailActivationId}">Activate account</a>
941 <br/>
942 <p>Cheers and happy playing,</p>
943 <p>The Team ESS</p>
944 `
945 }
946
947 transporter.sendMail(message, (err, data) => {
948 if (err) {
949 console.log(err);
950 }
951 })
952}
953
954let mailSentTo = {
955 poker: [],
956 roulette: [],
957 blackjack: [],
958}
959function sendMailForGameCompletition(game, username, displayName) {
960 return ;
961
962 const msgPoker = 'Your game was played to the end by the computer with the following rules:<br/>1. No more bets were made by any player;<br/>2. Cards were dealt normally like they would be under normal circumstances;<br/>3. Credits were given to the winners and taken from the losers.';
963 const msgRoulette = 'If you reconnect immediately, you can catch this ongoing game. But don\'t worry if you can\'t! If you win, credits will be awarded to you.';
964 const msgBlackjack = 'You can now continue playing your game.';
965
966 pool.query('SELECT * FROM users WHERE username = $1', [username], (error, results) => {
967 if (error) throw error;
968
969 if (results.rows.length > 0) {
970 const userEmail = results.rows[0].email;
971
972 if ((game === 'poker' && mailSentTo.poker.indexOf(userEmail) === -1) ||
973 (game === 'roulette' && mailSentTo.roulette.indexOf(userEmail) === -1) ||
974 (game === 'blackjack' && mailSentTo.blackjack.indexOf(userEmail) === -1))
975 {
976 const message = {
977 from: process.env.GOOGLE_EMAIL,
978 to: userEmail,
979 subject: "Caessino - Server is back online",
980 html: `
981 <h4>Hello, ${displayName}</h4>
982 <p>We are writing to inform you that the server is back online.</p>
983 <p>We know that you were in the middle of playing ${game}, and we apologize for the interrupt.</p>
984 <p>${game === 'poker' ? msgPoker : game === 'roulette' ? msgRoulette : msgBlackjack}</p>
985 <br/>
986 <p>All the best,</p>
987 <p>The Team ESS</p>
988 `
989 }
990
991 transporter.sendMail(message, (err, data) => {
992 if (err) {
993 console.log(err);
994 }
995 })
996
997 mailSentTo[game].push(userEmail)
998 }
999 }
1000 });
1001}
1002
1003function sendMailForComplaintAnswered(complaint) {
1004 pool.query('SELECT * FROM users WHERE username = $1', [complaint.by], (error, results) => {
1005 if (error) throw error;
1006
1007 if (results.rows.length > 0) {
1008 const userEmail = results.rows[0].email;
1009
1010 const message = {
1011 from: process.env.GOOGLE_EMAIL,
1012 to: userEmail,
1013 subject: "Caessino - Your complaint has been answered",
1014 html: `
1015 <h4>Hello, ${complaint.by}</h4>
1016 <p>You wrote a complaint on ${new Date(complaint.date).toGMTString()}, saying:</p>
1017 <blockquote><em>${complaint.description}</em></blockquote>
1018 <br/>
1019 <p>Your complaint has been listened to, here's what the admin has to say:<p>
1020 <blockquote><em>${complaint.answer}</em></blockquote>
1021 <br/>
1022 <p>We hope this fixes your issue,</p>
1023 <p>The Team ESS</p>
1024 `
1025 }
1026
1027 transporter.sendMail(message, (err, data) => {
1028 if (err) {
1029 console.log(err);
1030 }
1031 })
1032 }
1033 });
1034}
1035
1036/**
1037 * Admin session data
1038 */
1039 export var adminSessions = []
1040
1041/**
1042 * User session data
1043 */
1044export var sessions = []
1045
1046export function update_sessions_to_database() {
1047 pool.query('UPDATE sessions SET data = $1 WHERE identifier = $2', [JSON.stringify(sessions), 'sessions_data'], (error, results) => {
1048 if (error) throw error;
1049 });
1050}
1051
1052export function load_sessions_from_database() {
1053 pool.query('SELECT data FROM sessions WHERE identifier = $1', ['sessions_data'], (error, results) => {
1054 if (error) throw error;
1055
1056 sessions = JSON.parse(results?.rows[0]?.data || []);
1057 });
1058}
1059load_sessions_from_database();
1060
1061/**
1062 * Poker game data
1063 */
1064export var tables = []
1065
1066export function cleanTables() {
1067 tables = [];
1068}
1069
1070export function update_tables_to_database() {
1071 tables = tables.map(table => ({...table, turnTimeout: null}));
1072
1073 pool.query('UPDATE poker SET data = $1 WHERE identifier = $2', [JSON.stringify(tables), 'poker_data'], (error, results) => {
1074 if (error) throw error;
1075 });
1076}
1077
1078export async function load_tables_from_database() {
1079 pool.query('SELECT data FROM poker WHERE identifier = $1', ['poker_data'], (error, results) => {
1080 if (error) throw error;
1081
1082 tables = JSON.parse(results?.rows[0]?.data || []);
1083
1084 tables.forEach(table => {
1085 if (table.started) {
1086 progressRoundTillTheEnd(table.id);
1087 }
1088 })
1089
1090 tables.forEach(table => {
1091 if (table.ended) {
1092 table.players?.forEach(player => {
1093 if (!player.isGhost) {
1094 sendMailForGameCompletition('poker', player.username, player.displayName);
1095 }
1096 })
1097 }
1098 })
1099
1100 cleanTables();
1101
1102 update_tables_to_database();
1103 });
1104}
1105load_tables_from_database();
1106
1107/**
1108 * Roulette game data
1109 */
1110export var game = {}
1111
1112export function update_game_to_database() {
1113 pool.query('UPDATE roulette SET data = $1 WHERE identifier = $2', [JSON.stringify(game), 'roulette_data'], (error, results) => {
1114 if (error) throw error;
1115 });
1116}
1117
1118export async function load_game_from_database() {
1119 pool.query('SELECT data FROM roulette WHERE identifier = $1', ['roulette_data'], (error, results) => {
1120 if (error) throw error;
1121
1122 game = JSON.parse(results?.rows[0]?.data || []);
1123
1124 game.players?.forEach(player => {
1125 sendMailForGameCompletition('roulette', player.username, player.name);
1126 })
1127
1128 game.loaded = true;
1129 });
1130}
1131load_game_from_database();
1132
1133/**
1134 * Blackjack game data
1135 */
1136export var rooms = []
1137
1138export function update_rooms_to_database() {
1139 let tmpRooms = [];
1140
1141 for (let key in rooms) {
1142 if (key === "loaded") continue ;
1143
1144 tmpRooms.push(rooms[key]);
1145 tmpRooms[tmpRooms.length - 1].id = key;
1146 }
1147
1148 pool.query('UPDATE blackjack SET data = $1 WHERE identifier = $2', [JSON.stringify(tmpRooms), 'blackjack_data'], (error, results) => {
1149 if (error) throw error;
1150 });
1151}
1152
1153export async function load_rooms_from_database() {
1154 pool.query('SELECT data FROM blackjack WHERE identifier = $1', ['blackjack_data'], (error, results) => {
1155 if (error) throw error;
1156
1157 if (results?.rows[0]?.data) {
1158 const tmpRooms = JSON.parse(results.rows[0].data);
1159
1160 tmpRooms.forEach(room => {
1161 rooms[room.id] = {...room, id: ''}
1162 })
1163
1164 tmpRooms.forEach(room => {
1165 sendMailForGameCompletition('blackjack', room.username, room.displayName);
1166 })
1167
1168 rooms["loaded"] = true;
1169 }
1170 });
1171}
1172load_rooms_from_database();
Note: See TracBrowser for help on using the repository browser.