users.py 13 KB

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