Changeset e007fcd for pages/api/postgre


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/api/postgre
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • 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;
Note: See TracChangeset for help on using the changeset viewer.