-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (38 loc) · 1.78 KB
/
index.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
var Expirer = require('expire-unused-keys')
var spaces = require('level-spaces')
var authenticate = require('./lib/authenticate.js')
var createSession = require('./lib/createSession.js')
var deleteSession = require('./lib/deleteSession.js')
var sessionExists = require('./lib/sessionExists.js')
var unauthenticate = require('./lib/unauthenticate.js')
var isAuthenticated = require('./lib/isAuthenticated.js')
var defaultInactivity = 7 * 24 * 60 * 60 * 1000 // 1 week
var defaultInterval = 10 * 1000 // 10 sec
module.exports = function SessionState(core, db, opts) {
if (!core) throw new Error('Expected a just-login-core instance')
if (!db) throw new Error('Expected a levelup database')
if (!opts) opts = {}
var authedSessionsExpirer = new Expirer(
opts.unauthenticateAfterMs || defaultInactivity,
spaces(db, 'authed-session-expiration'),
opts.checkIntervalMs || defaultInterval
)
var sessionsExpirer = new Expirer(
opts.deleteSessionAfterMs || defaultInactivity,
spaces(db, 'session-expiration'),
opts.checkIntervalMs || defaultInterval
)
var authedSessionsDb = spaces(db, 'authed-sessions')
var sessionsDb = spaces(db, 'sessions')
var sessionState = {
createSession: createSession(sessionsDb, sessionsExpirer),
deleteSession: deleteSession(sessionsDb, sessionsExpirer),
sessionExists: sessionExists(sessionsDb, sessionsExpirer),
unauthenticate: unauthenticate(authedSessionsDb, authedSessionsExpirer, sessionsExpirer),
isAuthenticated: isAuthenticated(authedSessionsDb, authedSessionsExpirer, sessionsExpirer)
}
core.on('authenticated', authenticate(authedSessionsDb, authedSessionsExpirer, sessionsExpirer))
authedSessionsExpirer.on('expire', unauthenticate(authedSessionsDb, authedSessionsExpirer))
sessionsExpirer.on('expire', sessionState.deleteSession)
return sessionState
}