3 * Copyright(c) 2013 TJ Holowaychuk
4 * Copyright(c) 2014 Jonathan Ong
5 * Copyright(c) 2015 Douglas Christopher Wilson
19 * RegExp for basic auth credentials
21 * credentials = auth-scheme 1*SP token68
22 * auth-scheme = "Basic" ; case insensitive
23 * token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
27 var credentialsRegExp = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9\-\._~\+\/]+=*) *$/
30 * RegExp for basic auth user/pass
32 * user-pass = userid ":" password
33 * userid = *<TEXT excluding ":">
38 var userPassRegExp = /^([^:]*):(.*)$/
41 * Parse the Authorization header field of a request.
44 * @return {object} with .name and .pass
50 throw new TypeError('argument req is required')
53 if (typeof req !== 'object') {
54 throw new TypeError('argument req is required to be an object')
58 var header = getAuthorization(req.req || req)
61 var match = credentialsRegExp.exec(header || '')
68 var userPass = userPassRegExp.exec(decodeBase64(match[1]))
74 // return credentials object
75 return new Credentials(userPass[1], userPass[2])
79 * Decode base64 string.
83 function decodeBase64(str) {
84 return new Buffer(str, 'base64').toString()
88 * Get the Authorization header from request object.
92 function getAuthorization(req) {
93 if (!req.headers || typeof req.headers !== 'object') {
94 throw new TypeError('argument req is required to have headers property')
97 return req.headers.authorization
101 * Object to represent user credentials.
105 function Credentials(name, pass) {