Total Complexity | 5 |
Complexity/F | 1.67 |
Lines of Code | 41 |
Function Count | 3 |
Duplicated Lines | 0 |
Ratio | 0 % |
Coverage | 100% |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | 1 | var jwt = require('jsonwebtoken'); |
|
2 | |||
3 | /** |
||
4 | * Middleware for verifying JWT tokens |
||
5 | * |
||
6 | * Using the jsonwebtoken-library, available options can be found here: |
||
7 | * https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback |
||
8 | * |
||
9 | * @param {*} options - Options |
||
10 | * |
||
11 | * @return error or next() |
||
12 | */ |
||
13 | 1 | module.exports = function(secret, options = {}) { |
|
14 | 1 | return (req, res, next) => { |
|
15 | 4 | const token = req.body.token || req.query.token || req.headers['x-access-token']; |
|
16 | |||
17 | 4 | if (!token) { |
|
18 | 1 | return res.status(403).send({ |
|
19 | success: false, |
||
20 | status: 403, |
||
21 | title: 'NoTokenProvided', |
||
22 | description: "Forbidden, missing token." |
||
23 | }); |
||
24 | } |
||
25 | |||
26 | 3 | jwt.verify(token, secret, options, (err, decoded) => { |
|
27 | 3 | if (err) { |
|
28 | 2 | return res.status(403).send({ |
|
29 | success: false, |
||
30 | status: 403, |
||
31 | title: err.name, |
||
32 | description: `Forbidden. ${err.message}` |
||
33 | |||
34 | }); |
||
35 | } |
||
36 | |||
37 | 1 | req.decoded = decoded; |
|
38 | 1 | next(); |
|
|
|||
39 | }); |
||
40 | }; |
||
41 | }; |
||
42 |