1 |
|
2 |
|
3 |
|
4 |
|
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 |
|
21 |
|
22 |
|
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 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
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 |
|