1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | var crypto = require('crypto');
|
9 | var config = require('./config');
|
10 |
|
11 | function digest(message, key) {
|
12 | return crypto.createHmac("sha256", new Buffer(key, "hex")).update(message).digest('hex');
|
13 | }
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | function escapeToLower(url) {
|
21 | return encodeURIComponent(url).replace(/%../g, function (match) {
|
22 | return match.toLowerCase();
|
23 | });
|
24 | }
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 | module.exports = function (options) {
|
46 | var tokenName = options.token_name ? options.token_name : "__cld_token__";
|
47 | if (options.expiration == null) {
|
48 | if (options.duration != null) {
|
49 | var start = options.start_time != null ? options.start_time : Math.round(Date.now() / 1000);
|
50 | options.expiration = start + options.duration;
|
51 | } else {
|
52 | throw new Error("Must provide either expiration or duration");
|
53 | }
|
54 | }
|
55 | var tokenParts = [];
|
56 | if (options.ip != null) {
|
57 | tokenParts.push(`ip=${options.ip}`);
|
58 | }
|
59 | if (options.start_time != null) {
|
60 | tokenParts.push(`st=${options.start_time}`);
|
61 | }
|
62 | tokenParts.push(`exp=${options.expiration}`);
|
63 | if (options.acl != null) {
|
64 | tokenParts.push(`acl=${escapeToLower(options.acl)}`);
|
65 | }
|
66 | var toSign = [].concat(tokenParts);
|
67 | if (options.url) {
|
68 | var url = escapeToLower(options.url);
|
69 | toSign.push(`url=${url}`);
|
70 | }
|
71 | var auth = digest(toSign.join("~"), options.key);
|
72 | tokenParts.push(`hmac=${auth}`);
|
73 | return `${tokenName}=${tokenParts.join('~')}`;
|
74 | }; |
\ | No newline at end of file |