sync/lib/web/csrf.js

47 lines
1.0 KiB
JavaScript
Raw Normal View History

2015-02-23 00:15:22 +00:00
/*
* Adapted from https://github.com/expressjs/csurf
*/
var csrf = require("csrf");
var createError = require("http-errors");
var tokens = csrf();
2015-02-24 16:48:51 +00:00
exports.init = function csrfInit (domain) {
return function (req, res, next) {
var secret = req.signedCookies._csrf;
if (!secret) {
secret = tokens.secretSync();
res.cookie("_csrf", secret, {
domain: domain,
signed: true,
httpOnly: true
});
}
2015-02-23 00:15:22 +00:00
2015-02-24 16:48:51 +00:00
var token;
2015-02-23 00:15:22 +00:00
2015-02-24 16:48:51 +00:00
req.csrfToken = function csrfToken() {
if (token) {
return token;
}
token = tokens.create(secret);
2015-02-23 00:15:22 +00:00
return token;
2015-02-24 16:48:51 +00:00
};
2015-02-23 00:15:22 +00:00
2015-02-24 16:48:51 +00:00
next();
2015-02-23 00:15:22 +00:00
};
};
exports.verify = function csrfVerify(req) {
var secret = req.signedCookies._csrf;
var token = req.body._csrf || req.query._csrf;
if (!tokens.verify(secret, token)) {
throw createError(403, 'invalid csrf token', {
code: 'EBADCSRFTOKEN'
});
}
};