users.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. import logging
  2. from typing import Optional
  3. from open_webui.models.auths import Auths
  4. from open_webui.models.groups import Groups
  5. from open_webui.models.chats import Chats
  6. from open_webui.models.users import (
  7. UserModel,
  8. UserListResponse,
  9. UserRoleUpdateForm,
  10. Users,
  11. UserSettings,
  12. UserUpdateForm,
  13. )
  14. from open_webui.socket.main import get_active_status_by_user_id
  15. from open_webui.constants import ERROR_MESSAGES
  16. from open_webui.env import SRC_LOG_LEVELS
  17. from fastapi import APIRouter, Depends, HTTPException, Request, status
  18. from pydantic import BaseModel
  19. from open_webui.utils.auth import get_admin_user, get_password_hash, get_verified_user
  20. from open_webui.utils.access_control import get_permissions, has_permission
  21. log = logging.getLogger(__name__)
  22. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  23. router = APIRouter()
  24. ############################
  25. # GetUsers
  26. ############################
  27. PAGE_ITEM_COUNT = 30
  28. @router.get("/", response_model=UserListResponse)
  29. async def get_users(
  30. query: Optional[str] = None,
  31. order_by: Optional[str] = None,
  32. direction: Optional[str] = None,
  33. page: Optional[int] = 1,
  34. user=Depends(get_admin_user),
  35. ):
  36. limit = PAGE_ITEM_COUNT
  37. page = max(1, page)
  38. skip = (page - 1) * limit
  39. filter = {}
  40. if query:
  41. filter["query"] = query
  42. if order_by:
  43. filter["order_by"] = order_by
  44. if direction:
  45. filter["direction"] = direction
  46. return Users.get_users(filter=filter, skip=skip, limit=limit)
  47. @router.get("/all", response_model=UserListResponse)
  48. async def get_all_users(
  49. user=Depends(get_admin_user),
  50. ):
  51. return Users.get_users()
  52. ############################
  53. # User Groups
  54. ############################
  55. @router.get("/groups")
  56. async def get_user_groups(user=Depends(get_verified_user)):
  57. return Groups.get_groups_by_member_id(user.id)
  58. ############################
  59. # User Permissions
  60. ############################
  61. @router.get("/permissions")
  62. async def get_user_permissisions(request: Request, user=Depends(get_verified_user)):
  63. user_permissions = get_permissions(
  64. user.id, request.app.state.config.USER_PERMISSIONS
  65. )
  66. return user_permissions
  67. ############################
  68. # User Default Permissions
  69. ############################
  70. class WorkspacePermissions(BaseModel):
  71. models: bool = False
  72. knowledge: bool = False
  73. prompts: bool = False
  74. tools: bool = False
  75. class SharingPermissions(BaseModel):
  76. public_models: bool = True
  77. public_knowledge: bool = True
  78. public_prompts: bool = True
  79. public_tools: bool = True
  80. class ChatPermissions(BaseModel):
  81. controls: bool = True
  82. file_upload: bool = True
  83. delete: bool = True
  84. edit: bool = True
  85. share: bool = True
  86. export: bool = True
  87. stt: bool = True
  88. tts: bool = True
  89. call: bool = True
  90. multiple_models: bool = True
  91. temporary: bool = True
  92. temporary_enforced: bool = False
  93. class FeaturesPermissions(BaseModel):
  94. direct_tool_servers: bool = False
  95. web_search: bool = True
  96. image_generation: bool = True
  97. code_interpreter: bool = True
  98. notes: bool = True
  99. class UserPermissions(BaseModel):
  100. workspace: WorkspacePermissions
  101. sharing: SharingPermissions
  102. chat: ChatPermissions
  103. features: FeaturesPermissions
  104. @router.get("/default/permissions", response_model=UserPermissions)
  105. async def get_default_user_permissions(request: Request, user=Depends(get_admin_user)):
  106. return {
  107. "workspace": WorkspacePermissions(
  108. **request.app.state.config.USER_PERMISSIONS.get("workspace", {})
  109. ),
  110. "sharing": SharingPermissions(
  111. **request.app.state.config.USER_PERMISSIONS.get("sharing", {})
  112. ),
  113. "chat": ChatPermissions(
  114. **request.app.state.config.USER_PERMISSIONS.get("chat", {})
  115. ),
  116. "features": FeaturesPermissions(
  117. **request.app.state.config.USER_PERMISSIONS.get("features", {})
  118. ),
  119. }
  120. @router.post("/default/permissions")
  121. async def update_default_user_permissions(
  122. request: Request, form_data: UserPermissions, user=Depends(get_admin_user)
  123. ):
  124. request.app.state.config.USER_PERMISSIONS = form_data.model_dump()
  125. return request.app.state.config.USER_PERMISSIONS
  126. ############################
  127. # UpdateUserRole
  128. ############################
  129. @router.post("/update/role", response_model=Optional[UserModel])
  130. async def update_user_role(form_data: UserRoleUpdateForm, user=Depends(get_admin_user)):
  131. if user.id != form_data.id and form_data.id != Users.get_first_user().id:
  132. return Users.update_user_role_by_id(form_data.id, form_data.role)
  133. raise HTTPException(
  134. status_code=status.HTTP_403_FORBIDDEN,
  135. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  136. )
  137. ############################
  138. # GetUserSettingsBySessionUser
  139. ############################
  140. @router.get("/user/settings", response_model=Optional[UserSettings])
  141. async def get_user_settings_by_session_user(user=Depends(get_verified_user)):
  142. user = Users.get_user_by_id(user.id)
  143. if user:
  144. return user.settings
  145. else:
  146. raise HTTPException(
  147. status_code=status.HTTP_400_BAD_REQUEST,
  148. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  149. )
  150. ############################
  151. # UpdateUserSettingsBySessionUser
  152. ############################
  153. @router.post("/user/settings/update", response_model=UserSettings)
  154. async def update_user_settings_by_session_user(
  155. request: Request, form_data: UserSettings, user=Depends(get_verified_user)
  156. ):
  157. updated_user_settings = form_data.model_dump()
  158. if (
  159. user.role != "admin"
  160. and "toolServers" in updated_user_settings.get("ui").keys()
  161. and not has_permission(
  162. user.id,
  163. "features.direct_tool_servers",
  164. request.app.state.config.USER_PERMISSIONS,
  165. )
  166. ):
  167. # If the user is not an admin and does not have permission to use tool servers, remove the key
  168. updated_user_settings["ui"].pop("toolServers", None)
  169. user = Users.update_user_settings_by_id(user.id, updated_user_settings)
  170. if user:
  171. return user.settings
  172. else:
  173. raise HTTPException(
  174. status_code=status.HTTP_400_BAD_REQUEST,
  175. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  176. )
  177. ############################
  178. # GetUserInfoBySessionUser
  179. ############################
  180. @router.get("/user/info", response_model=Optional[dict])
  181. async def get_user_info_by_session_user(user=Depends(get_verified_user)):
  182. user = Users.get_user_by_id(user.id)
  183. if user:
  184. return user.info
  185. else:
  186. raise HTTPException(
  187. status_code=status.HTTP_400_BAD_REQUEST,
  188. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  189. )
  190. ############################
  191. # UpdateUserInfoBySessionUser
  192. ############################
  193. @router.post("/user/info/update", response_model=Optional[dict])
  194. async def update_user_info_by_session_user(
  195. form_data: dict, user=Depends(get_verified_user)
  196. ):
  197. user = Users.get_user_by_id(user.id)
  198. if user:
  199. if user.info is None:
  200. user.info = {}
  201. user = Users.update_user_by_id(user.id, {"info": {**user.info, **form_data}})
  202. if user:
  203. return user.info
  204. else:
  205. raise HTTPException(
  206. status_code=status.HTTP_400_BAD_REQUEST,
  207. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  208. )
  209. else:
  210. raise HTTPException(
  211. status_code=status.HTTP_400_BAD_REQUEST,
  212. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  213. )
  214. ############################
  215. # GetUserById
  216. ############################
  217. class UserResponse(BaseModel):
  218. name: str
  219. profile_image_url: str
  220. active: Optional[bool] = None
  221. @router.get("/{user_id}", response_model=UserResponse)
  222. async def get_user_by_id(user_id: str, user=Depends(get_verified_user)):
  223. # Check if user_id is a shared chat
  224. # If it is, get the user_id from the chat
  225. if user_id.startswith("shared-"):
  226. chat_id = user_id.replace("shared-", "")
  227. chat = Chats.get_chat_by_id(chat_id)
  228. if chat:
  229. user_id = chat.user_id
  230. else:
  231. raise HTTPException(
  232. status_code=status.HTTP_400_BAD_REQUEST,
  233. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  234. )
  235. user = Users.get_user_by_id(user_id)
  236. if user:
  237. return UserResponse(
  238. **{
  239. "name": user.name,
  240. "profile_image_url": user.profile_image_url,
  241. "active": get_active_status_by_user_id(user_id),
  242. }
  243. )
  244. else:
  245. raise HTTPException(
  246. status_code=status.HTTP_400_BAD_REQUEST,
  247. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  248. )
  249. ############################
  250. # UpdateUserById
  251. ############################
  252. @router.post("/{user_id}/update", response_model=Optional[UserModel])
  253. async def update_user_by_id(
  254. user_id: str,
  255. form_data: UserUpdateForm,
  256. session_user=Depends(get_admin_user),
  257. ):
  258. # Prevent modification of the primary admin user by other admins
  259. try:
  260. first_user = Users.get_first_user()
  261. if first_user and user_id == first_user.id and session_user.id != user_id:
  262. raise HTTPException(
  263. status_code=status.HTTP_403_FORBIDDEN,
  264. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  265. )
  266. except Exception as e:
  267. log.error(f"Error checking primary admin status: {e}")
  268. raise HTTPException(
  269. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  270. detail="Could not verify primary admin status.",
  271. )
  272. user = Users.get_user_by_id(user_id)
  273. if user:
  274. if form_data.email.lower() != user.email:
  275. email_user = Users.get_user_by_email(form_data.email.lower())
  276. if email_user:
  277. raise HTTPException(
  278. status_code=status.HTTP_400_BAD_REQUEST,
  279. detail=ERROR_MESSAGES.EMAIL_TAKEN,
  280. )
  281. if form_data.password:
  282. hashed = get_password_hash(form_data.password)
  283. log.debug(f"hashed: {hashed}")
  284. Auths.update_user_password_by_id(user_id, hashed)
  285. Auths.update_email_by_id(user_id, form_data.email.lower())
  286. updated_user = Users.update_user_by_id(
  287. user_id,
  288. {
  289. "name": form_data.name,
  290. "email": form_data.email.lower(),
  291. "profile_image_url": form_data.profile_image_url,
  292. },
  293. )
  294. if updated_user:
  295. return updated_user
  296. raise HTTPException(
  297. status_code=status.HTTP_400_BAD_REQUEST,
  298. detail=ERROR_MESSAGES.DEFAULT(),
  299. )
  300. raise HTTPException(
  301. status_code=status.HTTP_400_BAD_REQUEST,
  302. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  303. )
  304. ############################
  305. # DeleteUserById
  306. ############################
  307. @router.delete("/{user_id}", response_model=bool)
  308. async def delete_user_by_id(user_id: str, user=Depends(get_admin_user)):
  309. # Prevent deletion of the primary admin user
  310. try:
  311. first_user = Users.get_first_user()
  312. if first_user and user_id == first_user.id:
  313. raise HTTPException(
  314. status_code=status.HTTP_403_FORBIDDEN,
  315. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  316. )
  317. except Exception as e:
  318. log.error(f"Error checking primary admin status: {e}")
  319. raise HTTPException(
  320. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  321. detail="Could not verify primary admin status.",
  322. )
  323. if user.id != user_id:
  324. result = Auths.delete_auth_by_id(user_id)
  325. if result:
  326. return True
  327. raise HTTPException(
  328. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  329. detail=ERROR_MESSAGES.DELETE_USER_ERROR,
  330. )
  331. # Prevent self-deletion
  332. raise HTTPException(
  333. status_code=status.HTTP_403_FORBIDDEN,
  334. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  335. )