source: pages/api/postgre/index.js@ 285c3cc

main
Last change on this file since 285c3cc was 285c3cc, checked in by anastasovv <simon@…>, 2 years ago

Removed double client-side api requests

  • Property mode set to 100644
File size: 12.9 KB
Line 
1import { v4 as uuidv4 } from 'uuid';
2
3import axios from 'axios';
4
5require('dotenv').config();
6
7const crypto = require('crypto');
8
9const Pool = require('pg').Pool
10const pool = new Pool({
11 connectionString: `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}/${process.env.POSTGRES_DB}`
12});
13
14const sessions = []
15// example session = { id, displayName, username, credits, lastActivity }
16
17export default function handler(req, res) {
18 /**
19 * GET method
20 */
21 if (req.method === 'GET') {
22 /**
23 * /---------------------- GET ----------------------/
24 * If the player won credits, update them in the database.
25 * Also, update the stats in the database.
26 * @action give_credits
27 * @param session_id
28 * @param credits
29 */
30 if (req.query?.action === 'add_credits' && req.query?.session_id && req.query?.credits) {
31 const session_id = req.query.session_id
32 const session = sessions.find(session => session.id === session_id)
33
34 if (session) {
35 session.lastActivity = Date.now();
36
37 if (parseInt(req.query.credits) > 0) {
38 session.credits = session.credits + parseInt(req.query.credits)
39
40 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
41 if (error) throw error;
42 });
43 }
44
45 if (req.query?.dont_update_stats) {
46 // continue
47 } else {
48 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
49 if (error) throw error;
50
51 if (results.rows.length > 0) {
52 const stats = results.rows[0]
53
54 if (parseInt(req.query.credits) > 0) {
55 pool.query('UPDATE stats SET money_earned = $1 WHERE username = $2', [parseInt(stats.money_earned) + parseInt(req.query.credits), session.username], (error, results) => {
56 if (error) throw error;
57 });
58 }
59
60 if (req.query?.game === 'blackjack') {
61 if (req.query?.outcome === 'player_busted' || req.query?.outcome === 'player_lost') {
62 pool.query('UPDATE stats SET blackjack_games = $1 WHERE username = $2', [parseInt(stats.blackjack_games) + 1, session.username], (error, results) => {
63 if (error) throw error;
64 });
65 }
66 else if (req.query?.outcome === 'dealer_busted' || req.query?.outcome === 'player_won') {
67 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) => {
68 if (error) throw error;
69 });
70 }
71 }
72 }
73 });
74 }
75
76 res.json({
77 success: true,
78 credits: session.credits,
79 })
80
81 return ;
82 }
83
84 res.json({
85 success: false,
86 })
87 }
88
89 /**
90 * /---------------------- GET ----------------------/
91 * The player lost credits, update this in the database.
92 * @action take_credits
93 * @param session_id
94 * @param credits
95 */
96 if (req.query?.action === 'take_credits' && req.query?.session_id && req.query?.credits) {
97 const session_id = req.query.session_id
98 const session = sessions.find(session => session.id === session_id)
99
100 if (session) {
101 session.lastActivity = Date.now();
102
103 session.credits = session.credits - parseInt(req.query.credits)
104
105 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
106 if (error) throw error;
107 });
108
109 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
110 if (error) throw error;
111
112 if (results.rows.length > 0) {
113 const stats = results.rows[0]
114
115 pool.query('UPDATE stats SET money_bet = $1 WHERE username = $2', [parseInt(stats.money_bet) + parseInt(req.query.credits), session.username], (error, results) => {
116 if (error) throw error;
117 });
118 }
119 });
120
121 res.json({
122 success: true,
123 credits: session.credits,
124 })
125 return ;
126 }
127
128 res.json({
129 success: false,
130 })
131 }
132
133 /**
134 * /---------------------- GET ----------------------/
135 * Get stats for the player, so we can display them in the front end.
136 * @action get_stats
137 * @param session_id
138 */
139 if (req.query?.action === 'get_stats' && req.query?.session_id) {
140 const session_id = req.query.session_id
141 const session = sessions.find(session => session.id === session_id)
142
143 if (session) {
144 session.lastActivity = Date.now();
145
146 pool.query('SELECT * FROM stats WHERE username = $1', [session.username], (error, results) => {
147 if (error) throw error;
148
149 if (results.rows.length > 0) {
150 res.json({
151 success: true,
152 stats: results.rows[0],
153 })
154 }
155 else {
156 res.json({
157 success: false,
158 })
159 }
160 });
161
162 return ;
163 }
164
165 res.json({
166 success: false,
167 })
168 }
169
170 /**
171 * /---------------------- GET ----------------------/
172 * Checks if the player is logged in, and returns his session if so.
173 * @action check_if_logged_in
174 * @param session_id
175 */
176 if (req.query?.action === 'check_if_logged_in' && req.query?.session_id) {
177 const session_id = req.query.session_id
178 const session = sessions.find(session => session.id === session_id)
179
180 if (session) {
181 res.json({
182 success: true,
183 displayName: session.displayName,
184 session_id: session.id,
185 credits: session.credits,
186 })
187 return ;
188 }
189
190 res.json({
191 success: false,
192 })
193 }
194
195 /**
196 * /---------------------- GET ----------------------/
197 * Takes the credits in the player's session, and updates the database.
198 * Logs the player out and kills the session.
199 * @action logout
200 * @param session_id
201 */
202 if (req.query?.action === 'logout' && req.query?.session_id) {
203 const session_id = req.query.session_id
204 const session = sessions.find(session => session.id === session_id)
205
206 if (session) {
207 pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
208 if (error) throw error;
209 });
210
211 sessions.splice(sessions.indexOf(session), 1);
212
213 axios.get(`${process.env.HOME_URL}/api/blackjack/?action=remove_room&session_id=${session_id}`);
214 }
215
216 res.json({
217 success: true,
218 message: 'Successfully logged out',
219 })
220 }
221 }
222
223 /**
224 * POST method
225 */
226 if (req.method === 'POST') {
227 const { body } = req;
228
229 /**
230 * /---------------------- POST ----------------------/
231 * Checks if the entered account info is good, and registers a new user in the database if so.
232 * @action register
233 * @param username
234 * @param displayName
235 * @param password
236 */
237 if (body?.action === 'register') {
238 // checks
239 if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
240 res.json({
241 success: false,
242 message: 'Username is required',
243 });
244 return ;
245 }
246 if (/[^a-zA-Z]/g.test(body?.username)) {
247 res.json({
248 success: false,
249 message: 'Username must contain only letters',
250 })
251 return ;
252 }
253 if (body?.displayName == "undefined" || body?.displayName == "null" || body?.displayName == "") {
254 res.json({
255 success: false,
256 message: 'Display name is required',
257 });
258 return ;
259 }
260 if (body?.displayName?.toLowerCase() === "guest") {
261 res.json({
262 success: false,
263 message: 'Display name cannot be guest',
264 });
265 return ;
266 }
267 if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
268 res.json({
269 success: false,
270 message: 'Password is required',
271 });
272 return ;
273 }
274
275 // everything's okay
276 body.username = body.username.toLowerCase()
277
278 // hash password
279 const salt = crypto.randomBytes(16).toString('hex');
280 const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
281
282 // check if user already exists
283 pool.query('SELECT * FROM users WHERE username = $1', [body.username], (error, results) => {
284 if (error) throw error;
285
286 if (results.rows.length > 0) {
287 res.json({
288 success: false,
289 message: 'Username already exists',
290 });
291 return ;
292 }
293
294 // store user in database
295 pool.query('INSERT INTO users (username, password, salt) VALUES ($1, $2, $3)', [body.username, hashedPassword, salt], (error, usersResults) => {
296 if (error) throw error;
297
298 pool.query('INSERT INTO players (username, display_name, credits) VALUES ($1, $2, $3)', [body.username, body.displayName, 1000], (error, playersResults) => {
299 if (error) throw error;
300
301 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) => {
302 if (error) throw error;
303
304 res.json({
305 success: true,
306 message: 'Registration successful',
307 });
308 return ;
309 });
310 });
311 });
312 });
313 }
314
315 /**
316 * /---------------------- POST ----------------------/
317 * Checks if the entered account info is good, and logs the user in if so.
318 * @action login
319 * @param username
320 * @param password
321 */
322 if (body?.action === 'login') {
323 // checks
324 if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
325 res.json({
326 success: false,
327 message: 'Username is required',
328 });
329 return ;
330 }
331 if (/[^a-zA-Z]/g.test(body?.username)) {
332 res.json({
333 success: false,
334 message: 'Username must contain only letters',
335 })
336 return ;
337 }
338 if (body?.password == "undefined" || body?.password == "null" || body?.password == "") {
339 res.json({
340 success: false,
341 message: 'Password is required',
342 });
343 return ;
344 }
345
346 // everything's okay
347 body.username = body.username.toLowerCase();
348
349 // check if user exists
350 pool.query('SELECT * FROM users WHERE username = $1', [body.username], (error, usersResults) => {
351 if (error) throw error;
352
353 if (usersResults.rows.length === 0) {
354 res.json({
355 success: false,
356 message: 'User does not exist. Try Registering instead.',
357 });
358 return ;
359 }
360 else {
361 if (usersResults.rows.length > 0) {
362 const user = usersResults.rows[0];
363 const salt = user.salt;
364 const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
365
366 if (hashedPassword === user.password) {
367 pool.query('SELECT * FROM players WHERE username = $1', [body.username], (error, playersResults) => {
368 if (playersResults.rows.length > 0) {
369 let session = sessions.find(session => session.username === playersResults.rows[0].username)
370
371 if (session) {
372 // Already logged in
373 res.json({
374 success: false,
375 message: 'You are already logged in',
376 })
377 }
378 else {
379 // create a session
380 session = {
381 id: uuidv4(),
382 displayName: playersResults.rows[0].display_name,
383 username: playersResults.rows[0].username,
384 credits: playersResults.rows[0].credits,
385 lastActivity: Date.now(),
386 }
387
388 sessions.push(session);
389
390 res.json({
391 success: true,
392 message: 'Login successful',
393 session: session,
394 })
395 }
396
397 return ;
398 }
399 });
400 }
401 else {
402 res.json({
403 success: false,
404 message: 'Username and password do not match.',
405 });
406 }
407 }
408 }
409 });
410 }
411 }
412}
Note: See TracBrowser for help on using the repository browser.