user_manager.h 16 KB

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