forked from panva/node-oidc-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb.js
86 lines (67 loc) · 2.21 KB
/
mongodb.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
const { MongoClient } = require('mongodb'); // eslint-disable-line import/no-unresolved
const { snakeCase } = require('lodash');
let DB;
class CollectionSet extends Set {
add(name) {
const nu = this.has(name);
super.add(name);
if (!nu) {
DB.collection(name).createIndexes([
{ key: { grantId: 1 } },
{ key: { expiresAt: 1 }, expireAfterSeconds: 0 },
]).catch(console.error); // eslint-disable-line no-console
}
}
}
const collections = new CollectionSet();
class MongoAdapter {
constructor(name) {
this.name = snakeCase(name);
collections.add(this.name);
}
coll(name) {
return this.constructor.coll(name || this.name);
}
static coll(name) {
return DB.collection(name);
}
destroy(id) {
return this.coll().findOneAndDelete({ _id: id })
.then((found) => {
if (found.value && found.value.grantId) {
const promises = [];
collections.forEach((name) => {
promises.push(this.coll(name).deleteMany({ grantId: found.value.grantId }));
});
return Promise.all(promises);
}
return undefined;
});
}
consume(id) {
return this.coll().findOneAndUpdate({ _id: id }, { $currentDate: { consumed: true } });
}
find(id) {
return this.coll().find({ _id: id }).limit(1).next();
}
upsert(_id, payload, expiresIn) {
let expiresAt;
if (expiresIn) {
expiresAt = new Date(Date.now() + (expiresIn * 1000));
}
// HEROKU EXAMPLE ONLY, do not use the following block unless you want to drop dynamic
// registrations 24 hours after registration
if (this.name === 'client') {
expiresAt = new Date(Date.now() + (24 * 60 * 60 * 1000));
}
const document = Object.assign(payload, expiresAt && { expiresAt });
// the above does not work for _id sharded collections, use the one below
// const document = Object.assign(payload, { _id }, expiresAt && { expiresAt });
return this.coll().updateOne({ _id }, { $set: document }, { upsert: true });
}
static async connect() {
const connection = await MongoClient.connect(process.env.MONGODB_URI);
DB = connection.db(connection.s.options.dbName);
}
}
module.exports = MongoAdapter;