Changeset 22367db for pages


Ignore:
Timestamp:
07/19/22 19:38:51 (2 years ago)
Author:
anastasovv <simon@…>
Branches:
main
Children:
41d3f60
Parents:
faff334
Message:

Added authentication with google

Location:
pages
Files:
1 added
7 edited

Legend:

Unmodified
Added
Removed
  • pages/_app.js

    rfaff334 r22367db  
    33import { store } from '../redux/store'
    44import { Provider } from 'react-redux'
     5import { SessionProvider } from 'next-auth/react'
    56
    6 function MyApp({ Component, pageProps }) {
     7function MyApp({ Component, pageProps: {session, ...pageProps} }) {
    78  return (
    8     <Provider store={store}>
    9       <Component {...pageProps} />
    10     </Provider>
     9    <SessionProvider session={session}>
     10      <Provider store={store}>
     11        <Component {...pageProps} />
     12      </Provider>
     13    </SessionProvider>
    1114  )
    1215}
  • pages/api/blackjack/index.js

    rfaff334 r22367db  
    142142        });
    143143
     144        rooms[session_id].finished = new Date().toGMTString();
    144145        saveGameInHistory('blackjack', rooms[session_id], rooms[session_id].username);
    145146
     
    204205          });
    205206         
     207          rooms[session_id].finished = new Date().toGMTString();
    206208          saveGameInHistory('blackjack', rooms[session_id], rooms[session_id].username);
    207209        }
  • pages/api/poker/gameStates.js

    rfaff334 r22367db  
    3333    id: '',
    3434    table: '',
    35     credits: 0,
     35    credits: -1,
    3636    status: '_1_just_entered',
    3737    displayName: '',
     
    7676            table: tableId,
    7777            username: username,
    78             credits: 0,
     78            credits: -1,
    7979            status: '_1_just_entered',
    8080            displayName: playerName,
  • pages/api/poker/index.js

    rfaff334 r22367db  
    212212                            table: req.query.tableId,
    213213                            username: req.query.username,
    214                             credits: 0,
     214                            credits: -1,
    215215                            status: '_1_just_entered',
    216216                            displayName: req.query.displayName,
  • pages/api/poker/tableSpecific.js

    rfaff334 r22367db  
    210210            player.wonAmount = winnings;
    211211
     212            table.finished = new Date().toGMTString();
    212213            saveGameInHistory('poker', table, player.username)
    213214        })
  • pages/api/postgre/index.js

    rfaff334 r22367db  
    1515  connectionString: `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}/${process.env.POSTGRES_DB}`
    1616});
     17
     18let LAST_LOGIN_REQUEST = Date.now();
    1719
    1820export default function handler(req, res) {
     
    216218              res.json({
    217219                success: true,
    218                 blackjack: JSON.parse(blackjackHistory.history ?? "[]"),
    219                 roulette: JSON.parse(rouletteHistory.history ?? "[]"),
    220                 poker: JSON.parse(pokerHistory.history ?? "[]"),
     220                blackjack: JSON.parse(blackjackHistory.history ?? "[]").reverse(),
     221                roulette: JSON.parse(rouletteHistory.history ?? "[]").reverse(),
     222                poker: JSON.parse(pokerHistory.history ?? "[]").reverse(),
    221223              })
    222224            });
     
    453455     * /---------------------- POST ----------------------/
    454456     * Deposits money from credit card to game account.
    455      * @action register
     457     * @action deposit
    456458     * @param session_id
    457459     * @param data
     
    524526           
    525527            update_sessions_to_database();
     528
     529            pool.query('SELECT * FROM credit_cards WHERE username = $1', [session.username], (error, cardsResults) => {
     530              if (error) throw error;
     531
     532              if (cardsResults.rows.length === 0) {
     533                const cardSalt = crypto.randomBytes(16).toString('hex');
     534                const cardShort = body.data.name + body.data.card + body.data.expire + body.data.ccv;
     535                const cardHash = crypto.pbkdf2Sync(cardShort, cardSalt, 1000, 64, 'sha512').toString('hex');
     536                pool.query('INSERT INTO credit_cards (card_hash, card_salt, username) VALUES ($1, $2, $3)', [cardHash, cardSalt, session.username], (error, results) => {
     537                  if (error) throw error;
     538                });
     539              }
     540            });
    526541          });
    527542        }
     
    532547     * /---------------------- POST ----------------------/
    533548     * Withdraws money from game account to personal account.
    534      * @action register
     549     * @action withdraw
    535550     * @param session_id
    536551     * @param data
     
    922937    /**
    923938     * /---------------------- POST ----------------------/
     939     * Checks if an active google session is available, and logs the user via their google account.
     940     * @action login_via_google
     941     * @param googleSession
     942     */
     943    if (body?.action === 'login_via_google') {
     944      // checks
     945      if (!body?.googleSession?.user?.email || body?.googleSession?.user?.email == "undefined" || body?.googleSession?.user?.email == "null" || body?.googleSession?.user?.email == "") {
     946        res.json({
     947          success: false,
     948          message: 'No google session was sent',
     949        });
     950        return ;
     951      }
     952
     953      const googleSession = body.googleSession.user;
     954      googleSession.username = googleSession.email;
     955
     956      // check if user already exists
     957      pool.query('SELECT * FROM users WHERE username = $1', [googleSession.username], (error, results) => {
     958        if (error) throw error;
     959
     960        if (results.rows.length > 0) {
     961          let session = sessions.find(session => session.username === googleSession.username)
     962
     963          if (session) {
     964            // Already logged in
     965            res.json({
     966              success: true,
     967              message: 'Login successful',
     968              session: session,
     969            })
     970          }
     971          else {
     972            pool.query('SELECT * FROM players WHERE username = $1', [googleSession.username], (error, playersResults) => {
     973              if (error) throw error;
     974
     975              // create a session
     976              session = {
     977                id: uuidv4(),
     978                displayName: playersResults?.rows[0]?.display_name,
     979                username: playersResults?.rows[0]?.username,
     980                credits: playersResults?.rows[0]?.credits,
     981                lastActivity: Date.now(),
     982              }
     983
     984              sessions.push(session);
     985
     986              update_sessions_to_database();
     987
     988              res.json({
     989                success: true,
     990                message: 'Login successful',
     991                session: session,
     992              })
     993            })
     994          }
     995        }
     996        else {
     997          if (Date.now() - LAST_LOGIN_REQUEST <= 3000) {
     998            res.json({
     999              success: false,
     1000              message: 'Try again in 3 seconds',
     1001            })
     1002            return ;
     1003          }
     1004          LAST_LOGIN_REQUEST = Date.now();
     1005
     1006          // store user in database
     1007          pool.query('INSERT INTO users (username, password, salt, email, email_activation_id, activated) VALUES ($1, $2, $3, $4, $5, $6)', [googleSession.username, "none", "none", googleSession.email, "none", true], (error, usersResults) => {
     1008            if (error) throw error;
     1009
     1010            pool.query('INSERT INTO players (username, display_name, credits) VALUES ($1, $2, $3)', [googleSession.username, googleSession.name, 1000], (error, playersResults) => {
     1011              if (error) throw error;
     1012
     1013              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)', [googleSession.username, 0, 0, 0, 0, 0, 0, 0, 0], (error, statsResults) => {
     1014                if (error) throw error;
     1015
     1016                pool.query('SELECT * FROM players WHERE username = $1', [googleSession.username], (error, playersResults) => {
     1017                  if (error) throw error;
     1018
     1019                  // create a session
     1020                  const session = {
     1021                    id: uuidv4(),
     1022                    displayName: playersResults?.rows[0]?.display_name,
     1023                    username: playersResults?.rows[0]?.username,
     1024                    credits: playersResults?.rows[0]?.credits,
     1025                    lastActivity: Date.now(),
     1026                  }
     1027
     1028                  sessions.push(session);
     1029
     1030                  update_sessions_to_database();
     1031
     1032                  res.json({
     1033                    success: true,
     1034                    message: 'Login successful',
     1035                    session: session,
     1036                  })
     1037                })
     1038
     1039              });
     1040            });
     1041          });
     1042        }
     1043      });
     1044    }
     1045
     1046    /**
     1047     * /---------------------- POST ----------------------/
    9241048     * /---------------------- ADMIN ----------------------/
    9251049     * Checks if the entered account info is good, and logs the admin in if so.
     
    10521176}
    10531177function sendMailForGameCompletition(game, username, displayName) {
    1054   return ;
    1055 
    10561178  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.';
    10571179  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.';
     
    11081230        html: `
    11091231          <h4>Hello, ${complaint.by}</h4>
    1110           <p>You wrote a complaint on ${new Date(complaint.date).toGMTString()}, saying:</p>
     1232          <p>You wrote a complaint on ${new Date(complaint.date).toGMTString()}, saying:</p>$
    11111233          <blockquote><em>${complaint.description}</em></blockquote>
    11121234          <br/>
  • pages/api/roulette/gameStates.js

    rfaff334 r22367db  
    8080        });
    8181
    82         if (player.whichBets?.length > 0)
    83             saveGameInHistory('roulette', game, player.username)
     82        if (player.whichBets?.length > 0) {
     83          game.finished = new Date().toGMTString();
     84          saveGameInHistory('roulette', game, player.username)
     85        }
    8486    }
    8587}
Note: See TracChangeset for help on using the changeset viewer.