-
Notifications
You must be signed in to change notification settings - Fork 34
/
session.js
47 lines (44 loc) · 1.21 KB
/
session.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
const noop = () => undefined;
const validate = keystone => ({ valid = noop, invalid = noop }) => async (req, res, next) => {
if (!req.session || !req.session.keystoneItemId) {
invalid({ req, reason: 'empty' });
return next();
}
const list = keystone.lists[req.session.keystoneListKey];
if (!list) {
// TODO: probably destroy the session
invalid({ req, reason: 'invalid-list' });
return next();
}
const item = await list.adapter.findById(req.session.keystoneItemId);
if (!item) {
// TODO: probably destroy the session
invalid({ req, reason: 'invalid-item' });
return next();
}
valid({ req, list, item });
next();
};
function create(req, { item, list }) {
return new Promise((resolve, reject) =>
req.session.regenerate(err => {
if (err) return reject(err);
req.session.keystoneListKey = list.key;
req.session.keystoneItemId = item.id;
resolve();
})
);
}
function destroy(req) {
return new Promise((resolve, reject) =>
req.session.regenerate(err => {
if (err) return reject(err);
resolve({ success: true });
})
);
}
module.exports = keystone => ({
create: create,
destroy: destroy,
validate: validate(keystone),
});