1 var http = require('http');
5 * Copyright(c) 2010 Sencha Inc.
6 * Copyright(c) 2011 TJ Holowaychuk
13 * Status: Deprecated. No bug reports or pull requests are welcomed
14 * for this middleware. However, this middleware will not be removed.
15 * Instead, you should use [basic-auth](https://github.com/visionmedia/node-basic-auth).
17 * Enfore basic authentication by providing a `callback(user, pass)`,
18 * which must return `true` in order to gain access. Alternatively an async
19 * method is provided as well, invoking `callback(user, pass, callback)`. Populates
20 * `req.user`. The final alternative is simply passing username / password
23 * Simple username and password
25 * connect(connect.basicAuth('username', 'password'));
27 * Callback verification
30 * .use(connect.basicAuth(function(user, pass){
31 * return 'tj' == user && 'wahoo' == pass;
34 * Async callback verification, accepting `fn(err, user)`.
37 * .use(connect.basicAuth(function(user, pass, fn){
38 * User.authenticate({ user: user, pass: pass }, fn);
41 * @param {Function|String} callback or username
42 * @param {String} realm
46 module.exports = function basicAuth(callback, realm) {
47 var username, password;
49 // user / pass strings
50 if ('string' == typeof callback) {
53 if ('string' != typeof password) throw new Error('password argument required');
55 callback = function(user, pass){
56 return user == username && pass == password;
60 realm = realm || 'Authorization Required';
62 return function(req, res, next) {
63 var authorization = req.headers.authorization;
65 if (req.user) return next();
66 if (!authorization) return unauthorized(res, realm);
68 var parts = authorization.split(' ');
70 if (parts.length !== 2) return next(error(400));
73 , credentials = new Buffer(parts[1], 'base64').toString()
74 , index = credentials.indexOf(':');
76 if ('Basic' != scheme || index < 0) return next(error(400));
78 var user = credentials.slice(0, index)
79 , pass = credentials.slice(index + 1);
82 if (callback.length >= 3) {
83 callback(user, pass, function(err, user){
84 if (err || !user) return unauthorized(res, realm);
85 req.user = req.remoteUser = user;
90 if (callback(user, pass)) {
91 req.user = req.remoteUser = user;
94 unauthorized(res, realm);
101 * Respond with 401 "Unauthorized".
103 * @param {ServerResponse} res
104 * @param {String} realm
108 function unauthorized(res, realm) {
109 res.statusCode = 401;
110 res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
111 res.end('Unauthorized');
115 * Generate an `Error` from the given status `code`
116 * and optional `msg`.
118 * @param {Number} code
119 * @param {String} msg
124 function error(code, msg){
125 var err = new Error(msg || http.STATUS_CODES[code]);