user_manager.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. PAM, ///< PAM authentication
  70. SHARED_KEY ///< Shared key authentication
  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 defaultAdminUsername Default admin username
  98. * @param defaultAdminPassword Default admin password
  99. * @param defaultAdminEmail Default admin email
  100. */
  101. explicit UserManager(const std::string& dataDir,
  102. AuthMethod authMethod = AuthMethod::PAM,
  103. const std::string& defaultAdminUsername = "admin",
  104. const std::string& defaultAdminPassword = "admin123",
  105. const std::string& defaultAdminEmail = "admin@localhost");
  106. /**
  107. * @brief Destroy the User Manager object
  108. */
  109. ~UserManager();
  110. /**
  111. * @brief Initialize the user manager
  112. *
  113. * @return true if initialization successful, false otherwise
  114. */
  115. bool initialize();
  116. /**
  117. * @brief Shutdown the user manager
  118. */
  119. void shutdown();
  120. /**
  121. * @brief Authenticate user with username and password
  122. *
  123. * @param username Username
  124. * @param password Plain text password
  125. * @return AuthResult Authentication result
  126. */
  127. AuthResult authenticateUser(const std::string& username, const std::string& password);
  128. /**
  129. * @brief authenticate user with Unix system
  130. *
  131. * @param username Unix username
  132. * @param password Unix password (used when PAM is enabled)
  133. * @return AuthResult Authentication result
  134. */
  135. AuthResult authenticateUnix(const std::string& username, const std::string& password = "");
  136. /**
  137. * @brief authenticate user with PAM
  138. *
  139. * @param username Username
  140. * @param password Plain text password
  141. * @return AuthResult Authentication result
  142. */
  143. AuthResult authenticatePam(const std::string& username, const std::string& password);
  144. /**
  145. * @brief Authenticate with shared key
  146. *
  147. * @param sharedKey Shared key string
  148. * @return AuthResult Authentication result
  149. */
  150. AuthResult authenticateSharedKey(const std::string& sharedKey);
  151. /**
  152. * @brief Create a new user
  153. *
  154. * @param username Username
  155. * @param password Plain text password
  156. * @param email Email address
  157. * @param role User role
  158. * @param createdBy User ID of creator
  159. * @return std::pair<bool, std::string> Success flag and user ID or error message
  160. */
  161. std::pair<bool, std::string> createUser(const std::string& username,
  162. const std::string& password,
  163. const std::string& email,
  164. UserRole role = UserRole::USER,
  165. const std::string& createdBy = "system");
  166. /**
  167. * @brief Update user information
  168. *
  169. * @param userId User ID
  170. * @param updates Map of fields to update
  171. * @return std::pair<bool, std::string> Success flag and message
  172. */
  173. std::pair<bool, std::string> updateUser(const std::string& userId,
  174. const std::map<std::string, std::string>& updates);
  175. /**
  176. * @brief Delete a user
  177. *
  178. * @param userId User ID to delete
  179. * @param requestingUserId User ID making the request
  180. * @return std::pair<bool, std::string> Success flag and message
  181. */
  182. std::pair<bool, std::string> deleteUser(const std::string& userId,
  183. const std::string& requestingUserId);
  184. /**
  185. * @brief Change user password
  186. *
  187. * @param userId User ID
  188. * @param oldPassword Current password (can be empty for admin)
  189. * @param newPassword New password
  190. * @param requestingUserId User ID making the request
  191. * @return std::pair<bool, std::string> Success flag and message
  192. */
  193. std::pair<bool, std::string> changePassword(const std::string& userId,
  194. const std::string& oldPassword,
  195. const std::string& newPassword,
  196. const std::string& requestingUserId);
  197. /**
  198. * @brief Get user information
  199. *
  200. * @param userId User ID
  201. * @return UserInfo User information, empty if not found
  202. */
  203. UserInfo getUserInfo(const std::string& userId);
  204. /**
  205. * @brief Get user information by username
  206. *
  207. * @param username Username
  208. * @return UserInfo User information, empty if not found
  209. */
  210. UserInfo getUserInfoByUsername(const std::string& username);
  211. /**
  212. * @brief List all users
  213. *
  214. * @param requestingUserId User ID making the request
  215. * @return std::vector<UserInfo> List of users (limited for non-admins)
  216. */
  217. std::vector<UserInfo> listUsers(const std::string& requestingUserId);
  218. /**
  219. * @brief Create API key for user
  220. *
  221. * @param userId User ID
  222. * @param name Key name/description
  223. * @param permissions Key permissions
  224. * @param expiresAt Expiration timestamp (0 = no expiration)
  225. * @param createdBy User ID creating the key
  226. * @return std::pair<bool, std::string> Success flag and API key or error message
  227. */
  228. std::pair<bool, std::string> createApiKey(const std::string& userId,
  229. const std::string& name,
  230. const std::vector<std::string>& permissions,
  231. int64_t expiresAt = 0,
  232. const std::string& createdBy = "system");
  233. /**
  234. * @brief Revoke API key
  235. *
  236. * @param keyId API key ID
  237. * @param requestingUserId User ID making the request
  238. * @return std::pair<bool, std::string> Success flag and message
  239. */
  240. std::pair<bool, std::string> revokeApiKey(const std::string& keyId,
  241. const std::string& requestingUserId);
  242. /**
  243. * @brief List API keys for user
  244. *
  245. * @param userId User ID
  246. * @param requestingUserId User ID making the request
  247. * @return std::vector<ApiKeyInfo> List of API keys
  248. */
  249. std::vector<ApiKeyInfo> listApiKeys(const std::string& userId,
  250. const std::string& requestingUserId);
  251. /**
  252. * @brief Get API key information
  253. *
  254. * @param keyId API key ID
  255. * @param requestingUserId User ID making the request
  256. * @return ApiKeyInfo API key information, empty if not found
  257. */
  258. ApiKeyInfo getApiKeyInfo(const std::string& keyId,
  259. const std::string& requestingUserId);
  260. /**
  261. * @brief Update API key last used timestamp
  262. *
  263. * @param keyId API key ID
  264. */
  265. void updateApiKeyLastUsed(const std::string& keyId);
  266. /**
  267. * @brief Check if user has permission
  268. *
  269. * @param userId User ID
  270. * @param permission Permission to check
  271. * @return true if user has permission, false otherwise
  272. */
  273. bool hasPermission(const std::string& userId, const std::string& permission);
  274. /**
  275. * @brief Check if user has any of the specified permissions
  276. *
  277. * @param userId User ID
  278. * @param permissions List of permissions to check
  279. * @return true if user has any permission, false otherwise
  280. */
  281. bool hasAnyPermission(const std::string& userId,
  282. const std::vector<std::string>& permissions);
  283. /**
  284. * @brief Get user role as string
  285. *
  286. * @param role User role enum
  287. * @return std::string Role string
  288. */
  289. static std::string roleToString(UserRole role);
  290. /**
  291. * @brief Parse role from string
  292. *
  293. * @param roleStr Role string
  294. * @return UserRole Role enum
  295. */
  296. static UserRole stringToRole(const std::string& roleStr);
  297. /**
  298. * @brief Get default permissions for role
  299. *
  300. * @param role User role
  301. * @return std::vector<std::string> List of permissions
  302. */
  303. static std::vector<std::string> getDefaultPermissions(UserRole role);
  304. /**
  305. * @brief Set authentication method
  306. *
  307. * @param method Authentication method
  308. */
  309. void setAuthMethod(AuthMethod method);
  310. /**
  311. * @brief Get current authentication method
  312. *
  313. * @return AuthMethod Current authentication method
  314. */
  315. AuthMethod getAuthMethod() const;
  316. /**
  317. * @brief Enable or disable PAM authentication
  318. *
  319. * @param enable Enable PAM authentication
  320. */
  321. void setPamAuthEnabled(bool enable);
  322. /**
  323. * @brief Check if PAM authentication is enabled
  324. *
  325. * @return true if PAM authentication is enabled, false otherwise
  326. */
  327. bool isPamAuthEnabled() const;
  328. /**
  329. * @brief Get user statistics
  330. *
  331. * @return std::map<std::string, int> Statistics map
  332. */
  333. std::map<std::string, int> getStatistics();
  334. private:
  335. std::string m_dataDir; ///< Data directory
  336. AuthMethod m_authMethod; ///< Current auth method
  337. bool m_pamAuthEnabled; ///< PAM auth enabled flag
  338. std::string m_defaultAdminUsername; ///< Default admin username
  339. std::string m_defaultAdminPassword; ///< Default admin password
  340. std::string m_defaultAdminEmail; ///< Default admin email
  341. std::map<std::string, UserInfo> m_users; ///< User storage (username -> UserInfo)
  342. std::map<std::string, ApiKeyInfo> m_apiKeys; ///< API key storage (keyId -> ApiKeyInfo)
  343. std::map<std::string, std::string> m_apiKeyMap; ///< API key hash -> keyId mapping
  344. mutable std::mutex m_mutex; ///< Thread safety mutex
  345. #ifdef ENABLE_PAM_AUTH
  346. std::unique_ptr<PamAuth> m_pamAuth; ///< PAM authentication instance
  347. #endif
  348. /**
  349. * @brief Hash password using bcrypt
  350. *
  351. * @param password Plain text password
  352. * @return std::string Hashed password
  353. */
  354. std::string hashPassword(const std::string& password);
  355. /**
  356. * @brief Verify password against hash
  357. *
  358. * @param password Plain text password
  359. * @param hash Password hash
  360. * @return true if password matches, false otherwise
  361. */
  362. bool verifyPassword(const std::string& password, const std::string& hash);
  363. /**
  364. * @brief Hash API key
  365. *
  366. * @param apiKey Plain text API key
  367. * @return std::string Hashed API key
  368. */
  369. std::string hashApiKey(const std::string& apiKey);
  370. /**
  371. * @brief Generate unique user ID
  372. *
  373. * @return std::string Unique user ID
  374. */
  375. std::string generateUserId();
  376. /**
  377. * @brief Generate unique API key ID
  378. *
  379. * @return std::string Unique API key ID
  380. */
  381. std::string generateKeyId();
  382. /**
  383. * @brief Save user data to file
  384. *
  385. * @return true if successful, false otherwise
  386. */
  387. bool saveUserData();
  388. /**
  389. * @brief Load user data from file
  390. *
  391. * @return true if successful, false otherwise
  392. */
  393. bool loadUserData();
  394. /**
  395. * @brief Save API key data to file
  396. *
  397. * @return true if successful, false otherwise
  398. */
  399. bool saveApiKeyData();
  400. /**
  401. * @brief Load API key data from file
  402. *
  403. * @return true if successful, false otherwise
  404. */
  405. bool loadApiKeyData();
  406. /**
  407. * @brief Get current timestamp
  408. *
  409. * @return int64_t Current timestamp
  410. */
  411. static int64_t getCurrentTimestamp();
  412. /**
  413. * @brief Validate username format
  414. *
  415. * @param username Username to validate
  416. * @return true if valid, false otherwise
  417. */
  418. static bool validateUsername(const std::string& username);
  419. /**
  420. * @brief Validate password strength
  421. *
  422. * @param password Password to validate
  423. * @return true if valid, false otherwise
  424. */
  425. static bool validatePassword(const std::string& password);
  426. /**
  427. * @brief Validate email format
  428. *
  429. * @param email Email to validate
  430. * @return true if valid, false otherwise
  431. */
  432. static bool validateEmail(const std::string& email);
  433. /**
  434. * @brief Check if user can manage target user
  435. *
  436. * @param requestingUserId User making request
  437. * @param targetUserId Target user
  438. * @return true if allowed, false otherwise
  439. */
  440. bool canManageUser(const std::string& requestingUserId, const std::string& targetUserId);
  441. };
  442. #endif // USER_MANAGER_H