Changeset e007fcd for pages


Ignore:
Timestamp:
07/16/22 21:31:18 (2 years ago)
Author:
anastasovv <simon@…>
Branches:
main
Children:
e903234
Parents:
55701f0
Message:

Now you need to activate your account via email & also added mail sending after server crash

Location:
pages
Files:
3 added
7 edited

Legend:

Unmodified
Added
Removed
  • pages/api/blackjack/gameStates.js

    r55701f0 re007fcd  
    1414export let game = {
    1515  credits: -1,
     16  username: '',
     17  displayName: '',
    1618  deck: [...deck],
    1719  status: '_1_room_created',      // statuses: _1_room_created, _2_made_initial_bet, _3_made_side_bet, _4_cards_on_the_table, _5_game_over
  • pages/api/blackjack/index.js

    r55701f0 re007fcd  
    1111 * Set up a room
    1212 */
    13 function createARoom(session_id) {
     13function createARoom(session_id, displayName, username) {
    1414  let room = {
    15     ...game, playerCards: [...game.playerCards], dealerCards: [...game.dealerCards],
     15    ...game, displayName: displayName, username: username, playerCards: [...game.playerCards], dealerCards: [...game.dealerCards],
    1616  }
    1717
     
    241241        rooms[session_id] = room;
    242242
     243        update_rooms_to_database();
     244
    243245        if (room.sideBetName !== '' && room.sideBetName !== 'none') {
    244246          room.sideBetEarnings = calculateSideBetEarnings(room);
     
    257259         
    258260          rooms[session_id] = room;
    259 
    260           update_rooms_to_database();
    261261
    262262          axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${session_id}&credits=${room.sideBetEarnings}`).then(postgreRes => {
     
    348348    /**
    349349     * /---------------------- GET ----------------------/
    350      * Remove a room from the rooms array.
    351      * @action remove_room
    352      * @param session_id
    353      */
    354     if (req.query.action === 'remove_room' && req.query?.session_id) {
    355       const session_id = req.query.session_id;
    356 
    357       if (rooms[session_id] !== undefined) {
    358         delete rooms[session_id];
    359       }
    360      
    361       res.json({
    362         success: true,
    363       })
    364            
    365       update_rooms_to_database();
    366     }
    367 
    368     /**
    369      * /---------------------- GET ----------------------/
    370350     * Updates the state periodically
    371351     * @action update_state
     
    399379          }
    400380          else {
    401             createARoom(session_id);
     381            createARoom(session_id, postgreRes.data?.displayName, postgreRes.data?.username);
    402382          }
    403383   
  • pages/api/poker/gameStates.js

    r55701f0 re007fcd  
    5454 */
    5555
    56 export function createTable(playerId, playerName, tableName) {
     56export function createTable(playerId, playerName, tableName, username) {
    5757    const tableId = uuidv4();
    5858
     
    7575            id: playerId,
    7676            table: tableId,
     77            username: username,
    7778            credits: 0,
    7879            status: '_1_just_entered',
  • pages/api/poker/index.js

    r55701f0 re007fcd  
    198198         * @param tableId
    199199         * @param displayName
    200          */
    201          if (req.query.action === 'join_a_table' && req.query?.session_id && req.query?.tableId && req.query?.displayName) {
     200         * @param username
     201         */
     202         if (req.query.action === 'join_a_table' && req.query?.session_id && req.query?.tableId && req.query?.displayName && req.query?.username) {
    202203            if (req.query.tableId.length > 0) {
    203204                const { success } = getTableAndPlayer(req.query.session_id);
     
    210211                            id: req.query.session_id,
    211212                            table: req.query.tableId,
     213                            username: req.query.username,
    212214                            credits: 0,
    213215                            status: '_1_just_entered',
     
    241243         * @param displayName
    242244         * @param tableName
    243          */
    244         if (req.query.action === 'create_a_table' && req.query?.session_id && req.query?.displayName && req.query?.tableName) {
     245         * @param username
     246         */
     247        if (req.query.action === 'create_a_table' && req.query?.session_id && req.query?.displayName && req.query?.tableName && req.query?.username) {
    245248            const { success } = getTableAndPlayer(req.query.session_id);
    246249
    247250            if (!success) {
    248                 createTable(req.query.session_id, req.query.displayName, req.query.tableName);
     251                createTable(req.query.session_id, req.query.displayName, req.query.tableName, req.query.username);
    249252            }
    250253
     
    305308                        success: true,
    306309                        displayName: postgreRes.data?.displayName,
     310                        username: postgreRes.data?.username,
    307311                        session_id: postgreRes.data?.session_id,
    308312                        credits: postgreRes.data?.credits,
  • pages/api/postgre/index.js

    r55701f0 re007fcd  
    66
    77const crypto = require('crypto');
     8
     9const nodemailer = require('nodemailer');
    810
    911import { progressRoundTillTheEnd } from '../poker/tableSpecific';
     
    214216    /**
    215217     * /---------------------- GET ----------------------/
     218     * Activates an user account if not activated.
     219     * @action activate_account
     220     * @param emailActivationId
     221     */
     222    if (req.query?.action === 'activate_account' && req.query?.emailActivationId) {
     223      pool.query('SELECT * FROM users WHERE email_activation_id = $1', [req.query.emailActivationId], (error, results) => {
     224        if (error) throw error;
     225
     226        if (results.rows.length > 0) {
     227          pool.query('UPDATE users SET activated = $1 WHERE email_activation_id = $2', [true, req.query.emailActivationId], (error, results) => {
     228            if (error) throw error;
     229
     230            res.json({
     231              success: true,
     232            })
     233          });
     234        }
     235        else {
     236          res.json({
     237            success: false,
     238          })
     239        }
     240      });
     241    }
     242
     243    /**
     244     * /---------------------- GET ----------------------/
    216245     * Checks if the player is logged in, and returns his session if so.
    217246     * @action check_if_logged_in
     
    226255          success: true,
    227256          displayName: session.displayName,
     257          username: session.username,
    228258          session_id: session.id,
    229259          credits: session.credits,
     
    254284
    255285        sessions.splice(sessions.indexOf(session), 1);
    256 
    257         axios.get(`${process.env.HOME_URL}/api/blackjack/?action=remove_room&session_id=${session_id}`);
    258 
    259286        update_sessions_to_database();
     287
     288        // remove player from games:
     289        if (rooms[session_id] !== undefined) {
     290          delete rooms[session_id];
     291          update_rooms_to_database();
     292        }
     293
     294        if (game.players?.map(e=>e.session_id).indexOf(session_id) !== -1) {
     295          game.players?.splice(game.players?.map(e=>e.session_id).indexOf(session_id), 1);
     296          update_game_to_database();
     297        }
     298
     299        tables.forEach(table => {
     300          table.players?.forEach(player => {
     301            if (player.id === session_id) {
     302              player.isGhost = true;
     303            }
     304          })
     305        })
     306        update_tables_to_database();
    260307      }
    261308
     
    480527    if (body?.action === 'register') {
    481528      // checks
     529      if (body?.email == "undefined" || body?.email == "null" || body?.email == "") {
     530        res.json({
     531          success: false,
     532          message: 'Email is required',
     533        });
     534        return ;
     535      }
     536      if (!body?.email?.includes('@') || body?.email?.indexOf('@', body?.email?.indexOf('@')+1) !== -1) {
     537        res.json({
     538          success: false,
     539          message: 'Not a valid email',
     540        });
     541        return ;
     542      }
    482543      if (body?.username == "undefined" || body?.username == "null" || body?.username == "") {
    483544        res.json({
     
    535596        }
    536597
     598        const emailActivationId = uuidv4();
     599
    537600        // store user in database
    538         pool.query('INSERT INTO users (username, password, salt) VALUES ($1, $2, $3)', [body.username, hashedPassword, salt], (error, usersResults) => {
     601        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) => {
    539602          if (error) throw error;
    540603
     
    544607            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) => {
    545608              if (error) throw error;
     609
     610              sendMailForActivation(body.displayName, body.email, emailActivationId);
    546611
    547612              res.json({
     
    604669          if (usersResults.rows.length > 0) {
    605670            const user = usersResults.rows[0];
     671
    606672            const salt = user.salt;
    607673            const hashedPassword = crypto.pbkdf2Sync(body.password, salt, 1000, 64, 'sha512').toString('hex');
    608674
    609675            if (hashedPassword === user.password) {
     676              if (user.activated === "false") {
     677                res.json({
     678                  success: false,
     679                  message: 'Account not activated. Check your email.',
     680                })
     681
     682                return ;
     683              }
     684
    610685              pool.query('SELECT * FROM players WHERE username = $1', [body.username], (error, playersResults) => {
    611686                if (playersResults.rows.length > 0) {
     
    658733}
    659734
     735// Mailing
     736const transporter = nodemailer.createTransport({
     737  service: 'gmail',
     738  auth: {
     739      user: process.env.GOOGLE_EMAIL,
     740      pass: process.env.GOOGLE_APP_PASSWORD,
     741  }
     742})
     743
     744function sendMailForActivation(displayName, userEmail, emailActivationId) {
     745  const message = {
     746      from: process.env.GOOGLE_EMAIL,
     747      to: userEmail,
     748      subject: "Caessino - Activate your account",
     749      html: `
     750          <h4>Hello, ${displayName}</h4>
     751          <p>Thank you for creating an account at Caessino. Just one more step and you can start enjoying the games!</p>
     752          <p>To activate your account please follow this link: <a target="_blank" href="${process.env.HOME_URL}/activate/${emailActivationId}">Activate account</a>
     753          <br/>
     754          <p>Cheers and happy playing,</p>
     755          <p>The Team ESS</p>
     756      `
     757  }
     758
     759  transporter.sendMail(message, (err, data) => {
     760      if (err) {
     761          console.log(err);
     762      }
     763  })
     764}
     765
     766let mailSentTo = {
     767  poker: [],
     768  roulette: [],
     769  blackjack: [],
     770}
     771function sendMailForGameCompletition(game, username, displayName) {
     772  return ;
     773
     774  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.';
     775  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.';
     776  const msgBlackjack = 'You can now continue playing your game.';
     777 
     778  pool.query('SELECT * FROM users WHERE username = $1', [username], (error, results) => {
     779    if (error) throw error;
     780
     781    if (results.rows.length > 0) {
     782      const userEmail = results.rows[0].email;
     783
     784      if ((game === 'poker' && mailSentTo.poker.indexOf(userEmail) === -1) ||
     785          (game === 'roulette' && mailSentTo.roulette.indexOf(userEmail) === -1) ||
     786          (game === 'blackjack' && mailSentTo.blackjack.indexOf(userEmail) === -1))
     787      {
     788        const message = {
     789          from: process.env.GOOGLE_EMAIL,
     790          to: userEmail,
     791          subject: "Caessino - Server is back online",
     792          html: `
     793            <h4>Hello, ${displayName}</h4>
     794            <p>We are writing to inform you that the server is back online.</p>
     795            <p>We know that you were in the middle of playing ${game}, and we apologize for the interrupt.</p>
     796            <p>${game === 'poker' ? msgPoker : game === 'roulette' ? msgRoulette : msgBlackjack}</p>
     797            <br/>
     798            <p>All the best,</p>
     799            <p>The Team ESS</p>
     800            `
     801        }
     802
     803        transporter.sendMail(message, (err, data) => {
     804          if (err) {
     805              console.log(err);
     806          }
     807        })
     808
     809        mailSentTo[game].push(userEmail)
     810      }
     811    }
     812  });
     813}
    660814
    661815/**
     
    708862    })
    709863
     864    tables.forEach(table => {
     865      if (table.ended) {
     866        table.players?.forEach(player => {
     867          if (!player.isGhost) {
     868            sendMailForGameCompletition('poker', player.username, player.displayName);
     869          }
     870        })
     871      }
     872    })
     873
    710874    cleanTables();
    711875
     
    731895
    732896    game = JSON.parse(results?.rows[0]?.data || []);
     897
     898    game.players?.forEach(player => {
     899      sendMailForGameCompletition('roulette', player.username, player.name);
     900    })
    733901
    734902    game.loaded = true;
     
    767935        rooms[room.id] = {...room, id: ''}
    768936      })
     937
     938      tmpRooms.forEach(room => {
     939        sendMailForGameCompletition('blackjack', room.username, room.displayName);
     940      })
    769941     
    770942      rooms["loaded"] = true;
  • pages/api/roulette/gameStates.js

    r55701f0 re007fcd  
    2626    game.status = '_1_ongoing_timer';
    2727
     28    let inactivePlayers = []
     29
    2830    game.players.forEach(player => {
    2931        player.whichBets = [];
     
    3739        player.status = '_1_no_placed_bet';
    3840        player.gotResults = false;
     41
     42        const d = Date.now();
     43
     44        if (d - player.lastActivity > 200000) {
     45            inactivePlayers.push(player);
     46        }
    3947    })
     48
     49    for (let i = 0; i < inactivePlayers.length; i++) {
     50        if (game.players.indexOf(inactivePlayers[i]) !== -1) {
     51            game.players.splice(game.players.indexOf(inactivePlayers[i]), 1);
     52        }
     53    }
    4054}
    4155
     
    6882}
    6983
    70 export function addPlayer(session_id, name) {
     84export function addPlayer(session_id, name, username) {
    7185    if (game.players.map(e=>e.session_id).indexOf(session_id) === -1) {
    7286        game.players.push({
     87            lastActivity: Date.now(),
    7388            session_id: session_id,
     89            username: username,
    7490            name: name,
    7591            whichBets: [],
  • pages/api/roulette/index.js

    r55701f0 re007fcd  
    7878                        },
    7979                        player.credits = postgreRes.data?.credits;
     80                        player.lastActivity = Date.now();
    8081                    }
    8182                });
     
    9798
    9899            let extraAction = "";
     100            let extraAction2 = "";
    99101            let magicNumber = -1;
    100102            let winningBets = [];
     
    107109
    108110                    player.gotResults = true;
     111                }
     112                if (game.timeToStart > game.COUNTDOWN_FROM + game.WAIT_BEFORE - 15) {
     113                    extraAction2 = "keep_alert";
    109114                }
    110115            }
     
    121126                },
    122127                extraAction: extraAction,
     128                extraAction2: extraAction2,
    123129                magicNumber: magicNumber,
    124130                winningBets: winningBets,
     
    138144            axios.get(`${process.env.HOME_URL}/api/postgre?action=check_if_logged_in&session_id=${session_id}`).then(postgreRes => {
    139145                if (postgreRes.data?.success) {
    140                     addPlayer(session_id, postgreRes.data?.displayName);
     146                    addPlayer(session_id, postgreRes.data?.displayName, postgreRes.data?.username);
    141147               
    142148                    res.json({
Note: See TracChangeset for help on using the changeset viewer.