auth.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import express from 'express';
  2. import { mongoose } from 'mongoose';
  3. import bcrypt from "bcrypt";
  4. import jwt from "jsonwebtoken";
  5. import {SECRET_KEY} from "../passport.js";
  6. import {isValidEmail} from "../utils.js";
  7. /**
  8. * Create an Express router instance.
  9. *
  10. * @type {Express.Router}
  11. */
  12. const router = express.Router();
  13. /**
  14. * Set the salt rounds for password hashing (10).
  15. *
  16. * @type {number}
  17. */
  18. const saltRounds = 10;
  19. /**
  20. * Define a Mongoose schema for users.
  21. *
  22. * @typedef {Object} UserSchema
  23. * @property {String} email - The user's email address.
  24. * @property {String} password - The user's password.
  25. */
  26. /**
  27. * Create a new Mongoose model from the user schema.
  28. *
  29. * @type {Model<UserSchema>}
  30. */
  31. const userSchema = new mongoose.Schema({
  32. /**
  33. * The user's email address.
  34. *
  35. * @type {String}
  36. * @required
  37. */
  38. email: {
  39. type: String,
  40. required: true
  41. },
  42. /**
  43. * The user's password.
  44. *
  45. * @type {String}
  46. * @required
  47. */
  48. password: {
  49. type: String,
  50. required: true
  51. }
  52. })
  53. const User = mongoose.model('User', userSchema, 'users');
  54. /**
  55. * Generate a JWT token for the given user.
  56. *
  57. * @param {Object} user - The user object.
  58. * @returns {String} The generated JWT token.
  59. */
  60. function generateToken(user) {
  61. const payload = { id: user._id };
  62. return jwt.sign(payload, SECRET_KEY, {expiresIn: '6h'});
  63. }
  64. /**
  65. * Handle a login request.
  66. */
  67. router.post('/login', function (req, res) {
  68. const email = req.body.email;
  69. const password = req.body.password;
  70. if (!password || !email) {
  71. return res.status(400).json({ message: 'parameters invalid' });
  72. }
  73. if (!isValidEmail(email)) {
  74. return res.status(400).json({ message: 'email is invalid' });
  75. }
  76. User.findOne({ email: email })
  77. .then(user => {
  78. if (!user) {
  79. return res.status(422).json({ message: 'user not found' });
  80. }
  81. console.log(user);
  82. bcrypt.compare(password, user.password, function (err, result) {
  83. if (result) {
  84. res.json({ token: generateToken(user) });
  85. } else {
  86. res.status(401).json({ error: "Wrong password" });
  87. }
  88. });
  89. })
  90. .catch(err => {
  91. console.log(err);
  92. res.status(500).json({ error: err.message });
  93. });
  94. });
  95. /**
  96. * Handle a registration request.
  97. */
  98. router.post('/register', async function (req, res) {
  99. const email = req.body.email;
  100. const password = req.body.password;
  101. if (!password || !email) {
  102. return res.status(400).json({ message: 'parameters invalid' });
  103. }
  104. if (!isValidEmail(email)) {
  105. return res.status(400).json({ message: 'email is invalid' });
  106. }
  107. try {
  108. const existingUser = await User.findOne({ email: email });
  109. if (existingUser) {
  110. return res.status(403).json({ message: 'user already exists' });
  111. }
  112. // Hash the password
  113. bcrypt.hash(password, saltRounds, async function (err, hash) {
  114. if (err) {
  115. return res.status(500).json({ error: err.message });
  116. } else if (hash) {
  117. await User.collection.insertOne({ email: email, password: hash });
  118. const user = await User.findOne({ email: email });
  119. return res.json({ token: generateToken(user) });
  120. }
  121. });
  122. } catch (err) {
  123. console.error(err);
  124. return res.status(500).json({ error: 'Internal Server Error' });
  125. }
  126. });
  127. export { router, User };