users.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. # GetUserSettingsBySessionUser
  128. ############################
  129. @router.get("/user/settings", response_model=Optional[UserSettings])
  130. async def get_user_settings_by_session_user(user=Depends(get_verified_user)):
  131. user = Users.get_user_by_id(user.id)
  132. if user:
  133. return user.settings
  134. else:
  135. raise HTTPException(
  136. status_code=status.HTTP_400_BAD_REQUEST,
  137. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  138. )
  139. ############################
  140. # UpdateUserSettingsBySessionUser
  141. ############################
  142. @router.post("/user/settings/update", response_model=UserSettings)
  143. async def update_user_settings_by_session_user(
  144. request: Request, form_data: UserSettings, user=Depends(get_verified_user)
  145. ):
  146. updated_user_settings = form_data.model_dump()
  147. if (
  148. user.role != "admin"
  149. and "toolServers" in updated_user_settings.get("ui").keys()
  150. and not has_permission(
  151. user.id,
  152. "features.direct_tool_servers",
  153. request.app.state.config.USER_PERMISSIONS,
  154. )
  155. ):
  156. # If the user is not an admin and does not have permission to use tool servers, remove the key
  157. updated_user_settings["ui"].pop("toolServers", None)
  158. user = Users.update_user_settings_by_id(user.id, updated_user_settings)
  159. if user:
  160. return user.settings
  161. else:
  162. raise HTTPException(
  163. status_code=status.HTTP_400_BAD_REQUEST,
  164. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  165. )
  166. ############################
  167. # GetUserInfoBySessionUser
  168. ############################
  169. @router.get("/user/info", response_model=Optional[dict])
  170. async def get_user_info_by_session_user(user=Depends(get_verified_user)):
  171. user = Users.get_user_by_id(user.id)
  172. if user:
  173. return user.info
  174. else:
  175. raise HTTPException(
  176. status_code=status.HTTP_400_BAD_REQUEST,
  177. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  178. )
  179. ############################
  180. # UpdateUserInfoBySessionUser
  181. ############################
  182. @router.post("/user/info/update", response_model=Optional[dict])
  183. async def update_user_info_by_session_user(
  184. form_data: dict, user=Depends(get_verified_user)
  185. ):
  186. user = Users.get_user_by_id(user.id)
  187. if user:
  188. if user.info is None:
  189. user.info = {}
  190. user = Users.update_user_by_id(user.id, {"info": {**user.info, **form_data}})
  191. if user:
  192. return user.info
  193. else:
  194. raise HTTPException(
  195. status_code=status.HTTP_400_BAD_REQUEST,
  196. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  197. )
  198. else:
  199. raise HTTPException(
  200. status_code=status.HTTP_400_BAD_REQUEST,
  201. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  202. )
  203. ############################
  204. # GetUserById
  205. ############################
  206. class UserResponse(BaseModel):
  207. name: str
  208. profile_image_url: str
  209. active: Optional[bool] = None
  210. @router.get("/{user_id}", response_model=UserResponse)
  211. async def get_user_by_id(user_id: str, user=Depends(get_verified_user)):
  212. # Check if user_id is a shared chat
  213. # If it is, get the user_id from the chat
  214. if user_id.startswith("shared-"):
  215. chat_id = user_id.replace("shared-", "")
  216. chat = Chats.get_chat_by_id(chat_id)
  217. if chat:
  218. user_id = chat.user_id
  219. else:
  220. raise HTTPException(
  221. status_code=status.HTTP_400_BAD_REQUEST,
  222. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  223. )
  224. user = Users.get_user_by_id(user_id)
  225. if user:
  226. return UserResponse(
  227. **{
  228. "name": user.name,
  229. "profile_image_url": user.profile_image_url,
  230. "active": get_active_status_by_user_id(user_id),
  231. }
  232. )
  233. else:
  234. raise HTTPException(
  235. status_code=status.HTTP_400_BAD_REQUEST,
  236. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  237. )
  238. ############################
  239. # UpdateUserById
  240. ############################
  241. @router.post("/{user_id}/update", response_model=Optional[UserModel])
  242. async def update_user_by_id(
  243. user_id: str,
  244. form_data: UserUpdateForm,
  245. session_user=Depends(get_admin_user),
  246. ):
  247. # Prevent modification of the primary admin user by other admins
  248. try:
  249. first_user = Users.get_first_user()
  250. if first_user:
  251. if user_id == first_user.id:
  252. if session_user.id != user_id:
  253. # If the user trying to update is the primary admin, and they are not the primary admin themselves
  254. raise HTTPException(
  255. status_code=status.HTTP_403_FORBIDDEN,
  256. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  257. )
  258. if form_data.role != "admin":
  259. # If the primary admin is trying to change their own role, prevent it
  260. raise HTTPException(
  261. status_code=status.HTTP_403_FORBIDDEN,
  262. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  263. )
  264. except Exception as e:
  265. log.error(f"Error checking primary admin status: {e}")
  266. raise HTTPException(
  267. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  268. detail="Could not verify primary admin status.",
  269. )
  270. user = Users.get_user_by_id(user_id)
  271. if user:
  272. if form_data.email.lower() != user.email:
  273. email_user = Users.get_user_by_email(form_data.email.lower())
  274. if email_user:
  275. raise HTTPException(
  276. status_code=status.HTTP_400_BAD_REQUEST,
  277. detail=ERROR_MESSAGES.EMAIL_TAKEN,
  278. )
  279. if form_data.password:
  280. hashed = get_password_hash(form_data.password)
  281. log.debug(f"hashed: {hashed}")
  282. Auths.update_user_password_by_id(user_id, hashed)
  283. Auths.update_email_by_id(user_id, form_data.email.lower())
  284. updated_user = Users.update_user_by_id(
  285. user_id,
  286. {
  287. "role": form_data.role,
  288. "name": form_data.name,
  289. "email": form_data.email.lower(),
  290. "profile_image_url": form_data.profile_image_url,
  291. },
  292. )
  293. if updated_user:
  294. return updated_user
  295. raise HTTPException(
  296. status_code=status.HTTP_400_BAD_REQUEST,
  297. detail=ERROR_MESSAGES.DEFAULT(),
  298. )
  299. raise HTTPException(
  300. status_code=status.HTTP_400_BAD_REQUEST,
  301. detail=ERROR_MESSAGES.USER_NOT_FOUND,
  302. )
  303. ############################
  304. # DeleteUserById
  305. ############################
  306. @router.delete("/{user_id}", response_model=bool)
  307. async def delete_user_by_id(user_id: str, user=Depends(get_admin_user)):
  308. # Prevent deletion of the primary admin user
  309. try:
  310. first_user = Users.get_first_user()
  311. if first_user and user_id == first_user.id:
  312. raise HTTPException(
  313. status_code=status.HTTP_403_FORBIDDEN,
  314. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  315. )
  316. except Exception as e:
  317. log.error(f"Error checking primary admin status: {e}")
  318. raise HTTPException(
  319. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  320. detail="Could not verify primary admin status.",
  321. )
  322. if user.id != user_id:
  323. result = Auths.delete_auth_by_id(user_id)
  324. if result:
  325. return True
  326. raise HTTPException(
  327. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  328. detail=ERROR_MESSAGES.DELETE_USER_ERROR,
  329. )
  330. # Prevent self-deletion
  331. raise HTTPException(
  332. status_code=status.HTTP_403_FORBIDDEN,
  333. detail=ERROR_MESSAGES.ACTION_PROHIBITED,
  334. )