wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
oauth2TokenParser - Parser oauth2 tokens from the authorization header
or BODY of the request
 
If parsing from the BODY there is adependency on the bodyParser plugin:
 
server.use(plugins.bodyParser());
server.use(plugins.oauth2TokenParser());
 
 
*/
'use strict';
 
var errors = require('restify-errors');
 
/*
 
  Parses the header for the authorization: bearer
 
*/
function parseHeader(req) {
    if (req.headers && req.headers.authorization) {
        var credentialsIndex = 1;
        var parts = req.headers.authorization.split(' ');
        var partsExpectedLength = 2;
        var schemeIndex = 0;
 
        if (parts.length === partsExpectedLength) {
            var credentials = parts[credentialsIndex];
            var scheme = parts[schemeIndex];
 
            if (/^Bearer$/i.test(scheme)) {
                return credentials;
            }
        }
    }
 
    return null;
}
 
/**
 * Returns a plugin that will parse the client's request for an OAUTH2
   access token
 *
 * Subsequent handlers will see `req.oauth2`, which looks like:
 *
 * ```js
 * {
 *   oauth2: {
        accessToken: 'mF_9.B5f-4.1JqM&p=q'
    }
 * }
 * ```
 *
 * @public
 * @function oauth2TokenParser
 * @throws   {InvalidArgumentError}
 * @param    {Object} options - an options object
 * @returns  {Function} Handler
 */
function oauth2TokenParser(options) {
    function parseOauth2Token(req, res, next) {
        req.oauth2 = { accessToken: null };
 
        var tokenFromHeader = parseHeader(req);
 
        if (tokenFromHeader) {
            req.oauth2.accessToken = tokenFromHeader;
        }
 
        var tokenFromBody = null;
 
        if (typeof req.body === 'object') {
            tokenFromBody = req.body.access_token;
        }
 
        // more than one method to transmit the token in each request
        // is not allowed - return 400
        if (tokenFromBody && tokenFromHeader) {
            // eslint-disable-next-line new-cap
            return next(
                new errors.makeErrFromCode(400, 'multiple tokens disallowed')
            );
        }
 
        if (
            tokenFromBody &&
            req.contentType().toLowerCase() ===
                'application/x-www-form-urlencoded'
        ) {
            req.oauth2.accessToken = tokenFromBody;
        }
 
        return next();
    }
 
    return parseOauth2Token;
}
 
module.exports = oauth2TokenParser;