|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
'use strict' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var Buffer = require('safe-buffer').Buffer |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
module.exports = auth |
|
|
module.exports.parse = parse |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var USER_PASS_REGEXP = /^([^:]*):(.*)$/ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function auth (req) { |
|
|
if (!req) { |
|
|
throw new TypeError('argument req is required') |
|
|
} |
|
|
|
|
|
if (typeof req !== 'object') { |
|
|
throw new TypeError('argument req is required to be an object') |
|
|
} |
|
|
|
|
|
|
|
|
var header = getAuthorization(req) |
|
|
|
|
|
|
|
|
return parse(header) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function decodeBase64 (str) { |
|
|
return Buffer.from(str, 'base64').toString() |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function getAuthorization (req) { |
|
|
if (!req.headers || typeof req.headers !== 'object') { |
|
|
throw new TypeError('argument req is required to have headers property') |
|
|
} |
|
|
|
|
|
return req.headers.authorization |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function parse (string) { |
|
|
if (typeof string !== 'string') { |
|
|
return undefined |
|
|
} |
|
|
|
|
|
|
|
|
var match = CREDENTIALS_REGEXP.exec(string) |
|
|
|
|
|
if (!match) { |
|
|
return undefined |
|
|
} |
|
|
|
|
|
|
|
|
var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1])) |
|
|
|
|
|
if (!userPass) { |
|
|
return undefined |
|
|
} |
|
|
|
|
|
|
|
|
return new Credentials(userPass[1], userPass[2]) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function Credentials (name, pass) { |
|
|
this.name = name |
|
|
this.pass = pass |
|
|
} |
|
|
|