user.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import User from "../models/User.js";
  2. import {HttpError} from "../HttpError.js";
  3. import validate from "../validation/user.js";
  4. import bcrypt from "bcrypt";
  5. import crypto from "crypto";
  6. const createRoute = async (req, res, next)=>{
  7. try{
  8. validate(req.body);
  9. const user = await createUser(req.body);
  10. await user.save();
  11. res.json(responseUser(user));
  12. }catch(e){next(e)}
  13. }
  14. /*
  15. Create a new User object
  16. @param {Object} - Request body with user data
  17. @return {User} - User object
  18. */
  19. const createUser = async (data)=>{
  20. const email = data.email.toLowerCase();
  21. const user = await User.findOne({email: email});
  22. if(user !== null) throw new HttpError(400, "User with this email already exists");
  23. return new User({
  24. name: data.name,
  25. email: email,
  26. password: await hashPass(data.pass),
  27. workouts: [],
  28. uuid: createUuid()
  29. });
  30. }
  31. /*
  32. Hash a password
  33. @param {String} - Password to hash
  34. @return {String} - Hashed password
  35. */
  36. const hashPass = async (password)=>{
  37. return await bcrypt.hash(password, 10);
  38. }
  39. /*
  40. Create user object for sending to frontend
  41. @param {User} - User object
  42. @return {User} - Modified User object
  43. */
  44. const responseUser = (user)=>{
  45. return {
  46. id: user._id,
  47. name: user.name,
  48. email: user.email,
  49. workouts: user.workouts
  50. };
  51. }
  52. /*
  53. Create a new UUID token
  54. @return {String} - UUID token
  55. */
  56. const createUuid = ()=>{
  57. return crypto.randomUUID();
  58. }
  59. export {
  60. createRoute
  61. }