-
Notifications
You must be signed in to change notification settings - Fork 284
/
sessionstore.d
213 lines (181 loc) · 4.88 KB
/
sessionstore.d
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
MongoDB based HTTP session store.
Copyright: © 2017 Sönke Ludwig
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig
*/
module vibe.db.mongo.sessionstore;
import vibe.data.json;
import vibe.db.mongo.mongo;
import vibe.http.session;
import core.time;
import std.datetime : Clock, SysTime, UTC;
import std.typecons : Nullable;
import std.variant;
///
unittest {
import vibe.core.core : runApplication;
import vibe.db.mongo.sessionstore : MongoSessionStore;
import vibe.http.server : HTTPServerSettings, listenHTTP;
import vibe.http.router : URLRouter;
import core.time : hours;
void main()
{
auto store = new MongoSessionStore("mongodb://127.0.0.1/mydb", "sessions");
store.expirationTime = 5.hours;
auto settings = new HTTPServerSettings("127.0.0.1:8080");
settings.sessionStore = store;
auto router = new URLRouter;
// TODO: add some routes
listenHTTP(settings, router);
runApplication();
}
}
final class MongoSessionStore : SessionStore {
@safe:
private {
MongoCollection m_sessions;
Duration m_expirationTime = Duration.max;
}
/** Constructs a new MongoDB session store.
Params:
url = URL of the MongoDB database (e.g. `"mongodb://localhost/mydb"`)
database = Name of the database to use
collection = Optional collection name to store the sessions in
*/
this(string url, string collection = "sessions")
{
import std.exception : enforce;
MongoClientSettings settings;
enforce(parseMongoDBUrl(settings, url),
"Failed to parse MongoDB URL.");
auto db = connectMongoDB(settings).getDatabase(settings.database);
m_sessions = db[collection];
}
/** The duration without access after which a session expires.
*/
@property Duration expirationTime() const { return m_expirationTime; }
/// ditto
@property void expirationTime(Duration dur)
{
import std.typecons : tuple;
IndexModel[1] index;
index[0].add("time", 1);
index[0].options.expireAfter = dur;
m_sessions.createIndexes(index[]);
m_expirationTime = dur;
}
@property SessionStorageType storageType() const { return SessionStorageType.bson; }
Session create()
{
auto s = createSessionInstance();
m_sessions.insertOne(SessionEntry(s.id, Clock.currTime(UTC())));
return s;
}
Session open(string id)
{
auto res = m_sessions.findAndModify(["_id": id], ["$set": ["time": Clock.currTime(UTC())]], ["_id": 1]);
if (!res.isNull) return createSessionInstance(id);
return Session.init;
}
void set(string id, string name, Variant value)
@trusted {
m_sessions.updateOne(["_id": id], ["$set": [name.escape: value.get!Bson, "time": Clock.currTime(UTC()).serializeToBson]]);
}
Variant get(string id, string name, lazy Variant defaultVal)
@trusted {
auto f = name.escape;
FindOptions options;
options.projection = Bson([f: Bson(1)]);
auto r = m_sessions.findOne(["_id": id], options);
if (r.isNull) return defaultVal;
auto v = r.tryIndex(f);
if (v.isNull) return defaultVal;
return Variant(v.get);
}
bool isKeySet(string id, string key)
{
auto f = key.escape;
FindOptions options;
options.projection = Bson([f: Bson(1)]);
auto r = m_sessions.findOne(["_id": id], options);
if (r.isNull) return false;
return !r.tryIndex(f).isNull;
}
void remove(string id, string key)
{
m_sessions.updateOne(["_id": id], ["$unset": [key.escape: 1]]);
}
void destroy(string id)
{
m_sessions.deleteOne(["_id": id]);
}
int iterateSession(string id, scope int delegate(string key) @safe del)
{
import std.algorithm.searching : startsWith;
auto r = m_sessions.findOne(["_id": id]);
foreach (k, _; r.byKeyValue) {
if (k.startsWith("f_")) {
auto f = k.unescape;
if (auto ret = del(f))
return ret;
}
}
return 0;
}
private static struct SessionEntry {
string _id;
SysTime time;
}
}
private string escape(string field_name)
@safe {
import std.array : appender;
import std.format : formattedWrite;
auto ret = appender!string;
ret.reserve(field_name.length + 2);
ret.put("f_");
foreach (char ch; field_name) {
switch (ch) {
default:
ret.formattedWrite("+%02X", cast(int)ch);
break;
case 'a': .. case 'z':
case 'A': .. case 'Z':
case '0': .. case '9':
case '_', '-':
ret.put(ch);
break;
}
}
return ret.data;
}
private string unescape(string key)
@safe {
import std.algorithm.searching : startsWith;
import std.array : appender;
import std.conv : to;
assert(key.startsWith("f_"));
key = key[2 .. $];
auto ret = appender!string;
ret.reserve(key.length);
while (key.length) {
if (key[0] == '+') {
ret.put(cast(char)key[1 .. 3].to!int(16));
key = key[3 .. $];
} else {
ret.put(key[0]);
key = key[1 .. $];
}
}
return ret.data;
}
@safe unittest {
void test(string raw, string enc) {
assert(escape(raw) == enc);
assert(unescape(enc) == raw);
}
test("foo", "f_foo");
test("foo.bar", "f_foo+2Ebar");
test("foo+bar", "f_foo+2Bbar");
}