/
session.js
74 lines (66 loc) · 2.75 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
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
/**
* @typedef {import("../../types/node/sessionTypes").SessionData} SessionTypes.SessionData
*/
const MongoDb = require("mongodb"),
Db = require("."),
Encryption = require("./encryption");
// ### # #### #
// # # # # #
// # ### ### ### ## ### # ## # # # ##
// ### # # # # # # # ## # # # ## #
// # ##### ### ### # # # # # # # # #
// # # # # # # # # # # # # ## #
// ### ### #### #### ### ### # # #### # ##
/**
* A class to handle database calls to the session collection.
*/
class SessionDb {
// # ## #
// # # #
// ### ## # ## ### ##
// # # # ## # # ## # # ##
// # # ## # ## # ##
// ### ## ### ## ## ##
/**
* Deletes a sessino by its ID.
* @param {string} id The session ID.
* @returns {Promise} A promise that resolves when the session has been deleted.
*/
static async delete(id) {
const db = await Db.get();
await db.collection("session").deleteOne({_id: MongoDb.ObjectId.createFromHexString(id)});
}
// # #
// # #
// # # ### ### ### ### ##
// # # # # # # # # # # ##
// # # # # # # # ## # ##
// ### ### ### # # ## ##
// #
/**
* Updates the session.
* @param {SessionTypes.SessionData} session The session to update.
* @returns {Promise} A promise that resolves when the session has been updated.
*/
static async update(session) {
const db = await Db.get();
const encryptedTokens = {
accessToken: Encryption.encryptWithSalt(session.accessToken),
refreshToken: Encryption.encryptWithSalt(session.refreshToken)
};
await db.collection("session").findOneAndUpdate({_id: MongoDb.ObjectId.createFromHexString(session._id), ip: session.ip, userId: MongoDb.Long.fromNumber(session.userId)}, {$set: {
ip: session.ip,
userId: MongoDb.Long.fromNumber(session.userId),
accessToken: {
salt: new MongoDb.Binary(encryptedTokens.accessToken.salt),
encrypted: new MongoDb.Binary(encryptedTokens.accessToken.encrypted)
},
refreshToken: {
salt: new MongoDb.Binary(encryptedTokens.refreshToken.salt),
encrypted: new MongoDb.Binary(encryptedTokens.refreshToken.encrypted)
},
expires: session.expires
}});
}
}
module.exports = SessionDb;