UNPKG

2.69 kBJavaScriptView Raw
1
2/**
3 * Authorization Token
4 * @module auth_token
5 */
6
7(function() {
8 var config, crypto, digest, escape_to_lower;
9
10 crypto = require('crypto');
11
12 config = require('./config');
13
14 digest = function(message, key) {
15 return crypto.createHmac("sha256", new Buffer(key, "hex")).update(message).digest('hex');
16 };
17
18
19 /**
20 * Escape url using lowercase hex code
21 * @param {string} url a url string
22 * @return escaped url
23 */
24
25 escape_to_lower = function(url) {
26 return encodeURIComponent(url).replace(/%../g, function(match) {
27 return match.toLowerCase();
28 });
29 };
30
31
32 /**
33 * Generate an authorization token
34 * @param {Object} options
35 * @param {string} options.key - the secret key required to sign the token
36 * @param {string} [options.ip] - the IP address of the client
37 * @param {number} [options.start_time=now] - the start time of the token in seconds from epoch
38 * @param {string} [options.expiration] - the expiration time of the token in seconds from epoch
39 * @param {string} [options.duration] - the duration of the token (from start_time)
40 * @param {string} [options.acl] - the ACL for the token
41 * @param {string} [options.url] - the URL to authentication in case of a URL token
42 * @returns {string} the authorization token
43 */
44
45 module.exports = function(options) {
46 var auth, part, ref, ref1, start, toSign, tokenName, tokenParts, url;
47 tokenName = (ref = options.token_name) != null ? ref : "__cld_token__";
48 if (options.expiration == null) {
49 if (options.duration != null) {
50 start = (ref1 = options.start_time) != null ? ref1 : Math.round(Date.now() / 1000);
51 options.expiration = start + options.duration;
52 } else {
53 throw new Error("Must provide either expiration or duration");
54 }
55 }
56 tokenParts = [];
57 if (options.ip != null) {
58 tokenParts.push("ip=" + options.ip);
59 }
60 if (options.start_time != null) {
61 tokenParts.push("st=" + options.start_time);
62 }
63 tokenParts.push("exp=" + options.expiration);
64 if (options.acl != null) {
65 tokenParts.push("acl=" + (escape_to_lower(options.acl)));
66 }
67 toSign = (function() {
68 var i, len, results;
69 results = [];
70 for (i = 0, len = tokenParts.length; i < len; i++) {
71 part = tokenParts[i];
72 results.push(part);
73 }
74 return results;
75 })();
76 if (options.url) {
77 url = escape_to_lower(options.url);
78 toSign.push("url=" + url);
79 }
80 auth = digest(toSign.join("~"), options.key);
81 tokenParts.push("hmac=" + auth);
82 return tokenName + "=" + (tokenParts.join('~'));
83 };
84
85}).call(this);
86
87//# sourceMappingURL=auth_token.js.map