3 * Copyright(c) 2013 TJ Holowaychuk
4 * Copyright(c) 2014 Jonathan Ong
5 * Copyright(c) 2015-2016 Douglas Christopher Wilson
12 * Module dependencies.
16 var Buffer = require('safe-buffer').Buffer
24 module.exports.parse = parse
27 * RegExp for basic auth credentials
29 * credentials = auth-scheme 1*SP token68
30 * auth-scheme = "Basic" ; case insensitive
31 * token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
35 var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/
38 * RegExp for basic auth user/pass
40 * user-pass = userid ":" password
41 * userid = *<TEXT excluding ":">
46 var USER_PASS_REGEXP = /^([^:]*):(.*)$/
49 * Parse the Authorization header field of a request.
52 * @return {object} with .name and .pass
58 throw new TypeError('argument req is required')
61 if (typeof req !== 'object') {
62 throw new TypeError('argument req is required to be an object')
66 var header = getAuthorization(req)
73 * Decode base64 string.
77 function decodeBase64 (str) {
78 return Buffer.from(str, 'base64').toString()
82 * Get the Authorization header from request object.
86 function getAuthorization (req) {
87 if (!req.headers || typeof req.headers !== 'object') {
88 throw new TypeError('argument req is required to have headers property')
91 return req.headers.authorization
95 * Parse basic auth to object.
97 * @param {string} string
102 function parse (string) {
103 if (typeof string !== 'string') {
108 var match = CREDENTIALS_REGEXP.exec(string)
115 var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]))
121 // return credentials object
122 return new Credentials(userPass[1], userPass[2])
126 * Object to represent user credentials.
130 function Credentials (name, pass) {