user_manager.h 16 KB

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