-
Notifications
You must be signed in to change notification settings - Fork 0
/
csrf.js
61 lines (51 loc) · 2.03 KB
/
csrf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const Cookies = require('cookies');
const {
defCheckRoutes,
actionResponseHeaderContentTypeTextPlainSilent,
} = require('./common');
function getCSRF_token (request, response) {
var cookies = new Cookies(request, response);
var CSRF_token = cookies.get('CSRF_token');
return CSRF_token;
}
module.exports = {
getCSRF_token,
generateCSRFFormInput: function (request, response) {
return `<input type="hidden" name="CSRF_token" id="csrf-token" value="${getCSRF_token(request, response)}" />`;
},
defMiddlewareGenerateCsrf: function (wsgilite) {
if (!wsgilite) {throw new Error('wsgilite is not given')}
return function (request, response, meta) {
var CSRF_token = getCSRF_token(request, response);
if ((!CSRF_token) || (!wsgilite.tokens.verify(wsgilite.secret, CSRF_token))) {
var token = wsgilite.tokens.create(wsgilite.secret);
var cookies = new Cookies(request, response);
cookies.set('CSRF_token', token, {
maxAge: wsgilite.config.csrfMaxAge,
});
}
}
},
defFormCsrfCheckRoutes: function (rules, wsgilite) {
if (!wsgilite) {throw new Error('wsgilite is not given')}
return defCheckRoutes(rules, function (request, response, meta) {
var CSRF_token = getCSRF_token(request, response);
if (CSRF_token != meta.CSRF_token || (!wsgilite.tokens.verify(wsgilite.secret, CSRF_token))) {
actionResponseHeaderContentTypeTextPlainSilent(response);
response.statusCode = 403;
response.end('CSRF detected.');
}
});
},
defHeaderCsrfCheckRoutes: function (rules, wsgilite) {
if (!wsgilite) {throw new Error('wsgilite is not given')}
return defCheckRoutes(rules, function (request, response, meta) {
var CSRF_token = request.headers['x-csrf-token'];
if ((CSRF_token != meta.CSRF_token) || (!wsgilite.tokens.verify(wsgilite.secret, CSRF_token))) {
actionResponseHeaderContentTypeTextPlainSilent(response);
response.statusCode = 403;
response.end('CSRF detected.');
}
});
},
};