[Vuejs]-How to return current user information from MongoDB in a MEVN stack app

1πŸ‘

βœ…

I assume your user model has username and password fields, and your password is encrypted in db.

For finding user with username, if user found comparing the user.password with the encrypted password in the request body.
If user not found, or passwords don’t match, I send 400-Bad Request.

const bcrypt = require("bcryptjs");

router.post("/", async (req, res) => {
  const { username, password } = req.body;

  if (!(username && password))
    return res.status(400).json({ error: "username and password are required" });

  try {
    let user = await User.findOne({ username });
    if (!user) return res.status(400).json({ error: "invalid login" });

    const validPassword = await bcrypt.compare(password, user.password);
    if (!validPassword) return res.status(400).json({ error: "invalid login" });

    user.password = undefined;

    res.json(user);
  } catch (err) {
    console.log(err);
    return next(err);
  }
});

To hash the password before saving the user, can you add this code to the user model?

UserSchema.pre('save', async function (next) {
    this.password = await bcrypt.hash(this.password, 12);
    next();
});

Register route:

router.post("/register", async (req, res) => {
  const { username, password } = req.body;

  if (!username || !password)
    return res.json({ success: false, msg: "Please pass username and password." });

  try {
    let user = await User.findOne({ username });

    if (user) return res.json({ success: false, msg: "Username already exists." });

    user = new User({ username, password });

    await user.save();

    res.json({ success: true, msg: "Successful created new user." });
  } catch (err) {
    console.log(err);
    res.json({ success: false, msg: "Something went bad" });
  }
});
πŸ‘€SuleymanSah

Leave a comment