auth_middleware.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. #ifndef AUTH_MIDDLEWARE_H
  2. #define AUTH_MIDDLEWARE_H
  3. #include <string>
  4. #include <vector>
  5. #include <functional>
  6. #include <memory>
  7. #include "jwt_auth.h"
  8. #include "user_manager.h"
  9. #include "server_config.h"
  10. namespace httplib {
  11. class Request;
  12. class Response;
  13. }
  14. /**
  15. * @brief Authentication context structure
  16. */
  17. struct AuthContext {
  18. bool authenticated; ///< Authentication status
  19. std::string userId; ///< User ID
  20. std::string username; ///< Username
  21. std::string role; ///< User role
  22. std::vector<std::string> permissions; ///< User permissions
  23. std::string authMethod; ///< Authentication method used
  24. std::string errorMessage; ///< Error message if authentication failed
  25. std::string errorCode; ///< Error code for API responses
  26. };
  27. /**
  28. * @brief Authentication middleware class
  29. *
  30. * This class provides authentication and authorization middleware for HTTP requests.
  31. * It supports multiple authentication methods (JWT, API keys, Unix auth) and
  32. * role-based access control.
  33. */
  34. class AuthMiddleware {
  35. public:
  36. /**
  37. * @brief Authentication handler function type
  38. *
  39. * @param req HTTP request
  40. * @param res HTTP response
  41. * @param context Authentication context
  42. */
  43. using AuthHandler = std::function<void(const httplib::Request& req,
  44. httplib::Response& res,
  45. const AuthContext& context)>;
  46. /**
  47. * @brief Construct a new Auth Middleware object
  48. *
  49. * @param config Authentication configuration
  50. * @param userManager User manager instance
  51. */
  52. explicit AuthMiddleware(const AuthConfig& config,
  53. std::shared_ptr<UserManager> userManager);
  54. /**
  55. * @brief Destroy the Auth Middleware object
  56. */
  57. ~AuthMiddleware();
  58. /**
  59. * @brief Initialize the authentication middleware
  60. *
  61. * @return true if initialization successful, false otherwise
  62. */
  63. bool initialize();
  64. /**
  65. * @brief Authenticate HTTP request
  66. *
  67. * @param req HTTP request
  68. * @param res HTTP response
  69. * @return AuthContext Authentication context
  70. */
  71. AuthContext authenticate(const httplib::Request& req, httplib::Response& res);
  72. /**
  73. * @brief Check if path requires authentication
  74. *
  75. * @param path Request path
  76. * @return true if authentication required, false otherwise
  77. */
  78. bool requiresAuthentication(const std::string& path) const;
  79. /**
  80. * @brief Check if path requires admin access
  81. *
  82. * @param path Request path
  83. * @return true if admin access required, false otherwise
  84. */
  85. bool requiresAdminAccess(const std::string& path) const;
  86. /**
  87. * @brief Check if path requires user access (any authenticated user)
  88. *
  89. * @param path Request path
  90. * @return true if user access required, false otherwise
  91. */
  92. bool requiresUserAccess(const std::string& path) const;
  93. /**
  94. * @brief Check if user has permission for path
  95. *
  96. * @param path Request path
  97. * @param permissions User permissions
  98. * @return true if user has access, false otherwise
  99. */
  100. bool hasPathAccess(const std::string& path,
  101. const std::vector<std::string>& permissions) const;
  102. /**
  103. * @brief Create authentication middleware handler
  104. *
  105. * @param handler Next handler in chain
  106. * @return AuthHandler Middleware handler function
  107. */
  108. AuthHandler createMiddleware(AuthHandler handler);
  109. /**
  110. * @brief Send authentication error response
  111. *
  112. * @param res HTTP response
  113. * @param message Error message
  114. * @param errorCode Error code
  115. * @param statusCode HTTP status code
  116. */
  117. void sendAuthError(httplib::Response& res,
  118. const std::string& message,
  119. const std::string& errorCode = "AUTH_ERROR",
  120. int statusCode = 401);
  121. /**
  122. * @brief Send authorization error response
  123. *
  124. * @param res HTTP response
  125. * @param message Error message
  126. * @param errorCode Error code
  127. */
  128. void sendAuthzError(httplib::Response& res,
  129. const std::string& message,
  130. const std::string& errorCode = "ACCESS_DENIED");
  131. /**
  132. * @brief Add public path (no authentication required)
  133. *
  134. * @param path Path to add
  135. */
  136. void addPublicPath(const std::string& path);
  137. /**
  138. * @brief Add admin-only path
  139. *
  140. * @param path Path to add
  141. */
  142. void addAdminPath(const std::string& path);
  143. /**
  144. * @brief Add user-only path
  145. *
  146. * @param path Path to add
  147. */
  148. void addUserPath(const std::string& path);
  149. /**
  150. * @brief Set JWT secret
  151. *
  152. * @param secret JWT secret key
  153. */
  154. void setJwtSecret(const std::string& secret);
  155. /**
  156. * @brief Get JWT secret
  157. *
  158. * @return std::string JWT secret key
  159. */
  160. std::string getJwtSecret() const;
  161. /**
  162. * @brief Set authentication method
  163. *
  164. * @param method Authentication method
  165. */
  166. void setAuthMethod(UserManager::AuthMethod method);
  167. /**
  168. * @brief Get authentication method
  169. *
  170. * @return UserManager::AuthMethod Current authentication method
  171. */
  172. UserManager::AuthMethod getAuthMethod() const;
  173. /**
  174. * @brief Enable or disable guest access
  175. *
  176. * @param enable Enable guest access
  177. */
  178. void setGuestAccessEnabled(bool enable);
  179. /**
  180. * @brief Check if guest access is enabled
  181. *
  182. * @return true if guest access enabled, false otherwise
  183. */
  184. bool isGuestAccessEnabled() const;
  185. /**
  186. * @brief Get authentication configuration
  187. *
  188. * @return AuthConfig Current configuration
  189. */
  190. AuthConfig getConfig() const;
  191. /**
  192. * @brief Update authentication configuration
  193. *
  194. * @param config New configuration
  195. */
  196. void updateConfig(const AuthConfig& config);
  197. private:
  198. AuthConfig m_config; ///< Authentication configuration
  199. std::shared_ptr<UserManager> m_userManager; ///< User manager instance
  200. std::unique_ptr<JWTAuth> m_jwtAuth; ///< JWT authentication instance
  201. /**
  202. * @brief Authenticate using JWT token
  203. *
  204. * @param req HTTP request
  205. * @return AuthContext Authentication context
  206. */
  207. AuthContext authenticateJwt(const httplib::Request& req);
  208. /**
  209. * @brief Authenticate using API key
  210. *
  211. * @param req HTTP request
  212. * @return AuthContext Authentication context
  213. */
  214. AuthContext authenticateApiKey(const httplib::Request& req);
  215. /**
  216. * @brief Authenticate using Unix system
  217. *
  218. * @param req HTTP request
  219. * @return AuthContext Authentication context
  220. */
  221. AuthContext authenticateUnix(const httplib::Request& req);
  222. /**
  223. * @brief Extract token from request
  224. *
  225. * @param req HTTP request
  226. * @param headerName Header name to check
  227. * @return std::string Token string, empty if not found
  228. */
  229. std::string extractToken(const httplib::Request& req, const std::string& headerName) const;
  230. /**
  231. * @brief Create guest authentication context
  232. *
  233. * @return AuthContext Guest context
  234. */
  235. AuthContext createGuestContext() const;
  236. /**
  237. * @brief Check if path matches pattern
  238. *
  239. * @param path Request path
  240. * @param patterns List of patterns to match
  241. * @return true if path matches any pattern, false otherwise
  242. */
  243. static bool pathMatchesPattern(const std::string& path,
  244. const std::vector<std::string>& patterns);
  245. /**
  246. * @brief Get required permissions for path
  247. *
  248. * @param path Request path
  249. * @return std::vector<std::string> Required permissions
  250. */
  251. std::vector<std::string> getRequiredPermissions(const std::string& path) const;
  252. /**
  253. * @brief Log authentication attempt
  254. *
  255. * @param req HTTP request
  256. * @param context Authentication context
  257. * @param success Authentication success
  258. */
  259. void logAuthAttempt(const httplib::Request& req,
  260. const AuthContext& context,
  261. bool success) const;
  262. /**
  263. * @brief Get client IP address from request
  264. *
  265. * @param req HTTP request
  266. * @return std::string Client IP address
  267. */
  268. static std::string getClientIp(const httplib::Request& req);
  269. /**
  270. * @brief Get user agent from request
  271. *
  272. * @param req HTTP request
  273. * @return std::string User agent string
  274. */
  275. static std::string getUserAgent(const httplib::Request& req);
  276. /**
  277. * @brief Validate authentication configuration
  278. *
  279. * @param config Configuration to validate
  280. * @return true if valid, false otherwise
  281. */
  282. static bool validateConfig(const AuthConfig& config);
  283. /**
  284. * @brief Initialize default paths
  285. */
  286. void initializeDefaultPaths();
  287. /**
  288. * @brief Check if authentication is completely disabled
  289. *
  290. * @return true if authentication disabled, false otherwise
  291. */
  292. bool isAuthenticationDisabled() const;
  293. };
  294. /**
  295. * @brief Authentication middleware factory functions
  296. */
  297. namespace AuthMiddlewareFactory {
  298. /**
  299. * @brief Create authentication middleware with default configuration
  300. *
  301. * @param userManager User manager instance
  302. * @param dataDir Data directory for user storage
  303. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  304. */
  305. std::unique_ptr<AuthMiddleware> createDefault(std::shared_ptr<UserManager> userManager,
  306. const std::string& dataDir);
  307. /**
  308. * @brief Create authentication middleware with JWT only
  309. *
  310. * @param userManager User manager instance
  311. * @param jwtSecret JWT secret key
  312. * @param jwtExpirationMinutes JWT expiration in minutes
  313. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  314. */
  315. std::unique_ptr<AuthMiddleware> createJwtOnly(std::shared_ptr<UserManager> userManager,
  316. const std::string& jwtSecret,
  317. int jwtExpirationMinutes = 60);
  318. /**
  319. * @brief Create authentication middleware with API keys only
  320. *
  321. * @param userManager User manager instance
  322. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  323. */
  324. std::unique_ptr<AuthMiddleware> createApiKeyOnly(std::shared_ptr<UserManager> userManager);
  325. /**
  326. * @brief Create authentication middleware with multiple methods
  327. *
  328. * @param userManager User manager instance
  329. * @param config Authentication configuration
  330. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  331. */
  332. std::unique_ptr<AuthMiddleware> createMultiMethod(std::shared_ptr<UserManager> userManager,
  333. const AuthConfig& config);
  334. /**
  335. * @brief Create authentication middleware for development (no auth required)
  336. *
  337. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  338. */
  339. std::unique_ptr<AuthMiddleware> createDevelopment();
  340. };
  341. #endif // AUTH_MIDDLEWARE_H