Skip to content

Instantly share code, notes, and snippets.

@yactouat
Created September 2, 2022 11:14
Show Gist options
  • Save yactouat/b8b93304f6de7239c4f6798aa7350078 to your computer and use it in GitHub Desktop.
Save yactouat/b8b93304f6de7239c4f6798aa7350078 to your computer and use it in GitHub Desktop.
log a user in an Express controller (mongoose)
const jwt = require('jsonwebtoken');
// you'll also need some mongoose User model
exports.login = async (req, res, next) => {
let usr;
try {
usr = await User.findOne({ email: req.body.email });
} catch (error) {
res.status(500).json({
data: null,
msg: 'sorry we experienced an issue, please try again later',
success: false
});
return;
}
if (!usr) {
res.status(401).json({
data: null,
msg: 'no user found',
success: false
});
return;
}
let isPwdValid;
try {
isPwdValid = await bcrypt.compare(req.body.password, usr.password);
} catch (error) {
res.status(500).json({
data: null,
msg: 'sorry we experienced an issue, please try again later',
success: false
});
return;
}
if (!isPwdValid) {
res.status(401).json({
data: null,
msg: 'invalid credentials',
success: false
});
return;
}
res.status(200).json({
data: {
isAdmin: usr.isAdmin,
token: jwt.sign(
{ userId: usr._id },
process.env.RANDOM_SECRET_TOKEN,
{ expiresIn: '24h' }
),
userId: usr._id
},
msg: 'login successful',
success: true
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment