The one and only Two Factor Authentication Handler for Express.
Tested with Authy
, Google Authenticator
and Duo
.
npm i gatekeeper-express
npm i lodash express
- express-session
- passport (ie.
req.user
) - some rendering engine (vash, ejs, etc)
'use strict';
const { GateKeeper } = require('gatekeeper-express');
const gateKeeper = new GateKeeper({
appName: 'App',
length: 64
});
app.use(
gateKeeper.express({
routePathPrefix: '/tfa',
userIdPath: 'email',
onSerialize: async (req, tfa) => {
req.user.tfa = tfa;
await req.user.save();
},
onDeserialize: async req => {
return req.user.tfa;
}
})
);
GateKeeper uses res.render('two-fa')
to render the page with qr image.
This is an example in Vash. Please adapt it to your app.
<div class="text-center">
<h4 class="h4 text-gray-900 mb-3">Two Factor Authentication</h4>
</div>
<form autocomplete="off" action="@model.verifyUrl" method="POST" class="user">
<input autocomplete="off" name="hidden" type="text" style="display:none;">
@if (model.qrImage) {
<div class="text-center mb-2">
<img src="@model.qrImage">
</div>
}
<div class="form-group">
<input
type="text"
class="form-control form-control-user"
id="token-input"
name="token"
placeholder="Enter verification token...">
</div>
<button class="btn btn-primary btn-user btn-block" type="submit">Verify</button>
</form>
<script>$('#token-input').focus();</script>
You can also use Ajax.
If you request /tfa
with Ajax it will send back in JSON: { qrImage: string; verifyUrl: string; }
Do a POST
request to verifyUrl
and GateKeeper will send back a JSON
object with a redirect url to use: { redirect: string; }
if needed.
To reset a user's 2-fa, simply delete user.tfa
.
Made with ❤ at Income Store in Lancaster, PA.