text: // Generated by CoffeeScript 1.8.0
  (function() {
    var BasicStrategy, FindAgent, RestClient, headers, passport, query, restClient, util;
  
    passport = require("passport");
  
    RestClient = require("http/client").HttpClient;
  
    util = require("util");
  
    headers = {};
  
    restClient = new RestClient(global.config.stormkeeper.url, global.config.stormkeeper.port);
  
    BasicStrategy = require("passport-http").BasicStrategy;
  
    query = require("dirty-query").query;
  
    FindAgent = function(stoken, serial) {
      var dlist, newdlist;
      dlist = global.agentsDB.list();
      if (dlist) {
        newdlist = dlist.filter((function(_this) {
          return function(entry) {
            if (entry && entry.data && entry.data.stoken === stoken && entry.data.serialkey === serial) {
              return true;
            }
          };
        })(this));
      }
      if (newdlist != null) {
        return newdlist[0];
      }
    };
  
    exports.BasicStrategy = new BasicStrategy(function(username, password, done) {
      return process.nextTick(function() {
        if (FindAgent(password, username) != null) {
          util.log("Authentication succeeded");
          return restClient.get("/tokens/" + password, headers, function(err, response) {
            if ((err != null) || (response == null)) {
              util.log("Authorization failed, err " + err);
            }
            if ((err != null) || (response == null)) {
              return done(null, false);
            }
            return done(null, {
              username: username,
              password: password,
              rules: response.rule.rules
            });
          });
        } else {
          return done(null, false);
        }
      });
    });
  
    exports.checkRule = function(req, res, next) {
      var id, key, rule, status, _i, _len, _ref;
      id = this.params.id;
      key = this.params.key;
      status = this.params.status;
      if (req.user.rules != null) {
        _ref = req.user.rules;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          rule = _ref[_i];
          if (id != null) {
            rule = rule.replace(":id", id);
          }
          if (key != null) {
            rule = rule.replace(":key", key);
          }
          if (status != null) {
            rule = rule.replace(":status", status);
          }
          if (req.method + " " + req.originalUrl === rule) {
            next();
            return;
          }
        }
      }
      res.status(401);
      return next("Forbidden");
    };
  
    exports.authenticate = passport.authenticate('basic', {
      session: false
    });
  
    exports.authorization = [exports.authenticate, exports.checkRule];
  
  }).call(this);
  