-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.js
More file actions
97 lines (84 loc) · 2.55 KB
/
store.js
File metadata and controls
97 lines (84 loc) · 2.55 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* eslint-disable camelcase */
'use strict';
const {promisify} = require('util');
const redisScan = require('redisscan');
const t = require('tcomb');
const RefreshTokenJTI = t.String;
const AccessTokenJTI = t.String;
const TTL = t.Number;
module.exports = function Store({client, baseString = 'authomatic'}) {
const UserId = userId => {
t.String(userId);
if(userId.includes(baseString)) {
throw new Error(`User id: ${userId} should not contain the base string _${baseString}_.
Change the base string or the userId`);
}
return userId;
};
const setAsync = promisify(client.set).bind(client);
const delAsync = promisify(client.del).bind(client);
const getKeyPrefix = userId => `${userId}_${baseString}_`;
const getKey = (userId, refreshToken) => `${getKeyPrefix(userId)}${refreshToken}`;
/**
* Register token and refresh token to the user
* @param {String} userId
* @param {String} refreshTokenJTI
* @param {String} accessTokenJTI
* @param {Number} ttl time to live in ms
* @returns {Promise<Boolean>} returns true when created.
*/
const add = (userId, refreshTokenJTI, accessTokenJTI, ttl) => setAsync(
getKey(
UserId(userId),
RefreshTokenJTI(refreshTokenJTI)
),
// Not used yet, might be used later.
AccessTokenJTI(accessTokenJTI),
'EX', TTL(ttl)
).then(Boolean);
/**
* Scans for redis keys
* @param userId
*/
const scanKeys = userId => {
const set = new Set();
return new Promise((resolve, reject) => {
redisScan({
redis: client,
pattern: `${getKeyPrefix(userId)}*`,
keys_only: true,
each_callback: function (type, key, subkey, length, value, cb) {
set.add(key);
cb();
},
done_callback: function (err) {
if(err) {return reject(err);}
return resolve([...set]);
}
});
});
};
/**
* Remove a single refresh token from the user
* @param userId
* @param refreshTokenJTI
* @returns {Promise<Boolean>} true if found and deleted, otherwise false.
*/
const remove = (userId, refreshTokenJTI) =>
delAsync(getKey(UserId(userId), RefreshTokenJTI(refreshTokenJTI))).then(Boolean);
/**
* Removes all tokens for a particular user
* @param userId
* @returns {Promise<Boolean>} true if any were found and delete, false otherwise
*/
const removeAll = async userId => {
const keys = await scanKeys(UserId(userId));
return Boolean(keys.length && await delAsync(keys));
};
return {
remove,
removeAll,
add,
client
};
};