auth_session.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #pragma once
  2. /*
  3. * auth_session.h - In-memory + SQLite dual-layer session management
  4. *
  5. * Sessions are cached in memory for fast lookup, with SQLite as backing store.
  6. * Idle timeout: 30 minutes (1800s)
  7. * Absolute timeout: 8 hours (28800s), or 7 days if "remember me"
  8. */
  9. #include "auth_db.h"
  10. #include <string>
  11. #include <unordered_map>
  12. #include <mutex>
  13. #include <ctime>
  14. namespace auth {
  15. class SessionManager {
  16. public:
  17. SessionManager();
  18. void init(AuthDB *db, int idle_timeout_sec = 1800,
  19. int absolute_timeout_sec = 28800,
  20. int remember_timeout_sec = 604800);
  21. /* Create a new session for a user. Returns session_id. */
  22. std::string create_session(int user_id, const std::string &username,
  23. const std::string &remote_ip, bool remember = false,
  24. int user_role = 0);
  25. /* Validate a session. Returns true if valid. Updates last_active. */
  26. bool validate_session(const std::string &session_id, Session &sess);
  27. /* Destroy a session (logout) */
  28. void destroy_session(const std::string &session_id);
  29. /* Destroy all sessions for a user */
  30. void destroy_user_sessions(int user_id);
  31. /* Get CSRF token for a session */
  32. std::string get_csrf_token(const std::string &session_id);
  33. /* Periodic cleanup of expired sessions */
  34. void cleanup();
  35. /* Get active session count */
  36. int active_count();
  37. private:
  38. AuthDB *db_ = nullptr;
  39. int idle_timeout_ = 1800;
  40. int absolute_timeout_ = 28800;
  41. int remember_timeout_ = 604800;
  42. /* In-memory cache: session_id -> Session */
  43. std::unordered_map<std::string, Session> cache_;
  44. std::mutex cache_mutex_;
  45. bool is_expired(const Session &sess, time_t now);
  46. };
  47. } // namespace auth