auth_middleware.h 11 KB

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