Source: lib/auth_token.js

// Generated by CoffeeScript 1.12.2

/**
  * Authorization Token
  * @module auth_token
 */

(function() {
  var config, crypto, digest;

  crypto = require('crypto');

  config = require('./config');

  digest = function(message, key) {
    return crypto.createHmac("sha256", new Buffer(key, "hex")).update(message).digest('hex');
  };


  /**
    * Generate an authorization token
    * @param {Object} options
    * @param {string} options.key - the secret key required to sign the token
    * @param {string} [options.ip] - the IP address of the client
    * @param {number} [options.start_time=now] - the start time of the token in seconds from epoch
    * @param {string} [options.expiration] - the expiration time of the token in seconds from epoch
    * @param {string} [options.duration] - the duration of the token (from start_time)
    * @param {string} [options.acl] - the ACL for the token
    * @param {string} [options.url] - the URL to authentication in case of a URL token
    * @returns {string} the authorization token
   */

  module.exports = function(options) {
    var auth, params, part, ref, ref1, start, toSign, tokenName, tokenParts, url;
    params = Object.assign({}, config().auth_token, options);
    tokenName = (ref = params.token_name) != null ? ref : "__cld_token__";
    if (params.expiration == null) {
      if (params.duration != null) {
        start = (ref1 = params.start_time) != null ? ref1 : Math.round(Date.now() / 1000);
        params.expiration = start + params.duration;
      } else {
        throw new Error("Must provide either end_time or window");
      }
    }
    tokenParts = [];
    if (params.ip != null) {
      tokenParts.push("ip=" + params.ip);
    }
    if (params.start_time != null) {
      tokenParts.push("st=" + params.start_time);
    }
    tokenParts.push("exp=" + params.expiration);
    if (params.acl != null) {
      tokenParts.push("acl=" + params.acl);
    }
    toSign = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = tokenParts.length; i < len; i++) {
        part = tokenParts[i];
        results.push(part);
      }
      return results;
    })();
    if (params.url) {
      url = encodeURIComponent(params.url).replace(/%../g, function(match) {
        return match.toLowerCase();
      });
      toSign.push("url=" + url);
    }
    auth = digest(toSign.join("~"), params.key);
    tokenParts.push("hmac=" + auth);
    return tokenName + "=" + (tokenParts.join('~'));
  };

}).call(this);

//# sourceMappingURL=auth_token.js.map