1 module mongostore; 2 3 import vibe.http.session; 4 import vibe.db.mongo.mongo; 5 import vibe.db.mongo.database; 6 import vibe.db.mongo.client; 7 import vibe.db.mongo.connection; 8 import vibe.data.bson; 9 import std.variant; 10 11 /// Session class for `HTTPServerSettings.sessionStore` 12 final class MongoSessionStore : SessionStore 13 { 14 public: 15 /// 16 this(string host, string database, string collection = "sessions_") 17 { 18 _collection = connectMongoDB(host).getDatabase(database)[collection]; 19 } 20 21 /// 22 this(MongoClient client, string database, string collection = "sessions_") 23 { 24 _collection = client.getDatabase(database)[collection]; 25 } 26 27 /// 28 this(MongoDatabase database, string collection = "sessions_") 29 { 30 _collection = database[collection]; 31 } 32 33 /// 34 this(MongoCollection collection) 35 { 36 _collection = collection; 37 } 38 39 @property SessionStorageType storageType() const { return SessionStorageType.bson; } 40 41 Session create() 42 { 43 auto s = createSessionInstance(); 44 _collection.update(["id": s.id], Bson(["session": Bson(null)]), UpdateFlags.Upsert); 45 return s; 46 } 47 48 Session open(string id) 49 { 50 return _collection.findOne(["id": id]).isNull ? Session.init : createSessionInstance(id); 51 } 52 53 void set(string id, string key, Variant value) 54 { 55 _collection.update(["id": id], Bson(["$set": Bson(["session." ~ key: value.get!Bson])]), UpdateFlags.Upsert); 56 } 57 58 Variant get(string id, string key, lazy Variant defaultVal) 59 { 60 auto v = _collection.findOne(["id": id])["session"].tryIndex(key); 61 return v.isNull ? defaultVal : Variant(v.get); 62 } 63 64 bool isKeySet(string id, string key) 65 { 66 return !_collection.findOne(Bson(["id": Bson(id), "session." ~ key: Bson(["$exists": Bson(true)])])).isNull; 67 } 68 69 void destroy(string id) 70 { 71 _collection.remove(["id": id]); 72 } 73 74 int iterateSession(string id, scope int delegate(string key) del) 75 { 76 auto v = _collection.findOne(["id": id]); 77 foreach(string key, _; v["session"]) 78 if (auto ret = del(key)) 79 return ret; 80 return 0; 81 } 82 83 private: 84 MongoCollection _collection; 85 }