auth.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. const router = express.Router();
  8. const saltRounds = 10;
  9. const userSchema = new mongoose.Schema({
  10. email: {
  11. type: String,
  12. required: true
  13. },
  14. password: {
  15. type: String,
  16. required: true
  17. }
  18. })
  19. const User = mongoose.model('User', userSchema, 'users');
  20. // TODO split into different routes (/auth)
  21. function generateToken(user) {
  22. const payload = { id: user._id };
  23. return jwt.sign(payload, SECRET_KEY, {expiresIn: '6h'});
  24. }
  25. router.post('/login', function (req, res) {
  26. const email = req.body.email;
  27. const password = req.body.password;
  28. if (!password || !email) {
  29. return res.status(400).json({ message: 'parameters invalid' });
  30. }
  31. if (!isValidEmail(email)) {
  32. return res.status(400).json({ message: 'email is invalid' });
  33. }
  34. User.findOne({ email: email })
  35. .then(user => {
  36. if (!user) {
  37. return res.status(422).json({ message: 'user not found' });
  38. }
  39. console.log(user);
  40. bcrypt.compare(password, user.password, function (err, result) {
  41. if (result) {
  42. res.json({ token: generateToken(user) });
  43. } else {
  44. res.status(401).json({ error: "Wrong password" });
  45. }
  46. });
  47. })
  48. .catch(err => {
  49. console.log(err);
  50. res.status(500).json({ error: err.message }); // Ensure you send the error message
  51. });
  52. });
  53. router.post('/register', async function (req, res) {
  54. const email = req.body.email;
  55. const password = req.body.password;
  56. if (!password || !email) {
  57. return res.status(400).json({ message: 'parameters invalid' });
  58. }
  59. if (!isValidEmail(email)) {
  60. return res.status(400).json({ message: 'email is invalid' });
  61. }
  62. try {
  63. // Check if user already exists
  64. const existingUser = await User.findOne({ email: email });
  65. if (existingUser) {
  66. return res.status(403).json({ message: 'user already exists' });
  67. }
  68. // Hash the password
  69. bcrypt.hash(password, saltRounds, async function (err, hash) {
  70. if (err) {
  71. return res.status(500).json({ error: err.message });
  72. } else if (hash) {
  73. // Insert user into database and generate token
  74. await User.collection.insertOne({ email: email, password: hash });
  75. const user = await User.findOne({ email: email });
  76. return res.json({ token: generateToken(user) });
  77. }
  78. });
  79. } catch (err) {
  80. // Handle errors
  81. console.error(err);
  82. return res.status(500).json({ error: 'Internal Server Error' });
  83. }
  84. });
  85. export { router, User };