forked from lindleycb/meteor-stale-session
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
44 lines (42 loc) · 1.82 KB
/
server.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
//
// Server side activity detection for the session timeout
//
// Meteor settings:
// - staleSessionInactivityTimeout: the amount of time (in ms) after which, if no activity is noticed, a session will be considered stale
// - staleSessionPurgeInterval: interval (in ms) at which stale sessions are purged i.e. found and forcibly logged out
// - staleSessionForceLogout: whether or not we want to force log out and purge stale sessions
//
var staleSessionPurgeInterval =
(Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionPurgeInterval) || 1 * 60 * 1000; // 1min
var inactivityTimeout =
(Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionInactivityTimeout) || 30 * 60 * 1000; // 30mins
var forceLogout = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionForceLogout;
//
// provide a user activity heartbeat method which stamps the user record with a timestamp of the last
// received activity heartbeat.
//
Meteor.methods({
heartbeat: async function (options) {
if (!this.userId) {
return;
}
let user = await Meteor.users.findOneAsync(this.userId);
if (user) {
await Meteor.users.updateAsync(user._id, { $set: { heartbeat: new Date() } });
}
},
});
//
// periodically purge any stale sessions, removing their login tokens and clearing out the stale heartbeat.
//
if (forceLogout !== false) {
Meteor.setInterval(async function () {
let now = new Date(),
overdueTimestamp = new Date(now - inactivityTimeout);
await Meteor.users.updateAsync(
{ heartbeat: { $lt: overdueTimestamp } },
{ $set: { "services.resume.loginTokens": [] }, $unset: { heartbeat: 1 } },
{ multi: true },
);
}, staleSessionPurgeInterval);
}