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

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

Code cleanings

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