node-mongo-demo

node.js and mongodb demo

git clone https://9o.is/git/node-mongo-demo.git

user-signup.js

(1086B)


      1 import bcrypt from "bcryptjs";
      2 import jwt from "jsonwebtoken";
      3 import User from "../models/user.js";
      4 
      5 const signup = async (req, res) => {
      6   const { email, password, confirmPassword, firstName, lastName } = req.body;
      7 
      8   try {
      9     const existingUser = await User.findOne({ email });
     10     if (existingUser) {
     11       return res.status(400).json({ message: "User Already Exist" });
     12     }
     13 
     14     if (password !== confirmPassword) {
     15       return res.status(400).json({ message: "Password Does Not Match" });
     16     }
     17 
     18     const hashedPassword = await bcrypt.hash(password, 12);
     19     const result = await User.create({
     20       email,
     21       password: hashedPassword,
     22       name: `${firstName} ${lastName}`,
     23     });
     24     const token = jwt.sign(
     25       {
     26         _id: result._id,
     27         name: result.name,
     28         email: result.email,
     29         password: result.hashedPassword,
     30       },
     31       "test",
     32       { expiresIn: "1h" }
     33     );
     34 
     35     res.status(200).json({ token });
     36   } catch (error) {
     37     res.status(500).json({ message: "Something went wrong" });
     38     console.log(error);
     39   }
     40 };
     41 
     42 export default signup;