Skip to content

Instantly share code, notes, and snippets.

@AshutoshSajan
Created January 24, 2020 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AshutoshSajan/7e3b6b86cfd92de7d7b176724cf0187e to your computer and use it in GitHub Desktop.
Save AshutoshSajan/7e3b6b86cfd92de7d7b176724cf0187e to your computer and use it in GitHub Desktop.
const User = require("../models/User");
const bcrypt = require('bcrypt');
const jwtAuth = require('../utils/jwtAuth');
function loginUser (req, res){
User.findOne({
email: req.body.email
})
.exec((err, user) => {
if (err) {
res.status(500).json({
success: false,
message: "server error",
error: err
});
} else if (!user) {
res.status(400).json({
success: false,
message: "user does not exist."
});
} else if (user) {
const plainPassword = req.body.password;
bcrypt.compare(plainPassword, user.password, (err, match) => {
if (err) {
res.status(400).json({
success: false,
message: "bcrypt password compare error",
error: err
});
} else if (match) {
const token = jwtAuth.createToken(user._id, process.env.JWT_SECRET);
user.password = undefined;
res.status(200).json({
success: true,
message: "user login successfull :)",
user,
token
});
} else if (!match) {
res.status(400).json({
success: false,
message: "invalid password",
});
}
});
}
})
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment