Advertisement
Guest User

Untitled

a guest
Dec 31st, 2018
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. .post('/api/login', function (req, res) {
  2.  
  3. /* API LOGIN */
  4.  
  5. let email = req.body.email;
  6. let pass = req.body.password;
  7.  
  8. if (typeof email !== 'string' || email.length === 0 || typeof pass !== 'string' || pass.length === 0) {
  9. return res.status(400).send({status_code: 400, error: 'Invalid request'});
  10. }
  11.  
  12. let db = mysql.createConnection({
  13. host: "localhost",
  14. user: "root",
  15. password: "YmU5YTViZmQwYWZj",
  16. database: "db"
  17. });
  18.  
  19. db.connect(function (err) {
  20. if (err) {
  21. return res.status(500);
  22. }
  23.  
  24. db.query('SELECT userid, password, verified FROM users WHERE email = ?', email, function (err, reply) {
  25. if (err) {
  26. return res.status(500);
  27. }
  28.  
  29. if (reply.length === 0) {
  30. return res.status(401).send({status_code: 401, error: 'Invalid credentials'});
  31. }
  32.  
  33. if (reply.length > 1) {
  34. return res.status(500);
  35. }
  36.  
  37. if (!bcrypt.compareSync(pass, reply[0].password)) {
  38. return res.status(401).send({status_code: 401, error: 'Invalid credentials'});
  39. }
  40.  
  41. if (!reply[0].verified) {
  42. return res.status(401).send({status_code: 401, error: 'Account not verified'})
  43. }
  44.  
  45. let sess_salt = bcrypt.genSaltSync();
  46. let sess_id = bcrypt.hashSync(bcrypt.hashSync(Date.now()) + bcrypt.hashSync(reply[0].userid) + sess_salt, sess_salt);
  47.  
  48. res.cookie('SESS_ID', sess_id);
  49.  
  50. db.query('DELETE FROM sessions WHERE expirationts < ?', Date.now() - 1000 * 60 * 60 * 24, function (err, reply2) {
  51. if (err) {
  52. return res.status(500);
  53. }
  54.  
  55. db.query('INSERT INTO sessions SET ?', {
  56. cookiesessid: sess_id,
  57. userid: reply[0].userid,
  58. expirationts: Date.now() + 1000 * 60 * 24
  59. }, function (err, reply3) {
  60. if (err) {
  61. return res.status(500);
  62. }
  63.  
  64. res.status(200).send({status_code: 200, error: 'Successful'})
  65. })
  66. })
  67. });
  68. });
  69. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement