Skip to content

Instantly share code, notes, and snippets.

@techomoro
Last active Dec 5, 2021
Embed
What would you like to do?
const express = require("express");
const router = express.Router();
let models = require("../../model");
let _ = require("lodash");
const jwt = require("jsonwebtoken");
const config = require("../../config");
router.post("/", async (req, res) => {
try {
let user = await models.User.findOne({
email: req.body.email,
});
if (user) {
let isUserAuthenticated = user.validatePassword(
req.body.password,
user.password
);
if (isUserAuthenticated) {
user.token = jwt.sign(
{
id: user._id,
},
config.secret,
{
expiresIn: "10d",
}
);
res.status(200).json({
status: 200,
data: _.pick(user, models.User.returnable),
});
} else {
res.status(400).json({
status: 400,
message: "Password is incorrect",
});
}
} else {
res.status(400).json({
status: 400,
message: "No account exist",
});
}
} catch (err) {
console.log(err);
res.status(400).json({
message: "Some error occured",
err,
});
}
});
module.exports = router;
@Alenygam
Copy link

Alenygam commented Jul 29, 2021

rewrite that does the same thing but it is much shorter, easier to read and understand

const express = require("express");
const router = express.Router();
let models = require("../../model");
let _ = require("lodash");
const jwt = require("jsonwebtoken");
const config = require("../../config");

router.post("/", async (req, res) => {
  try {
    let user = await models.User.findOne({
      email: req.body.email
    })

    if (!user) return res.status(404).json({message: "Couldn't find this user."});

    const isUserAuthed = user.validatePassword(req.body.password, user.password);
    if (!isUserAuthed) return res.status(400).json({message: 'Password is incorrect.'});

    user.token = jwt.sign({_id: user._id}, config.secret, {expiresIn: "10d"});

    res.status(200).json(_.pick(user, models.User.returnable));
  } catch (err) {
    console.log(err);
    res.status(500).json({
      message: "An error occured"
    })
  }
})

module.exports = router;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment