-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (50 loc) · 1.54 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
/*!
* trek-csrf
* Copyright(c) 2017 Fangdun Cai <[email protected]> (https://fundon.me)
* MIT Licensed
*/
'use strict'
module.exports = csrfWithConfig
const Tokens = require('csrf')
const defaults = {
key: 'csrf',
tokenLookup: 'header:X-CSRF-Token',
ignoreMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'],
// https://github.com/pillarjs/csrf#new-tokensoptions
tokenOptions: undefined
}
function csrfWithConfig (options = {}) {
options = Object.assign({}, defaults, options)
const { key, tokenLookup, ignoreMethods, tokenOptions } = options
const tokens = new Tokens(tokenOptions)
const [via, field] = tokenLookup.split(':')
let extractor = csrfTokenFromHeader
switch (via) {
case 'form':
extractor = csrfTokenFromForm
break
case 'query':
extractor = csrfTokenFromQuery
break
// No default
}
return csrf
async function csrf ({ req, res, sessions, store }, next) {
if (!sessions.secret) sessions.secret = await tokens.secret()
if (!store.has(key)) store.set(key, tokens.create(sessions.secret))
if (ignoreMethods.includes(req.method)) return next()
const token = extractor(req, field)
if (!token) return res.send(403, 'Invalid CSRF token')
if (!tokens.verify(sessions.secret, token)) return res.send(403, 'Invalid CSRF token')
return next()
}
}
function csrfTokenFromHeader (req, header) {
return req.get(header)
}
function csrfTokenFromForm (req, name) {
return req.body && req.body[name]
}
function csrfTokenFromQuery (req, name) {
return req.query[name]
}