auth.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "auth.hpp"
  2. #include <openssl/rand.h>
  3. #include <array>
  4. #include <stdexcept>
  5. namespace svapi {
  6. std::optional<std::string> bearerToken(const std::string& h) {
  7. constexpr const char* P = "Bearer "; constexpr size_t L = 7;
  8. if (h.size() <= L || h.compare(0, L, P) != 0) return std::nullopt;
  9. return h.substr(L);
  10. }
  11. std::optional<std::string> cookieValue(const std::string& header, const std::string& name) {
  12. size_t pos = 0;
  13. while (pos < header.size()) {
  14. size_t semi = header.find(';', pos);
  15. std::string pair = header.substr(pos, semi == std::string::npos ? std::string::npos : semi - pos);
  16. size_t s = pair.find_first_not_of(" \t"); if (s != std::string::npos) pair = pair.substr(s);
  17. size_t eq = pair.find('=');
  18. if (eq != std::string::npos && pair.substr(0, eq) == name) return pair.substr(eq + 1);
  19. if (semi == std::string::npos) break;
  20. pos = semi + 1;
  21. }
  22. return std::nullopt;
  23. }
  24. std::string randomToken() {
  25. std::array<unsigned char, 16> buf{};
  26. if (RAND_bytes(buf.data(), (int)buf.size()) != 1) throw std::runtime_error("RAND_bytes failed");
  27. static const char* hex = "0123456789abcdef"; std::string o; o.reserve(32);
  28. for (unsigned char b : buf) { o.push_back(hex[b >> 4]); o.push_back(hex[b & 0xF]); }
  29. return o;
  30. }
  31. SessionStore::SessionStore(std::chrono::minutes ttl) : ttl_(ttl) {}
  32. std::string SessionStore::create(const std::string& apiKeyValue, std::chrono::system_clock::time_point now) {
  33. std::string tok = randomToken();
  34. std::lock_guard<std::mutex> lk(m_);
  35. sessions_[tok] = Entry{apiKeyValue, now + ttl_};
  36. return tok;
  37. }
  38. std::optional<std::string> SessionStore::keyFor(const std::string& token, std::chrono::system_clock::time_point now) {
  39. std::lock_guard<std::mutex> lk(m_);
  40. auto it = sessions_.find(token);
  41. if (it == sessions_.end()) return std::nullopt;
  42. if (now >= it->second.expiry) { sessions_.erase(it); return std::nullopt; }
  43. return it->second.key;
  44. }
  45. void SessionStore::remove(const std::string& token) { std::lock_guard<std::mutex> lk(m_); sessions_.erase(token); }
  46. void SessionStore::setTtl(std::chrono::minutes ttl) { std::lock_guard<std::mutex> lk(m_); ttl_ = ttl; }
  47. } // namespace svapi