source: pages/api/postgre/index.js@ 433e0c5

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

Added complaints, managing credits, and lost connection screens

  • Property mode set to 100644
File size: 23.6 KB
Line 
1import { v4 as uuidv4 } from 'uuid';
2
3import axios from 'axios';
4
5require('dotenv').config();
6
7const crypto = require('crypto');
8
9import { progressRoundTillTheEnd } from '../poker/tableSpecific';
10
11const Pool = require('pg').Pool
12const pool = new Pool({
13 connectionString: `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}/${process.env.POSTGRES_DB}`
14});
15
16export default function handler(req, res) {
17 /**
18 * GET method
19 */
20 if (req.method === 'GET') {
21 /**
22 * /---------------------- GET ----------------------/
23 * If the player won credits, update them in the database.
24 * Also, update the stats in the database.
25 * @action give_credits
26 * @param session_id
27 * @param credits
28 */
29 if (req.query?.action === 'add_credits' && req.query?.session_id && req.query?.credits) {
30 const session_id = req.query.session_id
31 const session = sessions.find(session => session.id === session_id)
32
33 if (session) {
34 session.lastActivity = Date.now();
35
36 if (parseInt(req.query.credits) > 0) {
37 session.credits = session.credits + parseInt(req.query.credits)
38
39 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
40 if (error) throw error;
41 });
42 }
43
44 if (req.query?.dont_update_stats) {
45 // continue
46 } else {
47 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
48 if (error) throw error;
49
50 if (results.rows.length > 0) {
51 const stats = results.rows[0]
52
53 if (parseInt(req.query.credits) > 0) {
54 pool.query('UPDATE stats SET money_earned = $1 WHERE username = $2', [parseInt(stats.money_earned) + parseInt(req.query.credits), session.username], (error, results) => {
55 if (error) throw error;
56 });
57 }
58
59 if (req.query?.game === 'blackjack') {
60 if (req.query?.outcome === 'player_busted' || req.query?.outcome === 'player_lost') {
61 pool.query('UPDATE stats SET blackjack_games = $1 WHERE username = $2', [parseInt(stats.blackjack_games) + 1, session.username], (error, results) => {
62 if (error) throw error;
63 });
64 }
65 else if (req.query?.outcome === 'dealer_busted' || req.query?.outcome === 'player_won') {
66 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) => {
67 if (error) throw error;
68 });
69 }
70 }
71 else if (req.query?.game === 'roulette') {
72 if (req.query?.outcome === 'lost') {
73 pool.query('UPDATE stats SET roulette_games = $1 WHERE username = $2', [parseInt(stats.roulette_games) + 1, session.username], (error, results) => {
74 if (error) throw error;
75 });
76 }
77 else if (req.query?.outcome === 'won') {
78 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) => {
79 if (error) throw error;
80 });
81 }
82 }
83 else if (req.query?.game === 'poker') {
84 if (req.query?.outcome === 'lost') {
85 pool.query('UPDATE stats SET poker_games = $1 WHERE username = $2', [parseInt(stats.poker_games) + 1, session.username], (error, results) => {
86 if (error) throw error;
87 });
88 }
89 else if (req.query?.outcome === 'won') {
90 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) => {
91 if (error) throw error;
92 });
93 }
94 }
95 }
96 });
97 }
98
99 update_sessions_to_database();
100
101 res.json({
102 success: true,
103 credits: session.credits,
104 })
105
106 return ;
107 }
108
109 res.json({
110 success: false,
111 })
112 }
113
114 /**
115 * /---------------------- GET ----------------------/
116 * The player lost credits, update this in the database.
117 * @action take_credits
118 * @param session_id
119 * @param credits
120 */
121 if (req.query?.action === 'take_credits' && req.query?.session_id && req.query?.credits) {
122 const session_id = req.query.session_id
123 const session = sessions.find(session => session.id === session_id)
124
125 let takeWhatYouCan = false;
126 if (req.query?.takeWhatYouCan === "true") takeWhatYouCan = true;
127
128 if (session) {
129 session.lastActivity = Date.now();
130
131 if (session.credits < parseInt(req.query.credits)) {
132 if (takeWhatYouCan) {
133 session.credits = 0;
134 }
135 else {
136 res.json({
137 success: false,
138 });
139
140 return ;
141 }
142 }
143 else {
144 session.credits = session.credits - parseInt(req.query.credits)
145 }
146
147 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
148 if (error) throw error;
149 });
150
151 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
152 if (error) throw error;
153
154 if (results.rows.length > 0) {
155 const stats = results.rows[0]
156
157 pool.query('UPDATE stats SET money_bet = $1 WHERE username = $2', [parseInt(stats.money_bet) + parseInt(req.query.credits), session.username], (error, results) => {
158 if (error) throw error;
159 });
160 }
161 });
162
163 update_sessions_to_database();
164
165 res.json({
166 success: true,
167 credits: session.credits,
168 })
169 return ;
170 }
171
172 res.json({
173 success: false,
174 })
175 }
176
177 /**
178 * /---------------------- GET ----------------------/
179 * Get stats for the player, so we can display them in the front end.
180 * @action get_stats
181 * @param session_id
182 */
183 if (req.query?.action === 'get_stats' && req.query?.session_id) {
184 const session_id = req.query.session_id
185 const session = sessions.find(session => session.id === session_id)
186
187 if (session) {
188 session.lastActivity = Date.now();
189
190 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
191 if (error) throw error;
192
193 if (results.rows.length > 0) {
194 res.json({
195 success: true,
196 stats: results.rows[0],
197 })
198 }
199 else {
200 res.json({
201 success: false,
202 })
203 }
204 });
205
206 return ;
207 }
208
209 res.json({
210 success: false,
211 })
212 }
213
214 /**
215 * /---------------------- GET ----------------------/
216 * Checks if the player is logged in, and returns his session if so.
217 * @action check_if_logged_in
218 * @param session_id
219 */
220 if (req.query?.action === 'check_if_logged_in' && req.query?.session_id) {
221 const session_id = req.query.session_id
222 const session = sessions.find(session => session.id === session_id)
223
224 if (session) {
225 res.json({
226 success: true,
227 displayName: session.displayName,
228 session_id: session.id,
229 credits: session.credits,
230 })
231 return ;
232 }
233
234 res.json({
235 success: false,
236 })
237 }
238
239 /**
240 * /---------------------- GET ----------------------/
241 * Takes the credits in the player's session, and updates the database.
242 * Logs the player out and kills the session.
243 * @action logout
244 * @param session_id
245 */
246 if (req.query?.action === 'logout' && req.query?.session_id) {
247 const session_id = req.query.session_id
248 const session = sessions.find(session => session.id === session_id)
249
250 if (session) {
251 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
252 if (error) throw error;
253 });
254
255 sessions.splice(sessions.indexOf(session), 1);
256
257 axios.get(`${process.env.HOME_URL}/api/blackjack/?action=remove_room&session_id=${session_id}`);
258
259 update_sessions_to_database();
260 }
261
262 res.json({
263 success: true,
264 message: 'Successfully logged out',
265 })
266 }
267 }
268
269 /**
270 * POST method
271 */
272 if (req.method === 'POST') {
273 const { body } = req;
274
275 /**
276 * /---------------------- POST ----------------------/
277 * Deposits money from credit card to game account.
278 * @action register
279 * @param session_id
280 * @param data
281 */
282 if (body?.action === 'deposit') {
283 // checks
284 if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
285 res.json({
286 success: false,
287 message: 'You are not logged in. Please log in first.',
288 });
289 return ;
290 }
291 if (body?.data?.name == "undefined" || body?.data?.name == "null" || body?.data?.name == "") {
292 res.json({
293 success: false,
294 message: 'Name field cannot be empty',
295 });
296 return ;
297 }
298 if (body?.data?.card == "undefined" || body?.data?.card == "null" || body?.data?.card == "") {
299 res.json({
300 success: false,
301 message: 'Card numbers field cannot be empty',
302 });
303 return ;
304 }
305 if (body?.data?.expire == "undefined" || body?.data?.expire == "null" || body?.data?.expire == "") {
306 res.json({
307 success: false,
308 message: 'Expiration date field cannot be empty',
309 });
310 return ;
311 }
312 if (body?.data?.ccv == "undefined" || body?.data?.ccv == "null" || body?.data?.ccv == "") {
313 res.json({
314 success: false,
315 message: 'CCV field cannot be empty',
316 });
317 return ;
318 }
319 if (body?.data?.amount == "undefined" || body?.data?.amount == "null" || body?.data?.amount == "") {
320 res.json({
321 success: false,
322 message: 'Amount field cannot be empty',
323 });
324 return ;
325 }
326
327 let session = sessions.find(session => session.id === body?.session_id)
328
329 if (session) {
330 if (parseInt(body.data.amount) > 0) {
331 session.credits = session.credits + parseInt(body.data.amount)
332
333 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
334 if (error) throw error;
335
336 res.json({
337 success: true,
338 credits: session.credits
339 })
340 });
341 }
342 }
343 }
344
345 /**
346 * /---------------------- POST ----------------------/
347 * Withdraws money from game account to personal account.
348 * @action register
349 * @param session_id
350 * @param data
351 */
352 if (body?.action === 'withdraw') {
353 // checks
354 if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
355 res.json({
356 success: false,
357 message: 'You are not logged in. Please log in first.',
358 });
359 return ;
360 }
361 if (body?.data?.citibank == "undefined" || body?.data?.citibank == "null" || body?.data?.citibank == "") {
362 res.json({
363 success: false,
364 message: 'Bank name field cannot be empty',
365 });
366 return ;
367 }
368 if (body?.data?.iban == "undefined" || body?.data?.iban == "null" || body?.data?.iban == "") {
369 res.json({
370 success: false,
371 message: 'IBAN code field cannot be empty',
372 });
373 return ;
374 }
375 if (body?.data?.bic == "undefined" || body?.data?.bic == "null" || body?.data?.bic == "") {
376 res.json({
377 success: false,
378 message: 'BIC code field cannot be empty',
379 });
380 return ;
381 }
382 if (body?.data?.beneficiary == "undefined" || body?.data?.beneficiary == "null" || body?.data?.beneficiary == "") {
383 res.json({
384 success: false,
385 message: 'Beneficiary name field cannot be empty',
386 });
387 return ;
388 }
389 if (body?.data?.address == "undefined" || body?.data?.address == "null" || body?.data?.address == "") {
390 res.json({
391 success: false,
392 message: 'Bank address field cannot be empty',
393 });
394 return ;
395 }
396 if (body?.data?.amount == "undefined" || body?.data?.amount == "null" || body?.data?.amount == "") {
397 res.json({
398 success: false,
399 message: 'Amount field cannot be empty',
400 });
401 return ;
402 }
403
404 let session = sessions.find(session => session.id === body?.session_id)
405
406 if (session) {
407 if (parseInt(body.data.amount) > 0) {
408 session.credits = Math.max(session.credits - parseInt(body.data.amount), 0)
409
410 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
411 if (error) throw error;
412
413 res.json({
414 success: true,
415 credits: session.credits
416 })
417 });
418 }
419 }
420 }
421
422 /**
423 * /---------------------- POST ----------------------/
424 * Sends a complaint.
425 * @action complain
426 * @param session_id
427 * @param description
428 */
429 if (body?.action === 'complain') {
430 // checks
431 if (body?.session_id == "undefined" || body?.session_id == "null" || body?.session_id == "") {
432 res.json({
433 success: false,
434 message: 'You are not logged in. Please log in first.',
435 });
436 return ;
437 }
438 if (body?.description == "undefined" || body?.description == "null" || body?.description == "") {
439 res.json({
440 success: false,
441 message: 'You cannot submit an empty complaint.',
442 });
443 return ;
444 }
445
446 let session = sessions.find(session => session.id === body.session_id)
447
448 if (session) {
449 // date, by, description, answered
450 const date = new Date();
451 pool.query('INSERT INTO complaints (date, by, description, answered) VALUES ($1, $2, $3, $4)', [date, session.username, body.description, false], (error, complaintResults) => {
452 if (error) throw error;
453
454 res.json({
455 success: true,
456 })
457 });
458 }
459 }
460
461 /**
462 * /---------------------- POST ----------------------/
463 * Checks if the entered account info is good, and registers a new user in the database if so.
464 * @action register
465 * @param username
466 * @param displayName
467 * @param password
468 */
469 if (body?.action === 'register') {
470 // checks
471 if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
472 res.json({
473 success: false,
474 message: 'Username is required',
475 });
476 return ;
477 }
478 if (/[^a-zA-Z]/g.test(body?.username)) {
479 res.json({
480 success: false,
481 message: 'Username must contain only letters',
482 })
483 return ;
484 }
485 if (body?.displayName == "undefined" || body?.displayName == "null" || body?.displayName == "") {
486 res.json({
487 success: false,
488 message: 'Display name is required',
489 });
490 return ;
491 }
492 if (body?.displayName?.toLowerCase() === "guest") {
493 res.json({
494 success: false,
495 message: 'Display name cannot be guest',
496 });
497 return ;
498 }
499 if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
500 res.json({
501 success: false,
502 message: 'Password is required',
503 });
504 return ;
505 }
506
507 // everything's okay
508 body.username = body.username.toLowerCase()
509
510 // hash password
511 const salt = crypto.randomBytes(16).toString('hex');
512 const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
513
514 // check if user already exists
515 pool.query('SELECT * FROM users WHERE username = $1', [body.username], (error, results) => {
516 if (error) throw error;
517
518 if (results.rows.length > 0) {
519 res.json({
520 success: false,
521 message: 'Username already exists',
522 });
523 return ;
524 }
525
526 // store user in database
527 pool.query('INSERT INTO users (username, password, salt) VALUES ($1, $2, $3)', [body.username, hashedPassword, salt], (error, usersResults) => {
528 if (error) throw error;
529
530 pool.query('INSERT INTO players (username, display_name, credits) VALUES ($1, $2, $3)', [body.username, body.displayName, 1000], (error, playersResults) => {
531 if (error) throw error;
532
533 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) => {
534 if (error) throw error;
535
536 res.json({
537 success: true,
538 message: 'Registration successful',
539 });
540 return ;
541 });
542 });
543 });
544 });
545 }
546
547 /**
548 * /---------------------- POST ----------------------/
549 * Checks if the entered account info is good, and logs the user in if so.
550 * @action login
551 * @param username
552 * @param password
553 */
554 if (body?.action === 'login') {
555 // checks
556 if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
557 res.json({
558 success: false,
559 message: 'Username is required',
560 });
561 return ;
562 }
563 if (/[^a-zA-Z]/g.test(body?.username)) {
564 res.json({
565 success: false,
566 message: 'Username must contain only letters',
567 })
568 return ;
569 }
570 if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
571 res.json({
572 success: false,
573 message: 'Password is required',
574 });
575 return ;
576 }
577
578 // everything's okay
579 body.username = body.username.toLowerCase();
580
581 // check if user exists
582 pool.query('SELECT * FROM users WHERE username = $1', [body.username], (error, usersResults) => {
583 if (error) throw error;
584
585 if (usersResults.rows.length === 0) {
586 res.json({
587 success: false,
588 message: 'User does not exist. Try Registering instead.',
589 });
590 return ;
591 }
592 else {
593 if (usersResults.rows.length > 0) {
594 const user = usersResults.rows[0];
595 const salt = user.salt;
596 const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
597
598 if (hashedPassword === user.password) {
599 pool.query('SELECT * FROM players WHERE username = $1', [body.username], (error, playersResults) => {
600 if (playersResults.rows.length > 0) {
601 let session = sessions.find(session => session.username === playersResults.rows[0].username)
602
603 if (session) {
604 // Already logged in
605 res.json({
606 success: true,
607 message: 'Login successful',
608 session: session,
609 })
610 }
611 else {
612 // create a session
613 session = {
614 id: uuidv4(),
615 displayName: playersResults.rows[0].display_name,
616 username: playersResults.rows[0].username,
617 credits: playersResults.rows[0].credits,
618 lastActivity: Date.now(),
619 }
620
621 sessions.push(session);
622
623 update_sessions_to_database();
624
625 res.json({
626 success: true,
627 message: 'Login successful',
628 session: session,
629 })
630 }
631
632 return ;
633 }
634 });
635 }
636 else {
637 res.json({
638 success: false,
639 message: 'Username and password do not match.',
640 });
641 }
642 }
643 }
644 });
645 }
646 }
647}
648
649
650/**
651 * User session data
652 */
653export var sessions = []
654
655export function update_sessions_to_database() {
656 pool.query('UPDATE sessions SET data = $1 WHERE identifier = $2', [JSON.stringify(sessions), 'sessions_data'], (error, results) => {
657 if (error) throw error;
658 });
659}
660
661export function load_sessions_from_database() {
662 pool.query('SELECT data FROM sessions WHERE identifier = $1', ['sessions_data'], (error, results) => {
663 if (error) throw error;
664
665 sessions = JSON.parse(results?.rows[0]?.data || []);
666 });
667}
668load_sessions_from_database();
669
670/**
671 * Poker game data
672 */
673export var tables = []
674
675export function cleanTables() {
676 tables = [];
677}
678
679export function update_tables_to_database() {
680 tables = tables.map(table => ({...table, turnTimeout: null}));
681
682 pool.query('UPDATE poker SET data = $1 WHERE identifier = $2', [JSON.stringify(tables), 'poker_data'], (error, results) => {
683 if (error) throw error;
684 });
685}
686
687export async function load_tables_from_database() {
688 pool.query('SELECT data FROM poker WHERE identifier = $1', ['poker_data'], (error, results) => {
689 if (error) throw error;
690
691 tables = JSON.parse(results?.rows[0]?.data || []);
692
693 tables.forEach(table => {
694 if (table.started) {
695 progressRoundTillTheEnd(table.id);
696 }
697 })
698
699 cleanTables();
700
701 update_tables_to_database();
702 });
703}
704load_tables_from_database();
705
706/**
707 * Roulette game data
708 */
709export var game = {}
710
711export function update_game_to_database() {
712 pool.query('UPDATE roulette SET data = $1 WHERE identifier = $2', [JSON.stringify(game), 'roulette_data'], (error, results) => {
713 if (error) throw error;
714 });
715}
716
717export async function load_game_from_database() {
718 pool.query('SELECT data FROM roulette WHERE identifier = $1', ['roulette_data'], (error, results) => {
719 if (error) throw error;
720
721 game = JSON.parse(results?.rows[0]?.data || []);
722
723 game.loaded = true;
724 });
725}
726load_game_from_database();
727
728/**
729 * Blackjack game data
730 */
731export var rooms = []
732
733export function update_rooms_to_database() {
734 let tmpRooms = [];
735
736 for (let key in rooms) {
737 if (key === "loaded") continue ;
738
739 tmpRooms.push(rooms[key]);
740 tmpRooms[tmpRooms.length - 1].id = key;
741 }
742
743 pool.query('UPDATE blackjack SET data = $1 WHERE identifier = $2', [JSON.stringify(tmpRooms), 'blackjack_data'], (error, results) => {
744 if (error) throw error;
745 });
746}
747
748export async function load_rooms_from_database() {
749 pool.query('SELECT data FROM blackjack WHERE identifier = $1', ['blackjack_data'], (error, results) => {
750 if (error) throw error;
751
752 if (results?.rows[0]?.data) {
753 const tmpRooms = JSON.parse(results.rows[0].data);
754
755 tmpRooms.forEach(room => {
756 rooms[room.id] = {...room, id: ''}
757 })
758
759 rooms["loaded"] = true;
760 }
761 });
762}
763load_rooms_from_database();
764
Note: See TracBrowser for help on using the repository browser.