xonecas.io
186
Ft

fractal-tree / files

fractal-tree / node_modules / connect / lib / middleware / basicAuth.js

2.3 KB
1
2/*!
3 * Connect - basicAuth
4 * Copyright(c) 2010 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
6 * MIT Licensed
7 */
8
9/**
10 * Module dependencies.
11 */
12
13var utils = require('../utils')
14  , unauthorized = utils.unauthorized
15  , badRequest = utils.badRequest;
16
17/**
18 * Enfore basic authentication by providing a `callback(user, pass)`,
19 * which must return `true` in order to gain access. Alternatively an async
20 * method is provided as well, invoking `callback(user, pass, callback)`. Populates
21 * `req.remoteUser`. The final alternative is simply passing username / password
22 * strings.
23 *
24 * Examples:
25 *
26 *     connect(connect.basicAuth('username', 'password'));
27 *
28 *     connect(
29 *       connect.basicAuth(function(user, pass){
30 *         return 'tj' == user & 'wahoo' == pass;
31 *       })
32 *     );
33 *
34 *     connect(
35 *       connect.basicAuth(function(user, pass, fn){
36 *         User.authenticate({ user: user, pass: pass }, fn);
37 *       })
38 *     );
39 *
40 * @param {Function|String} callback or username
41 * @param {String} realm
42 * @api public
43 */
44
45module.exports = function basicAuth(callback, realm) {
46  var username, password;
47
48  // user / pass strings
49  if ('string' == typeof callback) {
50    username = callback;
51    password = realm;
52    if ('string' != typeof password) throw new Error('password argument required');
53    realm = arguments[2];
54    callback = function(user, pass){
55      return user == username && pass == password;
56    }
57  }
58
59  realm = realm || 'Authorization Required';
60
61  return function(req, res, next) {
62    var authorization = req.headers.authorization;
63
64    if (req.remoteUser) return next();
65    if (!authorization) return unauthorized(res, realm);
66
67    var parts = authorization.split(' ')
68      , scheme = parts[0]
69      , credentials = new Buffer(parts[1], 'base64').toString().split(':');
70
71    if ('Basic' != scheme) return badRequest(res);
72
73    // async
74    if (callback.length >= 3) {
75      var pause = utils.pause(req);
76      callback(credentials[0], credentials[1], function(err, user){
77        if (err || !user)  return unauthorized(res, realm);
78        req.remoteUser = user;
79        next();
80        pause.resume();
81      });
82    // sync
83    } else {
84      if (callback(credentials[0], credentials[1])) {
85        req.remoteUser = credentials[0];
86        next();
87      } else {
88        unauthorized(res, realm);
89      }
90    }
91  }
92};
93