vibe.http.session 0/68(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
/** Cookie based session support. Copyright: © 2012-2013 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Jan Krüger, Sönke Ludwig, Ilya Shipunov */ module vibe.http.session; import vibe.core.log; import vibe.crypto.cryptorand; import std.array; import std.base64; import std.traits : hasAliasing; import std.variant; //random number generator //TODO: Use Whirlpool or SHA-512 here private SHA1HashMixerRNG g_rng; //The "URL and Filename safe" Base64 without padding alias Base64URLNoPadding = Base64Impl!('-', '_', Base64.NoPadding); /** Represents a single HTTP session. Indexing the session object with string keys allows to store arbitrary key/value pairs. */ struct Session { private { SessionStore m_store; string m_id; SessionStorageType m_storageType; } // created by the SessionStore using SessionStore.createSessionInstance private this(SessionStore store, string id = null) @safe { assert(id.length > 0); m_store = store; m_id = id; m_storageType = store.storageType; } /** Checks if the session is active. This operator enables a $(D Session) value to be used in conditionals to check if they are actially valid/active. */ bool opCast() const @safe { return m_store !is null; } /// unittest { //import vibe.http.server; // workaround for cyclic module ctor compiler error class HTTPServerRequest { Session session; string[string] form; } class HTTPServerResponse { Session startSession() { assert(false); } } void login(scope HTTPServerRequest req, scope HTTPServerResponse res) { // TODO: validate username+password // ensure that there is an active session if (!req.session) req.session = res.startSession(); // update session variables req.session.set("loginUser", req.form["user"]); } } /// Returns the unique session id of this session. @property string id() const @safe { return m_id; } /// Queries the session for the existence of a particular key. bool isKeySet(string key) @safe { return m_store.isKeySet(m_id, key); } /** Gets a typed field from the session. */ const(T) get(T)(string key, lazy T def_value = T.init) @trusted { // Variant, deserializeJson/deserializeBson static assert(!hasAliasing!T, "Type "~T.stringof~" contains references, which is not supported for session storage."); auto val = m_store.get(m_id, key, serialize(def_value)); return deserialize!T(val); } /** Sets a typed field to the session. */ void set(T)(string key, T value) { static assert(!hasAliasing!T, "Type "~T.stringof~" contains references, which is not supported for session storage."); m_store.set(m_id, key, serialize(value)); } // Removes a field from a session void remove(string key) @safe { m_store.remove(m_id, key); } /** Enables foreach-iteration over all keys of the session. */ int opApply(scope int delegate(string key) @safe del) @safe { return m_store.iterateSession(m_id, del); } /// unittest { //import vibe.http.server; // workaround for cyclic module ctor compiler error class HTTPServerRequest { Session session; } class HTTPServerResponse { import vibe.core.stream; OutputStream bodyWriter() @safe { assert(false); } string contentType; } // sends all session entries to the requesting browser // assumes that all entries are strings void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res) { res.contentType = "text/plain"; req.session.opApply((key) @safe { res.bodyWriter.write(key ~ ": " ~ req.session.get!string(key) ~ "\n"); return 0; }); } } package void destroy() @safe { m_store.destroy(m_id); } private Variant serialize(T)(T val) { import vibe.data.json; import vibe.data.bson; final switch (m_storageType) with (SessionStorageType) { case native: return () @trusted { return Variant(val); } (); case json: return () @trusted { return Variant(serializeToJson(val)); } (); case bson: return () @trusted { return Variant(serializeToBson(val)); } (); } } private T deserialize(T)(ref Variant val) { import vibe.data.json; import vibe.data.bson; final switch (m_storageType) with (SessionStorageType) { case native: return () @trusted { return val.get!T; } (); case json: return () @trusted { return deserializeJson!T(val.get!Json); } (); case bson: return () @trusted { return deserializeBson!T(val.get!Bson); } (); } } } /** Interface for a basic session store. A sesseion store is responsible for storing the id and the associated key/value pairs of a session. */ interface SessionStore { @safe: /// Returns the internal type used for storing session keys. @property SessionStorageType storageType() const; /// Creates a new session. Session create(); /// Opens an existing session. Session open(string id); /// Sets a name/value pair for a given session. void set(string id, string name, Variant value); /// Returns the value for a given session key. Variant get(string id, string name, lazy Variant defaultVal); /// Determines if a certain session key is set. bool isKeySet(string id, string key); /// Removes a key from a session void remove(string id, string key); /// Terminates the given session. void destroy(string id); /// Iterates all keys stored in the given session. int iterateSession(string id, scope int delegate(string key) @safe del); /// Creates a new Session object which sources its contents from this store. protected final Session createSessionInstance(string id = null) { if (!id.length) { ubyte[64] rand; if (!g_rng) g_rng = new SHA1HashMixerRNG(); g_rng.read(rand); id = () @trusted { return cast(immutable)Base64URLNoPadding.encode(rand); } (); } return Session(this, id); } } enum SessionStorageType { native, json, bson } /** Session store for storing a session in local memory. If the server is running as a single instance (no thread or process clustering), this kind of session store provies the fastest and simplest way to store sessions. In any other case, a persistent session store based on a database is necessary. */ final class MemorySessionStore : SessionStore { @safe: private { Variant[string][string] m_sessions; } @property SessionStorageType storageType() const { return SessionStorageType.native; } Session create() { auto s = createSessionInstance(); m_sessions[s.id] = null; return s; } Session open(string id) { auto pv = id in m_sessions; return pv ? createSessionInstance(id) : Session.init; } void set(string id, string name, Variant value) @trusted { // Variant m_sessions[id][name] = value; foreach(k, v; m_sessions[id]) logTrace("Csession[%s][%s] = %s", id, k, v); } Variant get(string id, string name, lazy Variant defaultVal) @trusted { // Variant assert(id in m_sessions, "session not in store"); foreach(k, v; m_sessions[id]) logTrace("Dsession[%s][%s] = %s", id, k, v); if (auto pv = name in m_sessions[id]) { return *pv; } else { return defaultVal; } } bool isKeySet(string id, string key) { return (key in m_sessions[id]) !is null; } void remove(string id, string key) { m_sessions[id].remove(key); } void destroy(string id) { m_sessions.remove(id); } int delegate(int delegate(ref string key, ref Variant value) @safe) @safe iterateSession(string id) { assert(id in m_sessions, "session not in store"); int iterator(int delegate(ref string key, ref Variant value) @safe del) @safe { foreach( key, ref value; m_sessions[id] ) if( auto ret = del(key, value) != 0 ) return ret; return 0; } return &iterator; } int iterateSession(string id, scope int delegate(string key) @safe del) @trusted { // hash map iteration assert(id in m_sessions, "session not in store"); foreach (key; m_sessions[id].byKey) if (auto ret = del(key)) return ret; return 0; } }