-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (61 loc) · 2.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* Module dependencies
*/
var debug = require('simple-debug')('consulate-simple-secrets')
, ss = require("simple-secrets")
, SmD = require('smd')
, bitfield = require('bitfield');
/**
* Simple Secrets issue token for consulate
*
* @param {Object} options
* @return {Function}
*/
module.exports = function(options) {
// Check that they gave us a key to sign
if (!options || !options.key) throw new Error("Missing a `key` for simple-secrets signer");
// Create a sender
var key = new Buffer(options.key, 'hex')
, sender = ss(key);
var ttl = options.ttl || 1;
var transform = options.transform || defaultTransform;
debug('using ttl of', ttl);
function register(app) {
// Save the `scopes` callback for compression
var getScopes = app.callback('getScopes');
// Allow the consumer to map scopes to a compressed enum value
var compress = options.compressScope || bitfield.pack;
app.issueToken(function(client, user, scopes, done) {
debug('issuing token for client', client, 'and user', user, 'with scopes', scopes);
// Get a list of the scopes enum
getScopes(function(err, availableScopes) {
if (err) return done(err);
var expires = SmD.from(Date.now() + (ttl+0.7)*SmD.ms_per_unit);
// Create a token with simple-secrets
// We use short variable names since we want to keep the size of our token down
var tokenOpts = {
s: compress(scopes, availableScopes),
c: client.id,
e: expires
};
// Allow clients to have a detached token
if (user) tokenOpts.u = user.id;
transform(client, user, scopes, availableScopes, tokenOpts, function(err, transformedTokenOpts) {
if (err) return done(err);
var token = sender.pack(transformedTokenOpts || tokenOpts);
debug('issued token', token);
done(null, token, { expires_in: SmD.seconds_from_now(expires) });
});
});
});
};
// Expose the sender
register.sender = sender;
return register;
};
/**
* Setup a default transform function
*/
function defaultTransform(client, user, scope, availableScopes, tokenOpts, done) {
done(null, tokenOpts);
}