forked from okdistribute/cookie-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (80 loc) · 2.29 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
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
87
88
89
90
var memdb = require('memdb')
var debug = require('debug')('auth')
var cookie = require('./cookie.js')
module.exports = Auth
function deny(req, res, cb) {
setImmediate(function() {
cb(new Error('not authorized'))
})
}
function Auth(opts) {
var self = this
if (!(this instanceof Auth)) return new Auth(opts)
if (!opts) opts = {}
this.cookie = cookie(opts)
this.sessions = opts.sessions || memdb()
this.authenticator = opts.authenticator || deny
}
Auth.prototype.handle = function(req, res, cb) {
var self = this
self.getSession(req, function(err, session) { // ignore errors
if (session) return cb(null, session)
self.authenticator(req, res, function(err) {
// user is not authorized
if (err) {
debug('not authorized', err)
if (!session) return setImmediate(function() { cb(err) })
self.sessions.del(session.session, function(delErr) {
cb(err)
})
return
}
// authenticate user
self.login(res, cb)
})
})
}
Auth.prototype.getSession = function(req, cb) {
var sessionKey = this.cookie.get(req)
this.sessions.get(sessionKey, {valueEncoding: 'json'}, function(err, data) {
if (err) return cb(err)
var resp = {session: sessionKey, created: data.created, data: data.data}
debug('session OK', resp)
return cb(null, resp)
})
}
Auth.prototype.login = function(res, data, cb) {
var self = this
if (typeof data === 'function') {
cb = data
data = undefined
}
var newSession = self.cookie.create(res)
var val = {
created: new Date().toISOString(),
data: data
}
self.sessions.put(newSession, val, {valueEncoding: 'json'}, function(err) {
debug('new session', newSession)
cb(err, {session: newSession, created: val.created, data: val.data})
})
}
Auth.prototype.delete = function(req, cb) {
var session = this.cookie.get(req)
if (session) {
this.sessions.del(session, cb)
} else {
setImmediate(cb)
}
}
Auth.prototype.logout = function(req, res, cb) {
var self = this
this.delete(req, logout)
function logout() { // ignore err
res.statusCode = 401
res.setHeader('content-type', 'application/json')
self.cookie.destroy(res)
res.end(JSON.stringify({error: "Unauthorized", loggedOut: true}) + '\n')
if (cb) setImmediate(cb)
}
}