user_manager.h 15 KB

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