users.py 13 KB

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