Skip to content

Commit 5299061

Browse files
committed
Improve error message when req missing headers property
1 parent 9a2a07d commit 5299061

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

HISTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ unreleased
22
==========
33

44
* Improve error message when `req` argument is not an object
5+
* Improve error message when `req` missing `headers` property
56

67
1.0.3 / 2015-07-01
78
==================

index.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ function auth(req) {
5555
}
5656

5757
// get header
58-
var header = (req.req || req).headers.authorization
58+
var header = getAuthorization(req.req || req)
5959

6060
// parse header
6161
var match = credentialsRegExp.exec(header || '')
@@ -84,6 +84,19 @@ function decodeBase64(str) {
8484
return new Buffer(str, 'base64').toString()
8585
}
8686

87+
/**
88+
* Get the Authorization header from request object.
89+
* @private
90+
*/
91+
92+
function getAuthorization(req) {
93+
if (!req.headers || typeof req.headers !== 'object') {
94+
throw new TypeError('argument req is required to have headers property')
95+
}
96+
97+
return req.headers.authorization
98+
}
99+
87100
/**
88101
* Object to represent user credentials.
89102
* @private

test/basic-auth.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ describe('auth(req)', function () {
3737
it('should reject a number', function () {
3838
assert.throws(auth.bind(null, 42), /argument req is required/)
3939
})
40+
41+
it('should reject an object without headers', function () {
42+
assert.throws(auth.bind(null, {}), /argument req is required/)
43+
})
4044
})
4145
})
4246

0 commit comments

Comments
 (0)