session.d 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // session with multisession --
  2. // we have same user_id - but few cookies (devices or people on same account etc)
  3. // sessions store:
  4. // postgresql = cookie -- user_id
  5. // memcached = cookie -- user_id ; user_id + key_part -- some_cached_values // todo think maybe store only - user_id + key_part -- used_id_cookies_list_csv_str
  6. import std.stdio : writeln;
  7. import std.array;
  8. import std.string;
  9. private{
  10. import std.digest.sha;
  11. import std.random : uniform;
  12. import std.base64 : Base64;
  13. import std.datetime : SysTime, Clock, dur;
  14. import std.algorithm;
  15. import std.typecons : Tuple, Nullable;
  16. }
  17. ubyte[][string] userSessions;
  18. //userSessions["user123"] = 42;
  19. //if("user123" in userSessions){
  20. // int value = userSessions["user123"];
  21. //}
  22. //userSessions.remove("user123");
  23. //userSessions.remove("user123", null);
  24. ubyte idLength = 15; // we got 20 chars here // session ID length in Base64 like YouTube videos id
  25. ubyte validityDays = 255; // max value for ubyte too enaught // session validity in days
  26. string generateCookie(){ // Cookie as SessionId
  27. ubyte[16] randomBytes;
  28. foreach(ref b; randomBytes){
  29. b = cast(ubyte)uniform(0, 256);
  30. }
  31. auto hash = sha256Of(randomBytes);
  32. ubyte[15] idBytes = hash[0..15].dup; // get 15 bytes - (120 bits) for 15-symbols Base64 // but got up to 20 symbols
  33. // Base64 - URL-safe coding
  34. auto base64 = Base64.encode(idBytes)
  35. .tr("+/", "-_") // replace +/ to -_
  36. .stripRight("="); // rm padding
  37. return base64.idup; // convert char[] into string
  38. }