user_manager.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. #ifndef USER_MANAGER_H
  2. #define USER_MANAGER_H
  3. #include <string>
  4. #include <vector>
  5. #include <map>
  6. #include <memory>
  7. #include <mutex>
  8. #include <functional>
  9. #ifdef ENABLE_PAM_AUTH
  10. #include "pam_auth.h"
  11. #endif
  12. /**
  13. * @brief User information structure
  14. */
  15. struct UserInfo {
  16. std::string id; ///< Unique user ID
  17. std::string username; ///< Username (unique)
  18. std::string email; ///< Email address
  19. std::string passwordHash; ///< Hashed password
  20. std::string role; ///< User role (admin, user, etc.)
  21. std::vector<std::string> permissions; ///< User permissions
  22. std::vector<std::string> apiKeys; ///< User's API keys
  23. bool active; ///< Account active status
  24. int64_t createdAt; ///< Account creation timestamp
  25. int64_t lastLoginAt; ///< Last login timestamp
  26. int64_t passwordChangedAt; ///< Password change timestamp
  27. std::string createdBy; ///< Who created this user
  28. };
  29. /**
  30. * @brief API key information structure
  31. */
  32. struct ApiKeyInfo {
  33. std::string keyId; ///< Unique key ID
  34. std::string keyHash; ///< Hashed API key
  35. std::string name; ///< Key name/description
  36. std::string userId; ///< Owner user ID
  37. std::vector<std::string> permissions; ///< Key permissions
  38. bool active; ///< Key active status
  39. int64_t createdAt; ///< Key creation timestamp
  40. int64_t lastUsedAt; ///< Last used timestamp
  41. int64_t expiresAt; ///< Key expiration timestamp (0 = no expiration)
  42. std::string createdBy; ///< Who created this key
  43. };
  44. /**
  45. * @brief Authentication result structure
  46. */
  47. struct AuthResult {
  48. bool success; ///< Authentication success
  49. std::string userId; ///< User ID if successful
  50. std::string username; ///< Username if successful
  51. std::string role; ///< User role if successful
  52. std::vector<std::string> permissions; ///< User permissions if successful
  53. std::string errorMessage; ///< Error message if failed
  54. std::string errorCode; ///< Error code for API responses
  55. };
  56. /**
  57. * @brief User management system
  58. *
  59. * This class provides user authentication, authorization, and management
  60. * functionality for the stable-diffusion.cpp-rest server. It supports
  61. * local user storage, API key management, and role-based access control.
  62. */
  63. class UserManager {
  64. public:
  65. /**
  66. * @brief Authentication methods enumeration
  67. */
  68. enum class AuthMethod {
  69. NONE, ///< No authentication required
  70. JWT, ///< JWT token authentication
  71. API_KEY, ///< API key authentication
  72. UNIX, ///< Unix system authentication
  73. PAM, ///< PAM authentication
  74. OPTIONAL ///< Authentication optional (guest access allowed)
  75. };
  76. /**
  77. * @brief User roles enumeration
  78. */
  79. enum class UserRole {
  80. GUEST, ///< Guest user (no authentication)
  81. USER, ///< Regular user
  82. ADMIN, ///< Administrator
  83. SERVICE ///< Service account
  84. };
  85. /**
  86. * @brief Standard permissions
  87. */
  88. struct Permissions {
  89. static const std::string READ; ///< Read access to models and status
  90. static const std::string GENERATE; ///< Generate images
  91. static const std::string QUEUE_MANAGE; ///< Manage generation queue
  92. static const std::string MODEL_MANAGE; ///< Load/unload models
  93. static const std::string USER_MANAGE; ///< Manage other users
  94. static const std::string ADMIN; ///< Full administrative access
  95. };
  96. /**
  97. * @brief Construct a new User Manager object
  98. *
  99. * @param dataDir Directory for storing user data
  100. * @param authMethod Primary authentication method
  101. * @param enableUnixAuth Enable Unix authentication
  102. */
  103. explicit UserManager(const std::string& dataDir,
  104. AuthMethod authMethod = AuthMethod::JWT);
  105. /**
  106. * @brief Destroy the User Manager object
  107. */
  108. ~UserManager();
  109. /**
  110. * @brief Initialize the user manager
  111. *
  112. * @return true if initialization successful, false otherwise
  113. */
  114. bool initialize();
  115. /**
  116. * @brief Shutdown the user manager
  117. */
  118. void shutdown();
  119. /**
  120. * @brief Authenticate user with username and password
  121. *
  122. * @param username Username
  123. * @param password Plain text password
  124. * @return AuthResult Authentication result
  125. */
  126. AuthResult authenticateUser(const std::string& username, const std::string& password);
  127. /**
  128. * @brief authenticate user with Unix system
  129. *
  130. * @param username Unix username
  131. * @param password Unix password (used when PAM is enabled)
  132. * @return AuthResult Authentication result
  133. */
  134. AuthResult authenticateUnix(const std::string& username, const std::string& password = "");
  135. /**
  136. * @brief authenticate user with PAM
  137. *
  138. * @param username Username
  139. * @param password Plain text password
  140. * @return AuthResult Authentication result
  141. */
  142. AuthResult authenticatePam(const std::string& username, const std::string& password);
  143. /**
  144. * @brief Authenticate with API key
  145. *
  146. * @param apiKey API key string
  147. * @return AuthResult Authentication result
  148. */
  149. AuthResult authenticateApiKey(const std::string& apiKey);
  150. /**
  151. * @brief Create a new user
  152. *
  153. * @param username Username
  154. * @param password Plain text password
  155. * @param email Email address
  156. * @param role User role
  157. * @param createdBy User ID of creator
  158. * @return std::pair<bool, std::string> Success flag and user ID or error message
  159. */
  160. std::pair<bool, std::string> createUser(const std::string& username,
  161. const std::string& password,
  162. const std::string& email,
  163. UserRole role = UserRole::USER,
  164. const std::string& createdBy = "system");
  165. /**
  166. * @brief Update user information
  167. *
  168. * @param userId User ID
  169. * @param updates Map of fields to update
  170. * @return std::pair<bool, std::string> Success flag and message
  171. */
  172. std::pair<bool, std::string> updateUser(const std::string& userId,
  173. const std::map<std::string, std::string>& updates);
  174. /**
  175. * @brief Delete a user
  176. *
  177. * @param userId User ID to delete
  178. * @param requestingUserId User ID making the request
  179. * @return std::pair<bool, std::string> Success flag and message
  180. */
  181. std::pair<bool, std::string> deleteUser(const std::string& userId,
  182. const std::string& requestingUserId);
  183. /**
  184. * @brief Change user password
  185. *
  186. * @param userId User ID
  187. * @param oldPassword Current password (can be empty for admin)
  188. * @param newPassword New password
  189. * @param requestingUserId User ID making the request
  190. * @return std::pair<bool, std::string> Success flag and message
  191. */
  192. std::pair<bool, std::string> changePassword(const std::string& userId,
  193. const std::string& oldPassword,
  194. const std::string& newPassword,
  195. const std::string& requestingUserId);
  196. /**
  197. * @brief Get user information
  198. *
  199. * @param userId User ID
  200. * @return UserInfo User information, empty if not found
  201. */
  202. UserInfo getUserInfo(const std::string& userId);
  203. /**
  204. * @brief Get user information by username
  205. *
  206. * @param username Username
  207. * @return UserInfo User information, empty if not found
  208. */
  209. UserInfo getUserInfoByUsername(const std::string& username);
  210. /**
  211. * @brief List all users
  212. *
  213. * @param requestingUserId User ID making the request
  214. * @return std::vector<UserInfo> List of users (limited for non-admins)
  215. */
  216. std::vector<UserInfo> listUsers(const std::string& requestingUserId);
  217. /**
  218. * @brief Create API key for user
  219. *
  220. * @param userId User ID
  221. * @param name Key name/description
  222. * @param permissions Key permissions
  223. * @param expiresAt Expiration timestamp (0 = no expiration)
  224. * @param createdBy User ID creating the key
  225. * @return std::pair<bool, std::string> Success flag and API key or error message
  226. */
  227. std::pair<bool, std::string> createApiKey(const std::string& userId,
  228. const std::string& name,
  229. const std::vector<std::string>& permissions,
  230. int64_t expiresAt = 0,
  231. const std::string& createdBy = "system");
  232. /**
  233. * @brief Revoke API key
  234. *
  235. * @param keyId API key ID
  236. * @param requestingUserId User ID making the request
  237. * @return std::pair<bool, std::string> Success flag and message
  238. */
  239. std::pair<bool, std::string> revokeApiKey(const std::string& keyId,
  240. const std::string& requestingUserId);
  241. /**
  242. * @brief List API keys for user
  243. *
  244. * @param userId User ID
  245. * @param requestingUserId User ID making the request
  246. * @return std::vector<ApiKeyInfo> List of API keys
  247. */
  248. std::vector<ApiKeyInfo> listApiKeys(const std::string& userId,
  249. const std::string& requestingUserId);
  250. /**
  251. * @brief Get API key information
  252. *
  253. * @param keyId API key ID
  254. * @param requestingUserId User ID making the request
  255. * @return ApiKeyInfo API key information, empty if not found
  256. */
  257. ApiKeyInfo getApiKeyInfo(const std::string& keyId,
  258. const std::string& requestingUserId);
  259. /**
  260. * @brief Update API key last used timestamp
  261. *
  262. * @param keyId API key ID
  263. */
  264. void updateApiKeyLastUsed(const std::string& keyId);
  265. /**
  266. * @brief Check if user has permission
  267. *
  268. * @param userId User ID
  269. * @param permission Permission to check
  270. * @return true if user has permission, false otherwise
  271. */
  272. bool hasPermission(const std::string& userId, const std::string& permission);
  273. /**
  274. * @brief Check if user has any of the specified permissions
  275. *
  276. * @param userId User ID
  277. * @param permissions List of permissions to check
  278. * @return true if user has any permission, false otherwise
  279. */
  280. bool hasAnyPermission(const std::string& userId,
  281. const std::vector<std::string>& permissions);
  282. /**
  283. * @brief Get user role as string
  284. *
  285. * @param role User role enum
  286. * @return std::string Role string
  287. */
  288. static std::string roleToString(UserRole role);
  289. /**
  290. * @brief Parse role from string
  291. *
  292. * @param roleStr Role string
  293. * @return UserRole Role enum
  294. */
  295. static UserRole stringToRole(const std::string& roleStr);
  296. /**
  297. * @brief Get default permissions for role
  298. *
  299. * @param role User role
  300. * @return std::vector<std::string> List of permissions
  301. */
  302. static std::vector<std::string> getDefaultPermissions(UserRole role);
  303. /**
  304. * @brief Set authentication method
  305. *
  306. * @param method Authentication method
  307. */
  308. void setAuthMethod(AuthMethod method);
  309. /**
  310. * @brief Get current authentication method
  311. *
  312. * @return AuthMethod Current authentication method
  313. */
  314. AuthMethod getAuthMethod() const;
  315. /**
  316. * @brief Enable or disable PAM authentication
  317. *
  318. * @param enable Enable PAM authentication
  319. */
  320. void setPamAuthEnabled(bool enable);
  321. /**
  322. * @brief Check if PAM authentication is enabled
  323. *
  324. * @return true if PAM authentication is enabled, false otherwise
  325. */
  326. bool isPamAuthEnabled() const;
  327. /**
  328. * @brief Get user statistics
  329. *
  330. * @return std::map<std::string, int> Statistics map
  331. */
  332. std::map<std::string, int> getStatistics();
  333. private:
  334. std::string m_dataDir; ///< Data directory
  335. AuthMethod m_authMethod; ///< Current auth method
  336. bool m_pamAuthEnabled; ///< PAM auth enabled flag
  337. std::map<std::string, UserInfo> m_users; ///< User storage (username -> UserInfo)
  338. std::map<std::string, ApiKeyInfo> m_apiKeys; ///< API key storage (keyId -> ApiKeyInfo)
  339. std::map<std::string, std::string> m_apiKeyMap; ///< API key hash -> keyId mapping
  340. mutable std::mutex m_mutex; ///< Thread safety mutex
  341. #ifdef ENABLE_PAM_AUTH
  342. std::unique_ptr<PamAuth> m_pamAuth; ///< PAM authentication instance
  343. #endif
  344. /**
  345. * @brief Hash password using bcrypt
  346. *
  347. * @param password Plain text password
  348. * @return std::string Hashed password
  349. */
  350. std::string hashPassword(const std::string& password);
  351. /**
  352. * @brief Verify password against hash
  353. *
  354. * @param password Plain text password
  355. * @param hash Password hash
  356. * @return true if password matches, false otherwise
  357. */
  358. bool verifyPassword(const std::string& password, const std::string& hash);
  359. /**
  360. * @brief Hash API key
  361. *
  362. * @param apiKey Plain text API key
  363. * @return std::string Hashed API key
  364. */
  365. std::string hashApiKey(const std::string& apiKey);
  366. /**
  367. * @brief Generate unique user ID
  368. *
  369. * @return std::string Unique user ID
  370. */
  371. std::string generateUserId();
  372. /**
  373. * @brief Generate unique API key ID
  374. *
  375. * @return std::string Unique API key ID
  376. */
  377. std::string generateKeyId();
  378. /**
  379. * @brief Save user data to file
  380. *
  381. * @return true if successful, false otherwise
  382. */
  383. bool saveUserData();
  384. /**
  385. * @brief Load user data from file
  386. *
  387. * @return true if successful, false otherwise
  388. */
  389. bool loadUserData();
  390. /**
  391. * @brief Save API key data to file
  392. *
  393. * @return true if successful, false otherwise
  394. */
  395. bool saveApiKeyData();
  396. /**
  397. * @brief Load API key data from file
  398. *
  399. * @return true if successful, false otherwise
  400. */
  401. bool loadApiKeyData();
  402. /**
  403. * @brief Get current timestamp
  404. *
  405. * @return int64_t Current timestamp
  406. */
  407. static int64_t getCurrentTimestamp();
  408. /**
  409. * @brief Validate username format
  410. *
  411. * @param username Username to validate
  412. * @return true if valid, false otherwise
  413. */
  414. static bool validateUsername(const std::string& username);
  415. /**
  416. * @brief Validate password strength
  417. *
  418. * @param password Password to validate
  419. * @return true if valid, false otherwise
  420. */
  421. static bool validatePassword(const std::string& password);
  422. /**
  423. * @brief Validate email format
  424. *
  425. * @param email Email to validate
  426. * @return true if valid, false otherwise
  427. */
  428. static bool validateEmail(const std::string& email);
  429. /**
  430. * @brief Check if user can manage target user
  431. *
  432. * @param requestingUserId User making request
  433. * @param targetUserId Target user
  434. * @return true if allowed, false otherwise
  435. */
  436. bool canManageUser(const std::string& requestingUserId, const std::string& targetUserId);
  437. };
  438. #endif // USER_MANAGER_H