auth.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. bcrypt.compare(password, user.password, function (err, result) {
  82. if (result) {
  83. res.json({ token: generateToken(user) });
  84. } else {
  85. res.status(401).json({ error: "Wrong password" });
  86. }
  87. });
  88. })
  89. .catch(err => {
  90. console.log(err);
  91. res.status(500).json({ error: err.message });
  92. });
  93. });
  94. /**
  95. * Handle a registration request.
  96. */
  97. router.post('/register', async function (req, res) {
  98. const email = req.body.email;
  99. const password = req.body.password;
  100. if (!password || !email) {
  101. return res.status(400).json({ message: 'parameters invalid' });
  102. }
  103. if (!isValidEmail(email)) {
  104. return res.status(400).json({ message: 'email is invalid' });
  105. }
  106. try {
  107. const existingUser = await User.findOne({ email: email });
  108. if (existingUser) {
  109. return res.status(403).json({ message: 'user already exists' });
  110. }
  111. // Hash the password
  112. bcrypt.hash(password, saltRounds, async function (err, hash) {
  113. if (err) {
  114. return res.status(500).json({ error: err.message });
  115. } else if (hash) {
  116. await User.collection.insertOne({ email: email, password: hash });
  117. const user = await User.findOne({ email: email });
  118. return res.json({ token: generateToken(user) });
  119. }
  120. });
  121. } catch (err) {
  122. console.error(err);
  123. return res.status(500).json({ error: 'Internal Server Error' });
  124. }
  125. });
  126. export { router, User };