Skip to content

Instantly share code, notes, and snippets.

@alancasagrande
Created November 16, 2020 13:29
Show Gist options
  • Save alancasagrande/62b045d33777ea49a627b3235794a52e to your computer and use it in GitHub Desktop.
Save alancasagrande/62b045d33777ea49a627b3235794a52e to your computer and use it in GitHub Desktop.
app.post('/login', (req, res) => {
let authenticatedUser;
const { body } = req;
if (body.username) {
// try password login
const user = getUser(body.username);
if (user && user.password === body.password) {
authenticatedUser = user;
// create session
req.session.username = body.username;
}
} else if (req.user) {
// try session login
authenticatedUser = req.user;
// require one-time password
if (req.user.mfaEnabled && !req.session.mfaVerified) {
return res.status(403).end();
}
}
if (!authenticatedUser) {
// no user found, destroy session and return unauthorized
req.session = null;
return res.status(401).end();
}
// strip password and mfaSecret from response
const { password, mfaSecret, ...response } = authenticatedUser;
res.json(response);
});
app.post('/verify_otp', (req, res) => {
const user = req.user;
if (verifyTOTP(req.body.code, user.mfaSecret)) {
user.mfaEnabled = true;
req.session.mfaVerified = true;
setUser(user);
res.json(true);
} else {
res.json(false);
}
});
// Routes beyond this point must have MFA verified if enabled
app.use(function (req, res, next) {
const user = req.user;
if (user && user.mfaEnabled && !req.session.mfaVerified) {
return res.status(403).end();
}
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment