Advertisement
vandasche

Untitled

Apr 16th, 2020
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. const jwt = require('jsonwebtoken');
  2. const bcrypt = require('bcrypt');
  3. const { User } = require('../models');
  4.  
  5. //===LOGIC LOGIN ===
  6. exports.login = async (req, res) => {
  7. try {
  8. //we request email and body from req.body
  9. const { email, password } = req.body;
  10. //then we search the user using sequelize command findOne
  11. const user = await User.findOne({
  12. //search based on email and put it in user variable or destructuring
  13. where: {
  14. email,
  15. },
  16. });
  17. //if the email we search is not available print invalid login
  18. if (!user) {
  19. res.status(401).send({ message: 'Invalid Login' });
  20. //if the user available then using bcrypt library for comparing the password that user input
  21. } else {
  22. bcrypt.compare(password, user.password, (err, result) => {
  23. if (result) {
  24. //if the request email and password match we allow user to sign in
  25. jwt.sign({ id: user.id }, 'this-is-my-secret-key', (err, token) => {
  26. //we declare variable data that contains email and token
  27. const data = {
  28. email,
  29. token,
  30. };
  31. //we send the data to user
  32. res.status(200).send({ data });
  33. });
  34. //if the result not matching we prompt message invalid
  35. } else {
  36. res.status(401).send({ message: 'Invalid Login' });
  37. }
  38. });
  39. }
  40. } catch (error) {
  41. res.status(500).send({ message: 'server internal error' });
  42. console.log(error);
  43. }
  44. };
  45.  
  46. exports.register = async (req, res) => {
  47. try {
  48. const saltRounds = 10;
  49. const { email, password } = req.body;
  50. const user = await User.findOne({
  51. where: {
  52. email,
  53. },
  54. });
  55. if (!user) {
  56. bcrypt.hash(password, saltRounds, async (err, hash) => {
  57. const value = {
  58. ...req.body,
  59. password: hash,
  60. };
  61. const newUser = await User.create(value);
  62. jwt.sign({ id: newUser.id }, 'this-is-my-secret-key', (err, token) => {
  63. const data = {
  64. email,
  65. token,
  66. };
  67. res.status(200).send(data);
  68. });
  69. });
  70. } else {
  71. res.status(400).send({ message: 'Email already registered' });
  72. }
  73. } catch (error) {
  74. res.send(500).send({ message: 'server internal error' });
  75. console.log(error);
  76. }
  77. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement