second
[josuexyz/.git] / node_modules / basic-auth / index.js
1 /*!
2  * basic-auth
3  * Copyright(c) 2013 TJ Holowaychuk
4  * Copyright(c) 2014 Jonathan Ong
5  * Copyright(c) 2015-2016 Douglas Christopher Wilson
6  * MIT Licensed
7  */
8
9 'use strict'
10
11 /**
12  * Module dependencies.
13  * @private
14  */
15
16 var Buffer = require('safe-buffer').Buffer
17
18 /**
19  * Module exports.
20  * @public
21  */
22
23 module.exports = auth
24 module.exports.parse = parse
25
26 /**
27  * RegExp for basic auth credentials
28  *
29  * credentials = auth-scheme 1*SP token68
30  * auth-scheme = "Basic" ; case insensitive
31  * token68     = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
32  * @private
33  */
34
35 var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/
36
37 /**
38  * RegExp for basic auth user/pass
39  *
40  * user-pass   = userid ":" password
41  * userid      = *<TEXT excluding ":">
42  * password    = *TEXT
43  * @private
44  */
45
46 var USER_PASS_REGEXP = /^([^:]*):(.*)$/
47
48 /**
49  * Parse the Authorization header field of a request.
50  *
51  * @param {object} req
52  * @return {object} with .name and .pass
53  * @public
54  */
55
56 function auth (req) {
57   if (!req) {
58     throw new TypeError('argument req is required')
59   }
60
61   if (typeof req !== 'object') {
62     throw new TypeError('argument req is required to be an object')
63   }
64
65   // get header
66   var header = getAuthorization(req)
67
68   // parse header
69   return parse(header)
70 }
71
72 /**
73  * Decode base64 string.
74  * @private
75  */
76
77 function decodeBase64 (str) {
78   return Buffer.from(str, 'base64').toString()
79 }
80
81 /**
82  * Get the Authorization header from request object.
83  * @private
84  */
85
86 function getAuthorization (req) {
87   if (!req.headers || typeof req.headers !== 'object') {
88     throw new TypeError('argument req is required to have headers property')
89   }
90
91   return req.headers.authorization
92 }
93
94 /**
95  * Parse basic auth to object.
96  *
97  * @param {string} string
98  * @return {object}
99  * @public
100  */
101
102 function parse (string) {
103   if (typeof string !== 'string') {
104     return undefined
105   }
106
107   // parse header
108   var match = CREDENTIALS_REGEXP.exec(string)
109
110   if (!match) {
111     return undefined
112   }
113
114   // decode user pass
115   var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]))
116
117   if (!userPass) {
118     return undefined
119   }
120
121   // return credentials object
122   return new Credentials(userPass[1], userPass[2])
123 }
124
125 /**
126  * Object to represent user credentials.
127  * @private
128  */
129
130 function Credentials (name, pass) {
131   this.name = name
132   this.pass = pass
133 }