-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcreate.js
More file actions
63 lines (55 loc) · 1.92 KB
/
Copy pathcreate.js
File metadata and controls
63 lines (55 loc) · 1.92 KB
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
const uuidv4 = require('uuid').v4;
const Promise = require('bluebird');
const { ActionTransport } = require('@microfleet/core');
const { sign } = require('../../utils/signatures');
const redisKey = require('../../utils/key');
const handlePipelineError = require('../../utils/pipeline-error');
const { getUserId } = require('../../utils/userData');
const { USERS_API_TOKENS, USERS_API_TOKENS_ZSET, BEARER_USERNAME_FIELD } = require('../../constants');
function storeData(userId) {
const { redis, name } = this;
const tokenPart = uuidv4();
// transform input
const payload = `${userId}.${tokenPart}`;
const signature = sign.call(this, payload);
const token = `${payload}.${signature}`;
// stores all issued keys and it's date
const key = redisKey(USERS_API_TOKENS, payload);
const zset = redisKey(USERS_API_TOKENS_ZSET, userId);
// prepare to store
return redis
.pipeline()
.hmset(key, {
[BEARER_USERNAME_FIELD]: userId,
name,
uuid: tokenPart,
})
.zadd(zset, Date.now(), payload)
.exec()
.then(handlePipelineError)
.return(token);
}
/**
* @api {amqp} <prefix>.token.create Create Token
* @apiVersion 1.0.0
* @apiName CreateToken
* @apiGroup Tokens
*
* @apiDescription This method allows to create an access token, which can be used instead of
* username+password exchanged for JWT. This is usable directly in .verify, but requires special flag
* passed to indicate type of token being used
*
* @apiParam (Payload) {String} username - id of the user
* @apiParam (Payload) {String} name - used to identify token
*/
function createToken({ params }) {
const { username, name } = params;
const { redis, config, userData } = this;
const context = { name, redis, config, userData };
return Promise
.bind(context, username)
.then(getUserId)
.then(storeData);
}
createToken.transports = [ActionTransport.amqp, ActionTransport.internal];
module.exports = createToken;