#include "pg_session_repo.hpp" #include #include #include #include #include namespace { std::string random_token_hex() { unsigned char buf[32]; randombytes_buf(buf, sizeof(buf)); static const char hex[] = "0123456789abcdef"; std::string out; out.resize(sizeof(buf) * 2); for (std::size_t i = 0; i < sizeof(buf); ++i) { out[i * 2] = hex[buf[i] >> 4]; out[i * 2 + 1] = hex[buf[i] & 0x0f]; } return out; } std::int64_t now_unix() { return static_cast(std::time(nullptr)); } } ISessionRepo::Created PgSessionRepo::create(const std::string& user_id) { const std::string token = random_token_hex(); const std::int64_t exp = now_unix() + ttl_; auto lease = pool_.acquire(); pqxx::work tx(*lease); tx.exec( "INSERT INTO sessions (token, user_id, expires_at) " "VALUES ($1, $2, to_timestamp($3::bigint))", pqxx::params{token, user_id, exp}); tx.commit(); return Created{token, exp}; } std::optional PgSessionRepo::lookup(const std::string& token) { auto lease = pool_.acquire(); pqxx::work tx(*lease); auto r = tx.exec( "SELECT user_id FROM sessions " "WHERE token = $1 AND expires_at > now()", pqxx::params{token}); tx.commit(); if (r.empty()) return std::nullopt; return r[0]["user_id"].as(); } bool PgSessionRepo::revoke(const std::string& token) { auto lease = pool_.acquire(); pqxx::work tx(*lease); auto r = tx.exec( "DELETE FROM sessions WHERE token = $1", pqxx::params{token}); tx.commit(); return r.affected_rows() > 0; }