user.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import bcrypt from "bcryptjs";
  2. import jwt from "jsonwebtoken";
  3. import Profile from "../models/profile.js";
  4. import User from "../models/user.js";
  5. export const signin = async (req, res) => {
  6. const { email, password } = req.body;
  7. try {
  8. const existingUser = await User.findOne({ email });
  9. if (!existingUser)
  10. return res
  11. .status(404)
  12. .json({ message: "User with this email doesnt exist" });
  13. const isPasswordCorrect = await bcrypt.compare(
  14. password,
  15. existingUser.password
  16. );
  17. if (!isPasswordCorrect)
  18. return res.status(400).json({ message: "Invalid credentials" });
  19. const token = jwt.sign(
  20. { email: existingUser.email, id: existingUser._id },
  21. "sometext"
  22. );
  23. res.status(200).json({ result: existingUser, token });
  24. } catch (error) {
  25. res.status(500).json({ message: "something went wrong" });
  26. }
  27. };
  28. export const signup = async (req, res) => {
  29. const { email, password, confirmPassword, firstName, lastName } = req.body;
  30. const profileFields = {};
  31. try {
  32. const existingUser = await User.findOne({ email });
  33. if (existingUser)
  34. return res
  35. .status(404)
  36. .json({ message: "User with this email already exist." });
  37. if (password != confirmPassword) {
  38. return res.status(404).json({ message: "Passwords has not confirmed" });
  39. }
  40. const hashedPassword = await bcrypt.hash(password, 12);
  41. const result = await User.create({
  42. email,
  43. password: hashedPassword,
  44. name: `${firstName} ${lastName}`,
  45. });
  46. const token = jwt.sign(
  47. { email: result.email, id: result._id },
  48. "sometext",
  49. {
  50. expiresIn: "1h",
  51. }
  52. );
  53. profileFields.user = result._id;
  54. const profile = await Profile.create(profileFields);
  55. await profile.save();
  56. res.status(201).json({ result, token });
  57. } catch (error) {
  58. res.status(500).json({ message: "something went wrong" });
  59. }
  60. };