1 module hunt.framework.http.session.SessionStorage; 2 3 import hunt.cache; 4 import hunt.framework.Exceptions; 5 import hunt.framework.util.Random; 6 import hunt.Exceptions; 7 8 import std.array; 9 import std.algorithm; 10 import std.ascii; 11 import std.json; 12 import std.conv; 13 import std.digest.sha; 14 import std.format; 15 import std.datetime; 16 import std.random; 17 import std.string; 18 import std.traits; 19 import std.variant; 20 21 import core.cpuid; 22 23 // import hunt.framework.http.session.HttpSession; 24 25 import hunt.http.server.HttpSession; 26 27 /** 28 * 29 */ 30 class SessionStorage { 31 this(Cache cache, string prefix="", int expire = 3600) { 32 _cache = cache; 33 _expire = expire; 34 _prefix = prefix; 35 } 36 37 alias set = put; 38 39 bool put(HttpSession session) { 40 int expire = session.getMaxInactiveInterval; 41 if(_expire < expire) 42 expire = _expire; 43 string key = session.getId(); 44 _cache.set(getRealAddr(key), HttpSession.toJson(session), _expire); 45 return true; 46 } 47 48 HttpSession get(string key) { 49 string keyWithPrefix = getRealAddr(key); 50 string s = cast(string) _cache.get!string(keyWithPrefix); 51 if(s.empty) { 52 // string sessionId = HttpSession.generateSessionId(); 53 // return HttpSession.create(sessionId, _sessionStorage.expire); 54 return null; 55 } else { 56 _cache.set(keyWithPrefix , s , _expire); 57 return HttpSession.fromJson(key, s); 58 } 59 } 60 61 // string _get(string key) { 62 // return cast(string) _cache.get!string(getRealAddr(key)); 63 // } 64 65 // alias isset = containsKey; 66 bool containsKey(string key) { 67 return _cache.hasKey(getRealAddr(key)); 68 } 69 70 // alias del = erase; 71 // alias remove = erase; 72 bool remove(string key) { 73 return _cache.remove(getRealAddr(key)); 74 } 75 76 static string generateSessionId(string sessionName = "hunt_session") { 77 SHA1 hash; 78 hash.start(); 79 hash.put(getRandom); 80 ubyte[20] result = hash.finish(); 81 string str = toLower(toHexString(result)); 82 83 // JSONValue json; 84 // json[sessionName] = str; 85 // json["_time"] = cast(int)(Clock.currTime.toUnixTime) + _expire; 86 87 // put(str, json.toString, _expire); 88 89 return str; 90 } 91 92 void setPrefix(string prefix) { 93 _prefix = prefix; 94 } 95 96 void expire(int expire) @property { 97 _expire = expire; 98 } 99 100 int expire() @property { 101 return _expire; 102 } 103 104 string getRealAddr(string key) { 105 return _prefix ~ key; 106 } 107 108 void clear() { 109 _cache.clear(); 110 } 111 112 private { 113 string _prefix; 114 string _sessionId; 115 116 int _expire; 117 Cache _cache; 118 } 119 } 120