auth.hpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #pragma once
  2. #include <chrono>
  3. #include <mutex>
  4. #include <optional>
  5. #include <string>
  6. #include <unordered_map>
  7. namespace svapi {
  8. /// Extract the token from an Authorization: Bearer <token> header.
  9. std::optional<std::string> bearerToken(const std::string& authHeader);
  10. /// Extract the value of a named cookie from a Cookie: header string.
  11. std::optional<std::string> cookieValue(const std::string& cookieHeader, const std::string& name);
  12. /// Generate a 32-character hex token (16 random bytes via OpenSSL RAND_bytes).
  13. std::string randomToken();
  14. /// In-memory session store: token → (apiKeyValue, expiry).
  15. class SessionStore {
  16. public:
  17. explicit SessionStore(std::chrono::minutes ttl);
  18. /// Create a new session for the given API key value, returns the token.
  19. std::string create(const std::string& apiKeyValue, std::chrono::system_clock::time_point now);
  20. /// Return the API key value for the token, or nullopt if missing/expired.
  21. std::optional<std::string> keyFor(const std::string& token, std::chrono::system_clock::time_point now);
  22. /// Remove/invalidate a session token.
  23. void remove(const std::string& token);
  24. /// Update the TTL for future sessions.
  25. void setTtl(std::chrono::minutes ttl);
  26. private:
  27. struct Entry {
  28. std::string key;
  29. std::chrono::system_clock::time_point expiry;
  30. };
  31. std::unordered_map<std::string, Entry> sessions_;
  32. std::chrono::minutes ttl_;
  33. std::mutex m_;
  34. };
  35. } // namespace svapi