forked from panva/node-oidc-provider
-
Notifications
You must be signed in to change notification settings - Fork 2
/
memory_adapter.js
87 lines (68 loc) · 1.8 KB
/
memory_adapter.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
84
85
86
87
const LRU = require('lru-cache');
const epochTime = require('../helpers/epoch_time');
let storage = new LRU({});
function grantKeyFor(id) {
return `grant:${id}`;
}
function sessionUidKeyFor(id) {
return `sessionUid:${id}`;
}
function userCodeKeyFor(userCode) {
return `userCode:${userCode}`;
}
class MemoryAdapter {
constructor(model) {
this.model = model;
}
key(id) {
return `${this.model}:${id}`;
}
async destroy(id) {
const key = this.key(id);
storage.del(key);
}
async consume(id) {
storage.get(this.key(id)).consumed = epochTime();
}
async find(id) {
return storage.get(this.key(id));
}
async findByUid(uid) {
const id = storage.get(sessionUidKeyFor(uid));
return this.find(id);
}
async findByUserCode(userCode) {
const id = storage.get(userCodeKeyFor(userCode));
return this.find(id);
}
async upsert(id, payload, expiresIn) {
const key = this.key(id);
if (this.model === 'Session') {
storage.set(sessionUidKeyFor(payload.uid), id, expiresIn * 1000);
}
const { grantId, userCode } = payload;
if (grantId) {
const grantKey = grantKeyFor(grantId);
const grant = storage.get(grantKey);
if (!grant) {
storage.set(grantKey, [key]);
} else {
grant.push(key);
}
}
if (userCode) {
storage.set(userCodeKeyFor(userCode), id, expiresIn * 1000);
}
storage.set(key, payload, expiresIn * 1000);
}
async revokeByGrantId(grantId) { // eslint-disable-line class-methods-use-this
const grantKey = grantKeyFor(grantId);
const grant = storage.get(grantKey);
if (grant) {
grant.forEach((token) => storage.del(token));
storage.del(grantKey);
}
}
}
module.exports = MemoryAdapter;
module.exports.setStorage = (store) => { storage = store; };