forked from verily-org/verily
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orm-session-store.js
130 lines (99 loc) · 3.47 KB
/
orm-session-store.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// Reference: Adapted by Alex from https://github.com/visionmedia/connect-redis/blob/master/lib/connect-redis.js
/*!
* Connect - Redis
* Copyright(c) 2012 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* One day in seconds.
*/
var oneDay = 86400;
// For persistent sessions using node-orm2
module.exports = function(connect) {
var Store = connect.session.Store;
var syncedModels;
function ORMSessionStore(models, options) {
var self = this;
options = options || {};
syncedModels = models;
this.ttl = options.ttl;
}
// Inherit from connect Store
ORMSessionStore.prototype.__proto__ = Store.prototype;
// Get a session identified by session id.
ORMSessionStore.prototype.get = function(sid, callback) {
syncedModels.Session.find({
sid: sid
}, 1, function(err, results) {
if (err) {
return callback(err);
}
if (!results || results.length === 0) {
console.log('returning as no results')
return callback();
}
var parsed;
var result = results[0];
var value = result.value.toString();
try {
parsed = JSON.parse(value);
} catch (err) {
return callback(err);
}
return callback(null, parsed);
});
};
// Set session identified by session id.
ORMSessionStore.prototype.set = function(sid, sess, callback) {
var maxAge = sess.cookie.maxAge;
var ttl = this.ttl;
ttl = ttl || ('number' == typeof maxAge
? maxAge / 1000 | 0
: oneDay);
sess.ttl = ttl;
var sess = JSON.stringify(sess);
syncedModels.Session.find({
sid: sid
}, 1, function(err, results) {
if (results && results.length !== 0 && results[0]) {
// This session is already stored in the database,
// update it.
var instance = results[0];
instance.value = sess;
instance.save(function (err) {
if (err) {
callback && callback(err);
} else {
callback && callback.apply(this, arguments);
}
});
} else {
// This session not yet stored in the database,
// create it.
syncedModels.Session.create({
sid: sid,
value: sess
}, function (err, results) {
if (err) {
callback && callback(err);
} else {
callback && callback.apply(this, arguments);
}
});
}
});
};
// Destroy session identified by session id.
ORMSessionStore.prototype.destroy = function(sid, callback) {
syncedModels.Session.find({
sid: sid
}, 1).remove(function(err) {
if (err) {
callback(err);
} else {
callback(null);
}
})
};
return ORMSessionStore;
};