users.py 14 KB

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