auth_service.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #include "smartbotic/webserver/auth_service.hpp"
  2. #include <jwt-cpp/traits/nlohmann-json/traits.h>
  3. #include <sodium.h>
  4. #include <spdlog/spdlog.h>
  5. #include <chrono>
  6. #include <random>
  7. namespace smartbotic::webserver {
  8. namespace {
  9. auto GenerateUuid() -> std::string {
  10. static std::random_device rd;
  11. static std::mt19937 gen(rd());
  12. static std::uniform_int_distribution<> dis(0, 15);
  13. static const char* hex_chars = "0123456789abcdef";
  14. std::string uuid;
  15. uuid.reserve(36);
  16. for (int i = 0; i < 36; ++i) {
  17. if (i == 8 || i == 13 || i == 18 || i == 23) {
  18. uuid += '-';
  19. } else {
  20. uuid += hex_chars[dis(gen)];
  21. }
  22. }
  23. return uuid;
  24. }
  25. } // namespace
  26. AuthService::AuthService(const JwtConfig& config) : config_(config) {
  27. // Initialize libsodium if not already done
  28. if (sodium_init() < 0) {
  29. spdlog::warn("libsodium initialization failed or already initialized");
  30. }
  31. }
  32. AuthService::~AuthService() = default;
  33. AuthService::AuthService(AuthService&&) noexcept = default;
  34. auto AuthService::operator=(AuthService&&) noexcept -> AuthService& = default;
  35. auto AuthService::GenerateTokens(const std::string& user_id, const std::string& email,
  36. const std::vector<std::string>& workspace_ids,
  37. const std::vector<std::string>& groups) -> TokenPair {
  38. using traits = jwt::traits::nlohmann_json;
  39. auto now = std::chrono::system_clock::now();
  40. auto access_exp = now + std::chrono::seconds(config_.access_token_expiry);
  41. auto refresh_exp = now + std::chrono::seconds(config_.refresh_token_expiry);
  42. std::string access_jti = GenerateJti();
  43. std::string refresh_jti = GenerateJti();
  44. // Build workspace_ids and groups arrays for JWT
  45. nlohmann::json ws_json = workspace_ids;
  46. nlohmann::json groups_json = groups;
  47. // Create access token
  48. auto access_token = jwt::create<traits>()
  49. .set_issuer(config_.issuer)
  50. .set_subject(user_id)
  51. .set_type("JWT")
  52. .set_id(access_jti)
  53. .set_issued_at(now)
  54. .set_expires_at(access_exp)
  55. .set_payload_claim("email", jwt::basic_claim<traits>(email))
  56. .set_payload_claim("workspace_ids", jwt::basic_claim<traits>(ws_json))
  57. .set_payload_claim("groups", jwt::basic_claim<traits>(groups_json))
  58. .set_payload_claim("token_type", jwt::basic_claim<traits>(std::string("access")))
  59. .sign(jwt::algorithm::hs256{config_.secret});
  60. // Create refresh token (contains user info for renewal)
  61. auto refresh_token = jwt::create<traits>()
  62. .set_issuer(config_.issuer)
  63. .set_subject(user_id)
  64. .set_type("JWT")
  65. .set_id(refresh_jti)
  66. .set_issued_at(now)
  67. .set_expires_at(refresh_exp)
  68. .set_payload_claim("email", jwt::basic_claim<traits>(email))
  69. .set_payload_claim("workspace_ids", jwt::basic_claim<traits>(ws_json))
  70. .set_payload_claim("groups", jwt::basic_claim<traits>(groups_json))
  71. .set_payload_claim("token_type", jwt::basic_claim<traits>(std::string("refresh")))
  72. .sign(jwt::algorithm::hs256{config_.secret});
  73. spdlog::debug("Generated token pair for user {} (access_jti: {}, refresh_jti: {})",
  74. user_id, access_jti, refresh_jti);
  75. return TokenPair{
  76. .access_token = access_token,
  77. .refresh_token = refresh_token,
  78. .access_expires_in = config_.access_token_expiry,
  79. .refresh_expires_in = config_.refresh_token_expiry};
  80. }
  81. auto AuthService::ValidateAccessToken(const std::string& token) -> TokenValidation {
  82. using traits = jwt::traits::nlohmann_json;
  83. try {
  84. auto decoded = jwt::decode<traits>(token);
  85. // Create verifier
  86. auto verifier = jwt::verify<traits>()
  87. .allow_algorithm(jwt::algorithm::hs256{config_.secret})
  88. .with_issuer(config_.issuer);
  89. // Verify token
  90. verifier.verify(decoded);
  91. // Check token type
  92. auto token_type = decoded.get_payload_claim("token_type").as_string();
  93. if (token_type != "access") {
  94. return TokenValidation{.valid = false, .error = "Not an access token", .user = std::nullopt};
  95. }
  96. // Check if token is invalidated
  97. auto jti = decoded.get_id();
  98. if (IsTokenInvalidated(jti)) {
  99. return TokenValidation{.valid = false, .error = "Token has been invalidated", .user = std::nullopt};
  100. }
  101. // Extract user info
  102. AuthUser user;
  103. user.user_id = decoded.get_subject();
  104. user.email = decoded.get_payload_claim("email").as_string();
  105. auto ws_claim = decoded.get_payload_claim("workspace_ids").to_json();
  106. if (ws_claim.is_array()) {
  107. for (const auto& ws : ws_claim) {
  108. user.workspace_ids.push_back(ws.get<std::string>());
  109. }
  110. }
  111. auto groups_claim = decoded.get_payload_claim("groups").to_json();
  112. if (groups_claim.is_array()) {
  113. for (const auto& g : groups_claim) {
  114. user.groups.push_back(g.get<std::string>());
  115. }
  116. }
  117. return TokenValidation{.valid = true, .error = "", .user = user};
  118. } catch (const jwt::error::token_verification_exception& e) {
  119. spdlog::debug("Token verification failed: {}", e.what());
  120. return TokenValidation{.valid = false, .error = e.what(), .user = std::nullopt};
  121. } catch (const std::exception& e) {
  122. spdlog::debug("Token parsing failed: {}", e.what());
  123. return TokenValidation{.valid = false, .error = "Invalid token format", .user = std::nullopt};
  124. }
  125. }
  126. auto AuthService::ValidateRefreshToken(const std::string& token) -> TokenValidation {
  127. using traits = jwt::traits::nlohmann_json;
  128. try {
  129. auto decoded = jwt::decode<traits>(token);
  130. // Create verifier
  131. auto verifier = jwt::verify<traits>()
  132. .allow_algorithm(jwt::algorithm::hs256{config_.secret})
  133. .with_issuer(config_.issuer);
  134. // Verify token
  135. verifier.verify(decoded);
  136. // Check token type
  137. auto token_type = decoded.get_payload_claim("token_type").as_string();
  138. if (token_type != "refresh") {
  139. return TokenValidation{.valid = false, .error = "Not a refresh token", .user = std::nullopt};
  140. }
  141. // Check if token is invalidated
  142. auto jti = decoded.get_id();
  143. if (IsTokenInvalidated(jti)) {
  144. return TokenValidation{.valid = false, .error = "Token has been invalidated", .user = std::nullopt};
  145. }
  146. // Extract user info
  147. AuthUser user;
  148. user.user_id = decoded.get_subject();
  149. user.email = decoded.get_payload_claim("email").as_string();
  150. auto ws_claim = decoded.get_payload_claim("workspace_ids").to_json();
  151. if (ws_claim.is_array()) {
  152. for (const auto& ws : ws_claim) {
  153. user.workspace_ids.push_back(ws.get<std::string>());
  154. }
  155. }
  156. auto groups_claim = decoded.get_payload_claim("groups").to_json();
  157. if (groups_claim.is_array()) {
  158. for (const auto& g : groups_claim) {
  159. user.groups.push_back(g.get<std::string>());
  160. }
  161. }
  162. return TokenValidation{.valid = true, .error = "", .user = user};
  163. } catch (const jwt::error::token_verification_exception& e) {
  164. spdlog::debug("Refresh token verification failed: {}", e.what());
  165. return TokenValidation{.valid = false, .error = e.what(), .user = std::nullopt};
  166. } catch (const std::exception& e) {
  167. spdlog::debug("Refresh token parsing failed: {}", e.what());
  168. return TokenValidation{.valid = false, .error = "Invalid token format", .user = std::nullopt};
  169. }
  170. }
  171. auto AuthService::RefreshAccessToken(const std::string& refresh_token) -> std::optional<TokenPair> {
  172. using traits = jwt::traits::nlohmann_json;
  173. auto validation = ValidateRefreshToken(refresh_token);
  174. if (!validation.valid || !validation.user) {
  175. spdlog::debug("Refresh token validation failed: {}", validation.error);
  176. return std::nullopt;
  177. }
  178. const auto& user = *validation.user;
  179. // Invalidate the old refresh token (token rotation)
  180. try {
  181. auto decoded = jwt::decode<traits>(refresh_token);
  182. invalidated_tokens_.insert(decoded.get_id());
  183. } catch (...) {
  184. // Ignore decoding errors here since we already validated
  185. }
  186. // Generate new token pair
  187. return GenerateTokens(user.user_id, user.email, user.workspace_ids, user.groups);
  188. }
  189. auto AuthService::InvalidateRefreshToken(const std::string& refresh_token) -> bool {
  190. using traits = jwt::traits::nlohmann_json;
  191. try {
  192. auto decoded = jwt::decode<traits>(refresh_token);
  193. auto jti = decoded.get_id();
  194. invalidated_tokens_.insert(jti);
  195. spdlog::debug("Invalidated refresh token: {}", jti);
  196. return true;
  197. } catch (const std::exception& e) {
  198. spdlog::debug("Failed to invalidate token: {}", e.what());
  199. return false;
  200. }
  201. }
  202. auto AuthService::IsTokenInvalidated(const std::string& jti) const -> bool {
  203. return invalidated_tokens_.contains(jti);
  204. }
  205. auto AuthService::ExtractBearerToken(const std::string& auth_header) -> std::optional<std::string> {
  206. const std::string prefix = "Bearer ";
  207. if (auth_header.size() <= prefix.size()) {
  208. return std::nullopt;
  209. }
  210. if (auth_header.substr(0, prefix.size()) != prefix) {
  211. return std::nullopt;
  212. }
  213. return auth_header.substr(prefix.size());
  214. }
  215. auto AuthService::HashPassword(const std::string& password) -> std::string {
  216. // Ensure libsodium is initialized
  217. if (sodium_init() < 0) {
  218. throw std::runtime_error("Failed to initialize libsodium");
  219. }
  220. char hash[crypto_pwhash_STRBYTES];
  221. if (crypto_pwhash_str(hash, password.c_str(), password.length(),
  222. crypto_pwhash_OPSLIMIT_INTERACTIVE,
  223. crypto_pwhash_MEMLIMIT_INTERACTIVE) != 0) {
  224. throw std::runtime_error("Password hashing failed (out of memory)");
  225. }
  226. return std::string(hash);
  227. }
  228. auto AuthService::VerifyPassword(const std::string& password, const std::string& hash) -> bool {
  229. // Ensure libsodium is initialized
  230. if (sodium_init() < 0) {
  231. return false;
  232. }
  233. return crypto_pwhash_str_verify(hash.c_str(), password.c_str(), password.length()) == 0;
  234. }
  235. auto AuthService::GenerateJti() -> std::string {
  236. return GenerateUuid();
  237. }
  238. } // namespace smartbotic::webserver