users.py 12 KB

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