auth.js 2.8 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. bcrypt.compare(password, user.password, function (err, result) {
  40. if (result) {
  41. res.json({ token: generateToken(user) });
  42. } else {
  43. res.status(401).json({ error: "Wrong password" });
  44. }
  45. });
  46. })
  47. .catch(err => {
  48. console.log(err);
  49. res.status(500).json({ error: err.message }); // Ensure you send the error message
  50. });
  51. });
  52. router.post('/register', async function (req, res) {
  53. const email = req.body.email;
  54. const password = req.body.password;
  55. if (!password || !email) {
  56. return res.status(400).json({ message: 'parameters invalid' });
  57. }
  58. if (!isValidEmail(email)) {
  59. return res.status(400).json({ message: 'email is invalid' });
  60. }
  61. try {
  62. // Check if user already exists
  63. const existingUser = await User.findOne({ email: email });
  64. if (existingUser) {
  65. return res.status(403).json({ message: 'user already exists' });
  66. }
  67. // Hash the password
  68. bcrypt.hash(password, saltRounds, async function (err, hash) {
  69. if (err) {
  70. return res.status(500).json({ error: err.message });
  71. } else if (hash) {
  72. // Insert user into database and generate token
  73. const user = await User.collection.insertOne({ email: email, password: hash });
  74. return res.json({ token: generateToken(user) });
  75. }
  76. });
  77. } catch (err) {
  78. // Handle errors
  79. console.error(err);
  80. return res.status(500).json({ error: 'Internal Server Error' });
  81. }
  82. });
  83. export { router, User };