-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
56 lines (49 loc) · 1.2 KB
/
index.js
File metadata and controls
56 lines (49 loc) · 1.2 KB
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
/**
* Dependencies
*/
const manner = require('manner')
const folder = require('manner-folder')
const jwt = require('jsonwebtoken')
const salute = require('salute')
const error = require('http-errors')
/**
* Create manner service when bearer token is
* verified.
*
* @param {String} path
* @param {String?} secret
* @api public
*/
module.exports = function (path, secret = process.env.JWT_SECRET) {
const service = typeof path === 'string'
? folder(path)
: manner(path)
return (req, res) => {
const payload = token(req)
if (payload) {
let obj
try {
obj = jwt.verify(payload, secret)
req.query = Object.assign(req.query || {}, obj)
return service(req, res)
} catch (e) {
// not verified
}
}
return salute(() => error(403, 'Not Authorized'))(req, res)
}
}
/**
* Extract token from authorization header.
*
* @param {httpIncomingMessage} req
* @return {String} (or undefined)
* @api private
*/
function token(req) {
const header = req.headers.authorization
if (header) {
const authorization = header.split(' ')
if (authorization[0] === 'Bearer' && authorization.length === 2) return authorization[1]
}
}