users.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import logging
  2. from typing import Optional
  3. import base64
  4. import io
  5. from fastapi import APIRouter, Depends, HTTPException, Request, status
  6. from fastapi.responses import Response, StreamingResponse, FileResponse
  7. from pydantic import BaseModel
  8. from open_webui.models.auths import Auths
  9. from open_webui.models.oauth_sessions import OAuthSessions
  10. from open_webui.models.groups import Groups
  11. from open_webui.models.chats import Chats
  12. from open_webui.models.users import (
  13. UserModel,
  14. UserListResponse,
  15. UserInfoListResponse,
  16. UserIdNameListResponse,
  17. UserRoleUpdateForm,
  18. Users,
  19. UserSettings,
  20. UserUpdateForm,
  21. )
  22. from open_webui.socket.main import (
  23. get_active_status_by_user_id,
  24. get_active_user_ids,
  25. get_user_active_status,
  26. )
  27. from open_webui.constants import ERROR_MESSAGES
  28. from open_webui.env import SRC_LOG_LEVELS, STATIC_DIR
  29. from open_webui.utils.auth import get_admin_user, get_password_hash, get_verified_user
  30. from open_webui.utils.access_control import get_permissions, has_permission
  31. log = logging.getLogger(__name__)
  32. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  33. router = APIRouter()
  34. ############################
  35. # GetActiveUsers
  36. ############################
  37. @router.get("/active")
  38. async def get_active_users(
  39. user=Depends(get_verified_user),
  40. ):
  41. """
  42. Get a list of active users.
  43. """
  44. return {
  45. "user_ids": get_active_user_ids(),
  46. }
  47. ############################
  48. # GetUsers
  49. ############################
  50. PAGE_ITEM_COUNT = 30
  51. @router.get("/", response_model=UserListResponse)
  52. async def get_users(
  53. query: Optional[str] = None,
  54. order_by: Optional[str] = None,
  55. direction: Optional[str] = None,
  56. page: Optional[int] = 1,
  57. user=Depends(get_admin_user),
  58. ):
  59. limit = PAGE_ITEM_COUNT
  60. page = max(1, page)
  61. skip = (page - 1) * limit
  62. filter = {}
  63. if query:
  64. filter["query"] = query
  65. if order_by:
  66. filter["order_by"] = order_by
  67. if direction:
  68. filter["direction"] = direction
  69. return Users.get_users(filter=filter, skip=skip, limit=limit)
  70. @router.get("/all", response_model=UserInfoListResponse)
  71. async def get_all_users(
  72. user=Depends(get_admin_user),
  73. ):
  74. return Users.get_users()
  75. @router.get("/search", response_model=UserIdNameListResponse)
  76. async def search_users(
  77. query: Optional[str] = None,
  78. user=Depends(get_verified_user),
  79. ):
  80. limit = PAGE_ITEM_COUNT
  81. page = 1 # Always return the first page for search
  82. skip = (page - 1) * limit
  83. filter = {}
  84. if query:
  85. filter["query"] = query
  86. return Users.get_users(filter=filter, skip=skip, limit=limit)
  87. ############################
  88. # User Groups
  89. ############################
  90. @router.get("/groups")
  91. async def get_user_groups(user=Depends(get_verified_user)):
  92. return Groups.get_groups_by_member_id(user.id)
  93. ############################
  94. # User Permissions
  95. ############################
  96. @router.get("/permissions")
  97. async def get_user_permissisions(request: Request, user=Depends(get_verified_user)):
  98. user_permissions = get_permissions(
  99. user.id, request.app.state.config.USER_PERMISSIONS
  100. )
  101. return user_permissions
  102. ############################
  103. # User Default Permissions
  104. ############################
  105. class WorkspacePermissions(BaseModel):
  106. models: bool = False
  107. knowledge: bool = False
  108. prompts: bool = False
  109. tools: bool = False
  110. class SharingPermissions(BaseModel):
  111. public_models: bool = True
  112. public_knowledge: bool = True
  113. public_prompts: bool = True
  114. public_tools: bool = True
  115. class ChatPermissions(BaseModel):
  116. controls: bool = True
  117. valves: bool = True
  118. system_prompt: bool = True
  119. params: bool = True
  120. file_upload: bool = True
  121. delete: bool = True
  122. delete_message: bool = True
  123. continue_response: bool = True
  124. regenerate_response: bool = True
  125. rate_response: bool = True
  126. edit: bool = True
  127. share: bool = True
  128. export: bool = True
  129. stt: bool = True
  130. tts: bool = True
  131. call: bool = True
  132. multiple_models: bool = True
  133. temporary: bool = True
  134. temporary_enforced: bool = False
  135. class FeaturesPermissions(BaseModel):
  136. direct_tool_servers: bool = False
  137. web_search: bool = True
  138. image_generation: bool = True
  139. code_interpreter: bool = True
  140. notes: bool = True
  141. class UserPermissions(BaseModel):
  142. workspace: WorkspacePermissions
  143. sharing: SharingPermissions
  144. chat: ChatPermissions
  145. features: FeaturesPermissions
  146. @router.get("/default/permissions", response_model=UserPermissions)
  147. async def get_default_user_permissions(request: Request, user=Depends(get_admin_user)):
  148. return {
  149. "workspace": WorkspacePermissions(
  150. **request.app.state.config.USER_PERMISSIONS.get("workspace", {})
  151. ),
  152. "sharing": SharingPermissions(
  153. **request.app.state.config.USER_PERMISSIONS.get("sharing", {})
  154. ),
  155. "chat": ChatPermissions(
  156. **request.app.state.config.USER_PERMISSIONS.get("chat", {})
  157. ),
  158. "features": FeaturesPermissions(
  159. **request.app.state.config.USER_PERMISSIONS.get("features", {})
  160. ),
  161. }
  162. @router.post("/default/permissions")
  163. async def update_default_user_permissions(
  164. request: Request, form_data: UserPermissions, user=Depends(get_admin_user)
  165. ):
  166. request.app.state.config.USER_PERMISSIONS = form_data.model_dump()
  167. return request.app.state.config.USER_PERMISSIONS
  168. ############################
  169. # GetUserSettingsBySessionUser
  170. ############################
  171. @router.get("/user/settings", response_model=Optional[UserSettings])
  172. async def get_user_settings_by_session_user(user=Depends(get_verified_user)):
  173. user = Users.get_user_by_id(user.id)
  174. if user:
  175. return user.settings
  176. else:
  177. raise HTTPException(
  178. status_code=status.HTTP_400_BAD_REQUEST,
  179. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  180. )
  181. ############################
  182. # UpdateUserSettingsBySessionUser
  183. ############################
  184. @router.post("/user/settings/update", response_model=UserSettings)
  185. async def update_user_settings_by_session_user(
  186. request: Request, form_data: UserSettings, user=Depends(get_verified_user)
  187. ):
  188. updated_user_settings = form_data.model_dump()
  189. if (
  190. user.role != "admin"
  191. and "toolServers" in updated_user_settings.get("ui").keys()
  192. and not has_permission(
  193. user.id,
  194. "features.direct_tool_servers",
  195. request.app.state.config.USER_PERMISSIONS,
  196. )
  197. ):
  198. # If the user is not an admin and does not have permission to use tool servers, remove the key
  199. updated_user_settings["ui"].pop("toolServers", None)
  200. user = Users.update_user_settings_by_id(user.id, updated_user_settings)
  201. if user:
  202. return user.settings
  203. else:
  204. raise HTTPException(
  205. status_code=status.HTTP_400_BAD_REQUEST,
  206. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  207. )
  208. ############################
  209. # GetUserInfoBySessionUser
  210. ############################
  211. @router.get("/user/info", response_model=Optional[dict])
  212. async def get_user_info_by_session_user(user=Depends(get_verified_user)):
  213. user = Users.get_user_by_id(user.id)
  214. if user:
  215. return user.info
  216. else:
  217. raise HTTPException(
  218. status_code=status.HTTP_400_BAD_REQUEST,
  219. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  220. )
  221. ############################
  222. # UpdateUserInfoBySessionUser
  223. ############################
  224. @router.post("/user/info/update", response_model=Optional[dict])
  225. async def update_user_info_by_session_user(
  226. form_data: dict, user=Depends(get_verified_user)
  227. ):
  228. user = Users.get_user_by_id(user.id)
  229. if user:
  230. if user.info is None:
  231. user.info = {}
  232. user = Users.update_user_by_id(user.id, {"info": {**user.info, **form_data}})
  233. if user:
  234. return user.info
  235. else:
  236. raise HTTPException(
  237. status_code=status.HTTP_400_BAD_REQUEST,
  238. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  239. )
  240. else:
  241. raise HTTPException(
  242. status_code=status.HTTP_400_BAD_REQUEST,
  243. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  244. )
  245. ############################
  246. # GetUserById
  247. ############################
  248. class UserResponse(BaseModel):
  249. name: str
  250. profile_image_url: str
  251. active: Optional[bool] = None
  252. @router.get("/{user_id}", response_model=UserResponse)
  253. async def get_user_by_id(user_id: str, user=Depends(get_verified_user)):
  254. # Check if user_id is a shared chat
  255. # If it is, get the user_id from the chat
  256. if user_id.startswith("shared-"):
  257. chat_id = user_id.replace("shared-", "")
  258. chat = Chats.get_chat_by_id(chat_id)
  259. if chat:
  260. user_id = chat.user_id
  261. else:
  262. raise HTTPException(
  263. status_code=status.HTTP_400_BAD_REQUEST,
  264. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  265. )
  266. user = Users.get_user_by_id(user_id)
  267. if user:
  268. return UserResponse(
  269. **{
  270. "name": user.name,
  271. "profile_image_url": user.profile_image_url,
  272. "active": get_active_status_by_user_id(user_id),
  273. }
  274. )
  275. else:
  276. raise HTTPException(
  277. status_code=status.HTTP_400_BAD_REQUEST,
  278. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  279. )
  280. @router.get("/{user_id}/oauth/sessions", response_model=Optional[dict])
  281. async def get_user_oauth_sessions_by_id(user_id: str, user=Depends(get_admin_user)):
  282. sessions = OAuthSessions.get_sessions_by_user_id(user_id)
  283. if sessions and len(sessions) > 0:
  284. return sessions
  285. else:
  286. raise HTTPException(
  287. status_code=status.HTTP_400_BAD_REQUEST,
  288. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  289. )
  290. ############################
  291. # GetUserProfileImageById
  292. ############################
  293. @router.get("/{user_id}/profile/image")
  294. async def get_user_profile_image_by_id(user_id: str, user=Depends(get_verified_user)):
  295. user = Users.get_user_by_id(user_id)
  296. if user:
  297. if user.profile_image_url:
  298. # check if it's url or base64
  299. if user.profile_image_url.startswith("http"):
  300. return Response(
  301. status_code=status.HTTP_302_FOUND,
  302. headers={"Location": user.profile_image_url},
  303. )
  304. elif user.profile_image_url.startswith("data:image"):
  305. try:
  306. header, base64_data = user.profile_image_url.split(",", 1)
  307. image_data = base64.b64decode(base64_data)
  308. image_buffer = io.BytesIO(image_data)
  309. return StreamingResponse(
  310. image_buffer,
  311. media_type="image/png",
  312. headers={"Content-Disposition": "inline; filename=image.png"},
  313. )
  314. except Exception as e:
  315. pass
  316. return FileResponse(f"{STATIC_DIR}/user.png")
  317. else:
  318. raise HTTPException(
  319. status_code=status.HTTP_400_BAD_REQUEST,
  320. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  321. )
  322. ############################
  323. # GetUserActiveStatusById
  324. ############################
  325. @router.get("/{user_id}/active", response_model=dict)
  326. async def get_user_active_status_by_id(user_id: str, user=Depends(get_verified_user)):
  327. return {
  328. "active": get_user_active_status(user_id),
  329. }
  330. ############################
  331. # UpdateUserById
  332. ############################
  333. @router.post("/{user_id}/update", response_model=Optional[UserModel])
  334. async def update_user_by_id(
  335. user_id: str,
  336. form_data: UserUpdateForm,
  337. session_user=Depends(get_admin_user),
  338. ):
  339. # Prevent modification of the primary admin user by other admins
  340. try:
  341. first_user = Users.get_first_user()
  342. if first_user:
  343. if user_id == first_user.id:
  344. if session_user.id != user_id:
  345. # If the user trying to update is the primary admin, and they are not the primary admin themselves
  346. raise HTTPException(
  347. status_code=status.HTTP_403_FORBIDDEN,
  348. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  349. )
  350. if form_data.role != "admin":
  351. # If the primary admin is trying to change their own role, prevent it
  352. raise HTTPException(
  353. status_code=status.HTTP_403_FORBIDDEN,
  354. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  355. )
  356. except Exception as e:
  357. log.error(f"Error checking primary admin status: {e}")
  358. raise HTTPException(
  359. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  360. detail="Could not verify primary admin status.",
  361. )
  362. user = Users.get_user_by_id(user_id)
  363. if user:
  364. if form_data.email.lower() != user.email:
  365. email_user = Users.get_user_by_email(form_data.email.lower())
  366. if email_user:
  367. raise HTTPException(
  368. status_code=status.HTTP_400_BAD_REQUEST,
  369. detail=ERROR_MESSAGES.EMAIL_TAKEN,
  370. )
  371. if form_data.password:
  372. hashed = get_password_hash(form_data.password)
  373. log.debug(f"hashed: {hashed}")
  374. Auths.update_user_password_by_id(user_id, hashed)
  375. Auths.update_email_by_id(user_id, form_data.email.lower())
  376. updated_user = Users.update_user_by_id(
  377. user_id,
  378. {
  379. "role": form_data.role,
  380. "name": form_data.name,
  381. "email": form_data.email.lower(),
  382. "profile_image_url": form_data.profile_image_url,
  383. },
  384. )
  385. if updated_user:
  386. return updated_user
  387. raise HTTPException(
  388. status_code=status.HTTP_400_BAD_REQUEST,
  389. detail=ERROR_MESSAGES.DEFAULT(),
  390. )
  391. raise HTTPException(
  392. status_code=status.HTTP_400_BAD_REQUEST,
  393. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  394. )
  395. ############################
  396. # DeleteUserById
  397. ############################
  398. @router.delete("/{user_id}", response_model=bool)
  399. async def delete_user_by_id(user_id: str, user=Depends(get_admin_user)):
  400. # Prevent deletion of the primary admin user
  401. try:
  402. first_user = Users.get_first_user()
  403. if first_user and user_id == first_user.id:
  404. raise HTTPException(
  405. status_code=status.HTTP_403_FORBIDDEN,
  406. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  407. )
  408. except Exception as e:
  409. log.error(f"Error checking primary admin status: {e}")
  410. raise HTTPException(
  411. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  412. detail="Could not verify primary admin status.",
  413. )
  414. if user.id != user_id:
  415. result = Auths.delete_auth_by_id(user_id)
  416. if result:
  417. return True
  418. raise HTTPException(
  419. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  420. detail=ERROR_MESSAGES.DELETE_USER_ERROR,
  421. )
  422. # Prevent self-deletion
  423. raise HTTPException(
  424. status_code=status.HTTP_403_FORBIDDEN,
  425. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  426. )
  427. ############################
  428. # GetUserGroupsById
  429. ############################
  430. @router.get("/{user_id}/groups")
  431. async def get_user_groups_by_id(user_id: str, user=Depends(get_admin_user)):
  432. return Groups.get_groups_by_member_id(user_id)