mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-25 23:00:53 -05:00
refac
This commit is contained in:
1 parent
6b1d890ffd
commit
464e83e414
15 files changed
+321
-255
No files matched your search
@@ -365,6 +365,9 @@ class EventDefinitions(BaseModel):
|
||||
NOTE_ACCESS_UPDATED: EventDefinition = EventDefinition(
|
||||
name='note.access_updated', description='Note access was updated.', message='Note access updated'
|
||||
)
|
||||
NOTE_FOLDER_UPDATED: EventDefinition = EventDefinition(
|
||||
name='note.folder_updated', description='A note folder assignment was updated.', message='Note folder updated'
|
||||
)
|
||||
NOTE_PINNED: EventDefinition = EventDefinition(
|
||||
name='note.pinned', description='A note was pinned.', message='Note pinned'
|
||||
)
|
||||
@@ -1156,7 +1159,7 @@ class NotificationEventSink:
|
||||
|
||||
class SocketSessionEventSink:
|
||||
async def handle_event(self, request: Request, event: Event) -> None:
|
||||
from open_webui.socket.main import refresh_chat_access
|
||||
from open_webui.socket.main import refresh_chat_access, refresh_note_access
|
||||
|
||||
if event.event in {
|
||||
EVENTS.FOLDER_ACCESS_UPDATED.name,
|
||||
@@ -1166,6 +1169,10 @@ class SocketSessionEventSink:
|
||||
EVENTS.CHAT_DELETED_ALL.name,
|
||||
}:
|
||||
await refresh_chat_access()
|
||||
if event.event != EVENTS.CHAT_DELETED_ALL.name:
|
||||
await refresh_note_access()
|
||||
elif event.event == EVENTS.NOTE_FOLDER_UPDATED.name:
|
||||
await refresh_note_access((event.subject or {}).get('id'))
|
||||
elif event.event in {
|
||||
EVENTS.CHAT_SHARED.name,
|
||||
EVENTS.CHAT_UNSHARED.name,
|
||||
|
||||
@@ -22,7 +22,9 @@ from sqlalchemy import (
|
||||
BigInteger,
|
||||
Column,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Text,
|
||||
and_,
|
||||
cast,
|
||||
delete,
|
||||
func,
|
||||
@@ -411,10 +413,13 @@ class Note(Base):
|
||||
title = Column(Text)
|
||||
data = Column(JSON, nullable=True)
|
||||
meta = Column(JSON, nullable=True)
|
||||
folder_id = Column(Text, nullable=True)
|
||||
|
||||
created_at = Column(BigInteger)
|
||||
updated_at = Column(BigInteger)
|
||||
|
||||
__table_args__ = (Index('ix_note_folder_id', 'folder_id'),)
|
||||
|
||||
|
||||
def sanitize_note_data(data: Optional[dict]) -> Optional[dict]:
|
||||
"""Sanitize malformed note.data so content.md is always markdown text."""
|
||||
@@ -451,6 +456,7 @@ class NoteModel(BaseModel):
|
||||
title: str
|
||||
data: Optional[dict] = None
|
||||
meta: Optional[dict] = None
|
||||
folder_id: Optional[str] = None
|
||||
is_pinned: Optional[bool] = False
|
||||
|
||||
access_grants: list[AccessGrantModel] = Field(default_factory=list)
|
||||
@@ -480,6 +486,7 @@ class NoteForm(BaseModel):
|
||||
title: str
|
||||
data: Optional[dict] = None
|
||||
meta: Optional[dict] = None
|
||||
folder_id: Optional[str] = None
|
||||
access_grants: Optional[list[dict]] = None
|
||||
|
||||
@field_validator('data', mode='before')
|
||||
@@ -545,14 +552,32 @@ class NoteTable:
|
||||
return note_model
|
||||
|
||||
def _has_permission(self, db, query, filter: dict, permission: str = 'read'):
|
||||
return AccessGrants.has_permission_filter(
|
||||
db=db,
|
||||
query=query,
|
||||
DocumentModel=Note,
|
||||
filter=filter,
|
||||
resource_type='note',
|
||||
permission=permission,
|
||||
)
|
||||
from open_webui.utils.access_control.folders import accessible_folder_ids
|
||||
|
||||
user_id = filter.get('user_id')
|
||||
group_ids = filter.get('group_ids', [])
|
||||
if not user_id:
|
||||
return AccessGrants.has_permission_filter(
|
||||
db=db,
|
||||
query=query,
|
||||
DocumentModel=Note,
|
||||
filter=filter,
|
||||
resource_type='note',
|
||||
permission=permission,
|
||||
)
|
||||
|
||||
def allowed(permission):
|
||||
return or_(
|
||||
AccessGrants.has_grant_expression(user_id, 'note', Note.id, permission, group_ids),
|
||||
and_(
|
||||
Note.folder_id.is_not(None),
|
||||
Note.folder_id.in_(accessible_folder_ids(user_id, group_ids, permission)),
|
||||
),
|
||||
)
|
||||
|
||||
if permission == 'read_only':
|
||||
return query.filter(Note.user_id != user_id, allowed('read'), ~allowed('write'))
|
||||
return query.filter(or_(Note.user_id == user_id, allowed(permission)))
|
||||
|
||||
async def insert_new_note(
|
||||
self, user_id: str, form_data: NoteForm, db: Optional[AsyncSession] = None
|
||||
@@ -630,6 +655,9 @@ class NoteTable:
|
||||
if filter.get('tag_ids'):
|
||||
stmt = stmt.filter(resource_tag_filter('note', Note.id, filter['tag_ids']))
|
||||
|
||||
if filter.get('folder_id'):
|
||||
stmt = stmt.filter(Note.folder_id == filter['folder_id'])
|
||||
|
||||
view_option = filter.get('view_option')
|
||||
if view_option == 'created':
|
||||
stmt = stmt.filter(Note.user_id == user_id)
|
||||
@@ -871,6 +899,28 @@ class NoteTable:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def get_notes_by_folder_id_and_user_id(
|
||||
self, folder_id: str, user_id: str, db: Optional[AsyncSession] = None
|
||||
) -> list[NoteModel]:
|
||||
async with get_async_db_context(db) as db:
|
||||
result = await db.execute(select(Note).filter_by(folder_id=folder_id, user_id=user_id))
|
||||
return [await self._to_note_model(note, db=db) for note in result.scalars().all()]
|
||||
|
||||
async def update_note_folder_id_by_id(
|
||||
self, id: str, folder_id: Optional[str], db: Optional[AsyncSession] = None
|
||||
) -> Optional[NoteModel]:
|
||||
async with get_async_db_context(db) as db:
|
||||
await db.execute(update(Note).filter_by(id=id).values(folder_id=folder_id))
|
||||
await db.commit()
|
||||
return await self.get_note_by_id(id, db=db)
|
||||
|
||||
async def move_notes_by_folder_id(
|
||||
self, folder_id: str, new_folder_id: Optional[str], db: Optional[AsyncSession] = None
|
||||
) -> None:
|
||||
async with get_async_db_context(db) as db:
|
||||
await db.execute(update(Note).filter_by(folder_id=folder_id).values(folder_id=new_folder_id))
|
||||
await db.commit()
|
||||
|
||||
async def get_tag_counts(
|
||||
self, filter: dict, permission: str = 'write', db: Optional[AsyncSession] = None
|
||||
) -> list[dict]:
|
||||
|
||||
@@ -52,6 +52,7 @@ from open_webui.retrieval.vector.main import GetResult, SearchResult
|
||||
from open_webui.retrieval.web.utils import get_web_loader
|
||||
from open_webui.utils.access_control.files import get_owner_accessible_folder_files, has_access_to_file
|
||||
from open_webui.utils.access_control.folders import has_folder_access
|
||||
from open_webui.utils.access_control.notes import has_note_access
|
||||
from open_webui.utils.headers import get_json_bearer_headers, include_user_info_headers
|
||||
from open_webui.utils.misc import get_content_from_message, get_message_list, strict_match_mime_type
|
||||
|
||||
@@ -1457,16 +1458,7 @@ async def get_sources_from_items(
|
||||
# Note Attached
|
||||
note = await Notes.get_note_by_id(item.get('id'))
|
||||
|
||||
if note and (
|
||||
user.role == 'admin'
|
||||
or note.user_id == user.id
|
||||
or await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
)
|
||||
):
|
||||
if note and (user.role == 'admin' or await has_note_access(user.id, note, 'read')):
|
||||
# User has access to the note
|
||||
query_result = {
|
||||
'documents': [[page['content'].get('md', '') for page in note.data['pages']]],
|
||||
|
||||
@@ -43,7 +43,7 @@ from open_webui.models.users import UserModel
|
||||
from open_webui.socket.main import get_event_emitter
|
||||
from open_webui.tasks import get_response_streams_by_chat_id, has_active_tasks, stop_item_tasks
|
||||
from open_webui.utils.access_control import has_permission, validate_access_grants
|
||||
from open_webui.utils.access_control.folders import has_chat_move_access, has_folder_write_access
|
||||
from open_webui.utils.access_control.folders import has_folder_move_access, has_folder_write_access
|
||||
from open_webui.utils.auth import bearer_security, get_admin_user, get_current_user, get_verified_user
|
||||
from open_webui.utils.chat_fork import build_fork_history
|
||||
from open_webui.utils.context_compaction import compact_chat_branch, get_chat_context_usage
|
||||
@@ -2354,7 +2354,7 @@ async def update_chat_folder_id_by_id(
|
||||
):
|
||||
chat = await Chats.get_chat_by_id(id, db=db)
|
||||
if chat and chat.user_id != user.id:
|
||||
if not await has_chat_move_access(user.id, chat.folder_id, form_data.folder_id, db=db):
|
||||
if not await has_folder_move_access(user.id, chat.folder_id, form_data.folder_id, db=db):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
|
||||
if chat:
|
||||
# None is allowed: it moves the chat out of any folder.
|
||||
|
||||
@@ -26,8 +26,11 @@ from open_webui.models.folders import (
|
||||
folder_status_ids,
|
||||
)
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.notes import NoteListResponse, Notes, NoteUserResponse
|
||||
from open_webui.models.shared_chats import ChatShareMode
|
||||
from open_webui.models.users import Users
|
||||
from open_webui.routers.notes import check_notes_access, truncate_note_data
|
||||
from open_webui.socket.main import close_note
|
||||
from open_webui.tasks import has_active_tasks
|
||||
from open_webui.utils.access_control import (
|
||||
has_permission,
|
||||
@@ -789,6 +792,57 @@ async def get_folder_automations(
|
||||
]
|
||||
|
||||
|
||||
class FolderNoteResponse(NoteUserResponse):
|
||||
write_access: bool = False
|
||||
|
||||
|
||||
class FolderNoteListResponse(NoteListResponse):
|
||||
items: list[FolderNoteResponse]
|
||||
|
||||
|
||||
@router.get('/{id}/notes', response_model=FolderNoteListResponse)
|
||||
async def get_folder_notes(
|
||||
request: Request,
|
||||
id: str,
|
||||
page: int = Query(1, ge=1),
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
"""The folder's notes, whoever made them. Anyone who can read the folder can read its notes."""
|
||||
folder = await check_folder_read_access(request, id, user, db)
|
||||
await check_notes_access(user, db=db)
|
||||
result = await Notes.search_notes(
|
||||
user.id, {'folder_id': id}, skip=(page - 1) * FOLDER_PAGE_SIZE, limit=FOLDER_PAGE_SIZE, db=db
|
||||
)
|
||||
has_write = (
|
||||
user.role == 'admin' or folder.user_id == user.id or await _has_folder_access(user.id, folder, 'write', db)
|
||||
)
|
||||
shared_write = (
|
||||
set()
|
||||
if has_write
|
||||
else await AccessGrants.get_accessible_resource_ids(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_ids=[note.id for note in result.items],
|
||||
permission='write',
|
||||
db=db,
|
||||
)
|
||||
)
|
||||
return FolderNoteListResponse(
|
||||
items=[
|
||||
FolderNoteResponse(
|
||||
**{
|
||||
**note.model_dump(),
|
||||
'data': truncate_note_data(note.data),
|
||||
'write_access': has_write or note.user_id == user.id or note.id in shared_write,
|
||||
}
|
||||
)
|
||||
for note in result.items
|
||||
],
|
||||
total=result.total,
|
||||
)
|
||||
|
||||
|
||||
@router.get('/{id}/users')
|
||||
async def get_folder_users(
|
||||
request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
|
||||
@@ -931,8 +985,12 @@ async def delete_folder_by_id(
|
||||
for folder_id in folder_ids:
|
||||
if delete_contents:
|
||||
await Chats.delete_chats_by_user_id_and_folder_id(folder_owner_id, folder_id, db=db)
|
||||
for note in await Notes.get_notes_by_folder_id_and_user_id(folder_id, folder_owner_id, db=db):
|
||||
await Notes.delete_note_by_id(note.id, db=db)
|
||||
await close_note(note)
|
||||
|
||||
await Chats.move_chats_by_folder_id(folder_id, None, db=db)
|
||||
await Notes.move_notes_by_folder_id(folder_id, None, db=db)
|
||||
|
||||
# Clean up access grants for this folder
|
||||
await AccessGrants.revoke_all_access('folder', folder_id, db=db)
|
||||
|
||||
@@ -52,6 +52,7 @@ from open_webui.utils.access_control import (
|
||||
validate_access_grants,
|
||||
)
|
||||
from open_webui.utils.access_control.files import has_access_to_file
|
||||
from open_webui.utils.access_control.notes import has_note_access
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.chat_variables import get_chat_variables_schema
|
||||
from open_webui.utils.models import get_all_models
|
||||
@@ -885,8 +886,12 @@ async def _verify_version_dependencies(request, form, user, db):
|
||||
if not resource or getattr(resource, 'is_active', True) is False:
|
||||
raise HTTPException(400, f'Referenced {resource_type} is unavailable: {resource_id}')
|
||||
if not (user.role == 'admin' and BYPASS_ADMIN_ACCESS_CONTROL) and resource.user_id != user.id:
|
||||
if not await AccessGrants.has_access(
|
||||
user_id=user.id, resource_type=resource_type, resource_id=resource_id, permission='read', db=db
|
||||
if not (
|
||||
await has_note_access(user.id, resource, 'read', db)
|
||||
if resource_type == 'note'
|
||||
else await AccessGrants.has_access(
|
||||
user_id=user.id, resource_type=resource_type, resource_id=resource_id, permission='read', db=db
|
||||
)
|
||||
):
|
||||
raise HTTPException(403, f'Referenced {resource_type} is not accessible: {resource_id}')
|
||||
|
||||
|
||||
@@ -27,17 +27,18 @@ from open_webui.models.notes import (
|
||||
get_content_files,
|
||||
get_note_files,
|
||||
matching_page,
|
||||
normalize_pages,
|
||||
)
|
||||
from open_webui.models.tags import TagModel, Tags, get_tag_id
|
||||
from open_webui.models.users import UserModel, UserResponse, Users
|
||||
from open_webui.socket.main import close_changed_note_documents, leave_room_for_users, sio
|
||||
from open_webui.socket.main import close_changed_note_documents, close_note, leave_room_for_users, note_rooms, sio
|
||||
from open_webui.utils.access_control import (
|
||||
filter_allowed_access_grants,
|
||||
has_permission,
|
||||
validate_access_grants,
|
||||
)
|
||||
from open_webui.utils.access_control.files import has_access_to_note_files
|
||||
from open_webui.utils.access_control.folders import has_folder_move_access, has_folder_write_access
|
||||
from open_webui.utils.access_control.notes import has_note_access
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
@@ -63,7 +64,7 @@ async def check_notes_access(user: UserModel, db: AsyncSession):
|
||||
)
|
||||
|
||||
|
||||
def _truncate_note_data(data: Optional[dict], max_length: int = 1000, query: str = '') -> Optional[dict]:
|
||||
def truncate_note_data(data: Optional[dict], max_length: int = 1000, query: str = '') -> Optional[dict]:
|
||||
if not data:
|
||||
return data
|
||||
page = matching_page(data, query)
|
||||
@@ -87,12 +88,11 @@ async def leave_note_rooms_for_revoked_users(
|
||||
return
|
||||
|
||||
users = await Users.get_users_by_user_ids(list(revoked_user_ids), db=db)
|
||||
# Admins retain access to notes regardless of grants.
|
||||
user_ids = [user.id for user in users if user.role != 'admin']
|
||||
page_rooms = [
|
||||
f'doc_note:{note.id}:page:{p["id"]}:{p.get("generation", 0)}' for p in normalize_pages(note.data)['pages']
|
||||
# Admins retain access to notes regardless of grants, and the note's folder may still give it.
|
||||
user_ids = [
|
||||
user.id for user in users if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db)
|
||||
]
|
||||
for room in [f'note:{note.id}', f'doc_note:{note.id}', *page_rooms]:
|
||||
for room in note_rooms(note):
|
||||
await leave_room_for_users(room, user_ids)
|
||||
|
||||
|
||||
@@ -138,7 +138,7 @@ async def get_notes(
|
||||
**{
|
||||
**note.model_dump(),
|
||||
'is_pinned': note.id in pinned_note_ids,
|
||||
'data': _truncate_note_data(note.data),
|
||||
'data': truncate_note_data(note.data),
|
||||
'user': UserResponse(**users[note.user_id].model_dump()),
|
||||
}
|
||||
)
|
||||
@@ -170,7 +170,7 @@ async def get_pinned_notes(
|
||||
**{
|
||||
**note.model_dump(),
|
||||
'is_pinned': True,
|
||||
'data': _truncate_note_data(note.data),
|
||||
'data': truncate_note_data(note.data),
|
||||
'user': UserResponse(**users[note.user_id].model_dump()),
|
||||
}
|
||||
)
|
||||
@@ -228,7 +228,7 @@ async def search_notes(
|
||||
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
|
||||
for note in result.items:
|
||||
note.is_pinned = note.id in pinned_note_ids
|
||||
note.data = _truncate_note_data(note.data, query=query or '')
|
||||
note.data = truncate_note_data(note.data, query=query or '')
|
||||
return result
|
||||
|
||||
|
||||
@@ -275,16 +275,7 @@ async def get_note_with_tag_access(id: str, user, db: AsyncSession):
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if user.role != 'admin' and (
|
||||
user.id != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='write',
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'write', db):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
return note
|
||||
|
||||
@@ -301,16 +292,7 @@ async def get_note_tags_by_id(
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if user.role != 'admin' and (
|
||||
user.id != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
return await Tags.get_tags_by_resource('note', id, db=db)
|
||||
@@ -377,6 +359,9 @@ async def create_new_note(
|
||||
):
|
||||
await check_notes_access(user, db=db)
|
||||
|
||||
if form_data.folder_id is not None and not await has_folder_write_access(user.id, form_data.folder_id, db=db):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
form_data.access_grants = await filter_allowed_access_grants(
|
||||
await Config.get('user.permissions'),
|
||||
user.id,
|
||||
@@ -396,7 +381,7 @@ async def create_new_note(
|
||||
EVENTS.NOTE_CREATED,
|
||||
actor=user,
|
||||
subject_id=note.id,
|
||||
data={'title': note.title},
|
||||
data={'title': note.title, 'folder_id': note.folder_id},
|
||||
)
|
||||
return note
|
||||
except Exception as e:
|
||||
@@ -424,30 +409,12 @@ async def get_note_by_id(
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if user.role != 'admin' and (
|
||||
user.id != note.user_id
|
||||
and (
|
||||
not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
db=db,
|
||||
)
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
write_access = (
|
||||
user.role == 'admin'
|
||||
or (user.id == note.user_id)
|
||||
or await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='write',
|
||||
db=db,
|
||||
)
|
||||
or await has_note_access(user.id, note, 'write', db)
|
||||
or has_public_write_access_grant(note.access_grants)
|
||||
)
|
||||
|
||||
@@ -472,16 +439,7 @@ async def get_note_chat_by_id(
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if user.role != 'admin' and (
|
||||
user.id != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
chat = await Chats.get_internal_chat_by_note_id(note.id, user.id, db=db)
|
||||
@@ -556,16 +514,7 @@ async def get_note_chats_by_id(
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if user.role != 'admin' and (
|
||||
user.id != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
chats = await Chats.get_internal_chats_by_note_id(note.id, user.id, db=db)
|
||||
@@ -608,16 +557,7 @@ async def create_note_chat_by_id(
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if user.role != 'admin' and (
|
||||
user.id != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
chat_id = str(uuid4())
|
||||
@@ -670,16 +610,7 @@ async def update_note_by_id(
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if user.role != 'admin' and (
|
||||
user.id != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='write',
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'write', db):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
if form_data.data and not await has_access_to_note_files(
|
||||
@@ -795,6 +726,49 @@ async def update_note_access_by_id(
|
||||
return note
|
||||
|
||||
|
||||
# Update Note Folder By Id
|
||||
|
||||
|
||||
class NoteFolderIdForm(BaseModel):
|
||||
folder_id: Optional[str] = None
|
||||
|
||||
|
||||
@router.post('/{id}/folder', response_model=Optional[NoteModel])
|
||||
async def update_note_folder_id_by_id(
|
||||
request: Request,
|
||||
id: str,
|
||||
form_data: NoteFolderIdForm,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await check_notes_access(user, db=db)
|
||||
|
||||
note = await Notes.get_note_by_id(id, db=db)
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if note.user_id != user.id and not await has_folder_move_access(
|
||||
user.id, note.folder_id, form_data.folder_id, db=db
|
||||
):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
# None is allowed: it moves the note out of any folder.
|
||||
if form_data.folder_id is not None and not await has_folder_write_access(user.id, form_data.folder_id, db=db):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
note = await Notes.update_note_folder_id_by_id(id, form_data.folder_id, db=db)
|
||||
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
|
||||
note.is_pinned = note.id in pinned_note_ids
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.NOTE_FOLDER_UPDATED,
|
||||
actor=user,
|
||||
subject_id=note.id,
|
||||
data={'folder_id': form_data.folder_id},
|
||||
)
|
||||
return note
|
||||
|
||||
|
||||
# Pin Note By Id
|
||||
|
||||
|
||||
@@ -811,16 +785,7 @@ async def pin_note_by_id(
|
||||
if not note:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
if user.role != 'admin' and (
|
||||
user.id != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
note = await Notes.toggle_note_pinned_by_id(id, user.id, db=db)
|
||||
@@ -865,14 +830,8 @@ async def delete_note_by_id(
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
try:
|
||||
previous = note
|
||||
page_rooms = [
|
||||
f'doc_note:{id}:page:{p["id"]}:{p.get("generation", 0)}' for p in normalize_pages(note.data)['pages']
|
||||
]
|
||||
note = await Notes.delete_note_by_id(id, db=db)
|
||||
await close_changed_note_documents(previous, None)
|
||||
for room in [f'note:{id}', f'doc_note:{id}', *page_rooms]:
|
||||
await sio.close_room(room)
|
||||
await Notes.delete_note_by_id(id, db=db)
|
||||
await close_note(note)
|
||||
|
||||
await publish_event(
|
||||
request,
|
||||
|
||||
@@ -323,7 +323,7 @@ async def search_workspace( # noqa: C901 — keep permission scoping and source
|
||||
SharedChat.updated_at,
|
||||
)
|
||||
|
||||
if 'note' in enabled and kind in ('all', 'note') and not scope and not chat_filtered:
|
||||
if 'note' in enabled and kind in ('all', 'note') and not scope.startswith('channel:') and not chat_filtered:
|
||||
pinned = select(PinnedNote.id).where(PinnedNote.note_id == Note.id, PinnedNote.user_id == user.id).exists()
|
||||
note_shared = (
|
||||
select(AccessGrant.id)
|
||||
@@ -334,10 +334,16 @@ async def search_workspace( # noqa: C901 — keep permission scoping and source
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
stmt = AccessGrants.has_permission_filter(
|
||||
select(Note, pinned, note_shared), Note, {'user_id': user.id, 'group_ids': groups}, 'note', 'read', db=db
|
||||
stmt = select(Note, pinned, note_shared).where(
|
||||
or_(
|
||||
Note.user_id == user.id,
|
||||
AccessGrants.has_grant_expression(user.id, 'note', Note.id, 'read', groups),
|
||||
Note.folder_id.in_(select(folders.c.id)),
|
||||
),
|
||||
sharing_filter(Note.user_id),
|
||||
)
|
||||
stmt = stmt.where(sharing_filter(Note.user_id))
|
||||
if scope:
|
||||
stmt = stmt.where(Note.folder_id.in_(scoped_folders))
|
||||
stmt = apply_match(
|
||||
stmt, Note, func.coalesce(Note.data['search_text'].as_string(), Note.data['content']['md'].as_string())
|
||||
)
|
||||
@@ -440,15 +446,17 @@ async def search_workspace( # noqa: C901 — keep permission scoping and source
|
||||
elif match.source == 'note':
|
||||
page = matching_page(item.data, query)
|
||||
content = page['content'].get('md', '')
|
||||
folder = folder_map.get(item.folder_id)
|
||||
is_shared = item.user_id != user.id or row[2] or item.folder_id in shared_folder_ids
|
||||
append_result(
|
||||
'note:' + item.id,
|
||||
'note',
|
||||
item.title,
|
||||
'Shared note' if item.user_id != user.id or row[2] else 'Personal note',
|
||||
folder.name if folder else ('Shared note' if is_shared else 'Personal note'),
|
||||
content if isinstance(content, str) else '',
|
||||
'/notes/' + item.id + '?' + urlencode({'page': page['id'], 'search': query}),
|
||||
match.updated_at,
|
||||
item.user_id != user.id or row[2],
|
||||
is_shared,
|
||||
row[1],
|
||||
match.rank,
|
||||
)
|
||||
|
||||
@@ -35,7 +35,6 @@ from open_webui.env import (
|
||||
WEBSOCKET_SERVER_PING_INTERVAL,
|
||||
WEBSOCKET_SERVER_PING_TIMEOUT,
|
||||
)
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.channels import Channels
|
||||
from open_webui.models.chat_messages import ChatMessages
|
||||
from open_webui.models.chats import Chats
|
||||
@@ -56,6 +55,7 @@ from open_webui.tasks import (
|
||||
)
|
||||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.utils.access_control.files import has_access_to_note_files
|
||||
from open_webui.utils.access_control.notes import has_note_access
|
||||
from open_webui.utils.auth import get_verified_user_by_token
|
||||
from open_webui.utils.chat_id import is_saved_chat_id, is_temporary_chat_id
|
||||
from open_webui.utils.json_codec import SOCKETIO_JSON, JSONCodec, dumps_bytes
|
||||
@@ -734,6 +734,29 @@ async def refresh_chat_access(chat_id=None):
|
||||
await publish_chat_presence(cid)
|
||||
|
||||
|
||||
async def refresh_note_access(note_id=None):
|
||||
"""Make users who lost access to notes they have open, e.g. through a folder, leave their rooms."""
|
||||
user_ids_by_note: dict[str, set[str]] = {}
|
||||
for batch in get_session_pool_batches():
|
||||
for _, session in batch:
|
||||
for id in (session or {}).get('note_ids') or []:
|
||||
if not note_id or id == note_id:
|
||||
user_ids_by_note.setdefault(id, set()).add(session['id'])
|
||||
|
||||
for id, user_ids in user_ids_by_note.items():
|
||||
note = await Notes.get_note_by_id(id)
|
||||
if not note:
|
||||
continue
|
||||
users = await Users.get_users_by_user_ids(list(user_ids))
|
||||
revoked = [
|
||||
user.id for user in users if user.role != 'admin' and not await has_note_access(user.id, note, 'read')
|
||||
]
|
||||
if not revoked:
|
||||
continue
|
||||
for room in note_rooms(note):
|
||||
await leave_room_for_users(room, revoked)
|
||||
|
||||
|
||||
@sio.on('heartbeat')
|
||||
async def heartbeat(sid, data):
|
||||
user = await get_socket_session_user(sid)
|
||||
@@ -796,16 +819,7 @@ async def join_note(sid, data):
|
||||
log.error(f'Note {data["note_id"]} not found for user {user.id}')
|
||||
return
|
||||
|
||||
if (
|
||||
user.role != 'admin'
|
||||
and user.id != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
)
|
||||
):
|
||||
if user.role != 'admin' and not await has_note_access(user.id, note, 'read'):
|
||||
log.error(f'User {user.id} does not have access to note {data["note_id"]}')
|
||||
return
|
||||
|
||||
@@ -984,6 +998,22 @@ def normalize_document_id(document_id: str) -> str:
|
||||
return document_id
|
||||
|
||||
|
||||
def note_rooms(note) -> list[str]:
|
||||
pages = normalize_pages(note.data)['pages']
|
||||
return [
|
||||
f'note:{note.id}',
|
||||
f'doc_note:{note.id}',
|
||||
*[f'doc_note:{note.id}:page:{page["id"]}:{page.get("generation", 0)}' for page in pages],
|
||||
]
|
||||
|
||||
|
||||
async def close_note(note):
|
||||
"""Close a deleted note's documents and rooms."""
|
||||
await close_changed_note_documents(note, None)
|
||||
for room in note_rooms(note):
|
||||
await sio.close_room(room)
|
||||
|
||||
|
||||
async def close_changed_note_documents(previous, current):
|
||||
remaining = {p['id']: p.get('generation', 0) for p in normalize_pages(current.data)['pages']} if current else {}
|
||||
for page in normalize_pages(previous.data)['pages']:
|
||||
@@ -1035,16 +1065,7 @@ async def ydoc_document_join(sid, data):
|
||||
return
|
||||
page = document_page(note.data, document_id)
|
||||
|
||||
if (
|
||||
user.get('role') != 'admin'
|
||||
and user.get('id') != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.get('id'),
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
)
|
||||
):
|
||||
if user.get('role') != 'admin' and not await has_note_access(user.get('id'), note, 'read'):
|
||||
log.error(f'User {user.get("id")} does not have access to note {note_id}')
|
||||
return
|
||||
else:
|
||||
@@ -1130,16 +1151,7 @@ async def document_save_handler(document_id, data, user):
|
||||
log.error(f'Note {note_id} not found')
|
||||
return
|
||||
|
||||
if (
|
||||
user.get('role') != 'admin'
|
||||
and user.get('id') != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.get('id'),
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='write',
|
||||
)
|
||||
):
|
||||
if user.get('role') != 'admin' and not await has_note_access(user.get('id'), note, 'write'):
|
||||
log.error(f'User {user.get("id")} does not have write access to note {note_id}')
|
||||
return
|
||||
|
||||
@@ -1249,16 +1261,7 @@ async def yjs_document_update(sid, data):
|
||||
return
|
||||
page = document_page(note.data, document_id)
|
||||
|
||||
if (
|
||||
user.get('role') != 'admin'
|
||||
and user.get('id') != note.user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user.get('id'),
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='write',
|
||||
)
|
||||
):
|
||||
if user.get('role') != 'admin' and not await has_note_access(user.get('id'), note, 'write'):
|
||||
log.warning(f'User {user.get("id")} does not have write access to note {note_id}. Rejecting update.')
|
||||
return
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ from open_webui.socket.main import close_changed_note_documents, sio
|
||||
from open_webui.tools.visualizations import render_visualization # noqa: F401 — re-exported
|
||||
from open_webui.tools.knowledge_fs import kb_exec # noqa: F401 — re-exported
|
||||
from open_webui.utils.access_control.files import has_access_to_note_files
|
||||
from open_webui.utils.access_control.notes import has_note_access
|
||||
from open_webui.utils.chat_id import is_saved_chat_id
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.notifications import notify_target
|
||||
@@ -83,22 +84,6 @@ log = logging.getLogger(__name__)
|
||||
MAX_KNOWLEDGE_BASE_SEARCH_ITEMS = 10_000
|
||||
|
||||
|
||||
async def _has_write_access_to_note(note, user_id: str) -> bool:
|
||||
if note.user_id == user_id:
|
||||
return True
|
||||
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
|
||||
user_group_ids = [group.id for group in await Groups.get_groups_by_member_id(user_id, include_inherited=True)]
|
||||
return await AccessGrants.has_access(
|
||||
user_id=user_id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='write',
|
||||
user_group_ids=set(user_group_ids),
|
||||
)
|
||||
|
||||
|
||||
async def _emit_note_updated(request: Request, user: dict, note) -> None:
|
||||
await sio.emit('events', {'data': {'type': 'note:updated', 'data': note.model_dump()}}, to=f'note:{note.id}')
|
||||
await publish_event(
|
||||
@@ -1378,21 +1363,7 @@ async def view_note(
|
||||
|
||||
# Check access permission
|
||||
user_id = __user__.get('id')
|
||||
user_group_ids = [group.id for group in await Groups.get_groups_by_member_id(user_id, include_inherited=True)]
|
||||
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
|
||||
if (
|
||||
__user__.get('role') != 'admin'
|
||||
and note.user_id != user_id
|
||||
and not await AccessGrants.has_access(
|
||||
user_id=user_id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
user_group_ids=set(user_group_ids),
|
||||
)
|
||||
):
|
||||
if __user__.get('role') != 'admin' and not await has_note_access(user_id, note, 'read'):
|
||||
return JSONCodec.dumps({'error': 'Access denied'})
|
||||
|
||||
page = get_page(note.data, page_id) if page_id or len(note.data['pages']) == 1 else None
|
||||
@@ -1525,7 +1496,7 @@ async def replace_note_content(
|
||||
return JSONCodec.dumps({'error': 'Note not found', 'code': 'not_found'})
|
||||
|
||||
user_id = __user__.get('id')
|
||||
if __user__.get('role') != 'admin' and not await _has_write_access_to_note(note, user_id):
|
||||
if __user__.get('role') != 'admin' and not await has_note_access(user_id, note, 'write'):
|
||||
return JSONCodec.dumps({'error': 'Write access denied', 'code': 'write_access_denied'})
|
||||
|
||||
page = get_page(note.data, page_id)
|
||||
@@ -3453,16 +3424,7 @@ async def list_knowledge(
|
||||
|
||||
elif item_type == 'note':
|
||||
note = await Notes.get_note_by_id(item_id)
|
||||
if note and (
|
||||
user_role == 'admin'
|
||||
or note.user_id == user_id
|
||||
or await AccessGrants.has_access(
|
||||
user_id=user_id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
)
|
||||
):
|
||||
if note and (user_role == 'admin' or await has_note_access(user_id, note, 'read')):
|
||||
notes.append(
|
||||
{
|
||||
'id': note.id,
|
||||
@@ -3581,16 +3543,7 @@ async def query_knowledge_files(
|
||||
elif item_type == 'note':
|
||||
# Note - always return full content as context
|
||||
note = await Notes.get_note_by_id(item_id)
|
||||
if note and (
|
||||
user_role == 'admin'
|
||||
or note.user_id == user_id
|
||||
or await AccessGrants.has_access(
|
||||
user_id=user_id,
|
||||
resource_type='note',
|
||||
resource_id=note.id,
|
||||
permission='read',
|
||||
)
|
||||
):
|
||||
if note and (user_role == 'admin' or await has_note_access(user_id, note, 'read')):
|
||||
content = note.data.get('content', {}).get('md', '')
|
||||
note_results.append(
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@ from open_webui.models.knowledge import Knowledges
|
||||
from open_webui.models.models import Models
|
||||
from open_webui.models.notes import NoteModel, Notes, get_note_files
|
||||
from open_webui.models.users import UserModel, Users
|
||||
from open_webui.utils.access_control.notes import has_note_access
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -130,6 +131,10 @@ async def has_access_to_file(
|
||||
db=db,
|
||||
):
|
||||
return True
|
||||
for note_id in note_ids:
|
||||
note = await Notes.get_note_by_id(note_id, db=db)
|
||||
if note and note.folder_id and await has_note_access(user.id, note, 'read', db):
|
||||
return True
|
||||
|
||||
# Check if the file is directly attached to a shared workspace model (per the ownership
|
||||
# note above, model write is conferred only for files the model owner owns).
|
||||
@@ -190,19 +195,8 @@ async def get_accessible_folder_files(
|
||||
):
|
||||
accessible.append(entry)
|
||||
elif entry_type == 'note':
|
||||
# Owner has no self-grant (notes are private by default), so check ownership too.
|
||||
note = await Notes.get_note_by_id(entry_id, db=db)
|
||||
if note and (
|
||||
note.user_id == user.id
|
||||
or await AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type='note',
|
||||
resource_id=entry_id,
|
||||
permission='read',
|
||||
user_group_ids=user_group_ids,
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
if note and await has_note_access(user.id, note, 'read', db):
|
||||
accessible.append(entry)
|
||||
return accessible
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.folders import FolderModel, Folders
|
||||
from open_webui.models.folders import Folder, FolderModel, Folders
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
@@ -34,10 +35,21 @@ async def has_folder_write_access(user_id: str, folder_id: str, db: AsyncSession
|
||||
return await has_folder_access(user_id, folder, 'write', db)
|
||||
|
||||
|
||||
async def has_chat_move_access(
|
||||
def accessible_folder_ids(user_id: str, group_ids, permission: str = 'read'):
|
||||
"""Select of the folders has_folder_access allows, for filtering lists in SQL."""
|
||||
granted = AccessGrants.has_grant_expression(user_id, 'folder', Folder.id, permission, group_ids)
|
||||
# UNION (not UNION ALL) terminates even if a parent loop exists.
|
||||
folders = (
|
||||
select(Folder.id).where(or_(Folder.user_id == user_id, granted)).cte(f'{permission}_folders', recursive=True)
|
||||
)
|
||||
folders = folders.union(select(Folder.id).join(folders, Folder.parent_id == folders.c.id))
|
||||
return select(folders.c.id)
|
||||
|
||||
|
||||
async def has_folder_move_access(
|
||||
user_id: str, source_folder_id: str | None, target_folder_id: str | None, db: AsyncSession | None = None
|
||||
) -> bool:
|
||||
"""Only the owner may reorganize another user's chat within the same folder tree."""
|
||||
"""Only the owner may reorganize another user's chat or note within the same folder tree."""
|
||||
|
||||
async def get_owned_folder_root_id(folder_id):
|
||||
seen_ids = set()
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.folders import Folders
|
||||
from open_webui.utils.access_control.folders import has_folder_access
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def has_note_access(user_id: str, note, permission: str = 'read', db: AsyncSession | None = None) -> bool:
|
||||
"""Owner, a direct grant, or the same permission on the note's folder."""
|
||||
if note.user_id == user_id:
|
||||
return True
|
||||
if await AccessGrants.has_access(
|
||||
user_id=user_id, resource_type='note', resource_id=note.id, permission=permission, db=db
|
||||
):
|
||||
return True
|
||||
if note.folder_id:
|
||||
folder = await Folders.get_folder_by_id(note.folder_id, db=db)
|
||||
return bool(folder) and await has_folder_access(user_id, folder, permission, db)
|
||||
return False
|
||||
@@ -8,6 +8,7 @@ from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.utils.access_control.notes import has_note_access
|
||||
from sqlalchemy import select
|
||||
|
||||
|
||||
@@ -74,7 +75,11 @@ async def comment_resource(resource_type, resource_id, user, db, *, lock=False,
|
||||
allowed = (
|
||||
allowed
|
||||
or (user.role == 'admin' and (resource_type == 'note' or BYPASS_ADMIN_ACCESS_CONTROL))
|
||||
or await AccessGrants.has_access(user.id, resource_type, resource_id, 'read', db=db)
|
||||
or (
|
||||
await has_note_access(user.id, resource, 'read', db)
|
||||
if resource_type == 'note'
|
||||
else await AccessGrants.has_access(user.id, resource_type, resource_id, 'read', db=db)
|
||||
)
|
||||
)
|
||||
if not allowed:
|
||||
raise HTTPException(404, 'Resource not found')
|
||||
|
||||
@@ -115,6 +115,13 @@ async def resource_queries(user, db):
|
||||
)
|
||||
|
||||
models = source_models()
|
||||
# UNION (not UNION ALL) terminates even if legacy folder data contains a cycle.
|
||||
folders = (
|
||||
select(Folder.id)
|
||||
.where(or_(Folder.user_id == user.id, grant('folder', Folder.id)))
|
||||
.cte('inbox_folders', recursive=True)
|
||||
)
|
||||
folders = folders.union(select(Folder.id).join(folders, Folder.parent_id == folders.c.id))
|
||||
queries = {}
|
||||
for kind in ('model', 'knowledge', 'prompt', 'skill', 'tool', 'note'):
|
||||
if not config.get('comments.enable') or (kind == 'note' and not await enabled('notes')):
|
||||
@@ -125,15 +132,10 @@ async def resource_queries(user, db):
|
||||
if admin and (kind == 'note' or BYPASS_ADMIN_ACCESS_CONTROL)
|
||||
else or_(model.user_id == user.id, grant(kind, model.id))
|
||||
)
|
||||
if kind == 'note':
|
||||
allowed = or_(allowed, model.folder_id.in_(select(folders.c.id)))
|
||||
queries[kind] = select(model.id).where(allowed)
|
||||
chat = models['chat']
|
||||
# UNION (not UNION ALL) terminates even if legacy folder data contains a cycle.
|
||||
folders = (
|
||||
select(Folder.id)
|
||||
.where(or_(Folder.user_id == user.id, grant('folder', Folder.id)))
|
||||
.cte('inbox_folders', recursive=True)
|
||||
)
|
||||
folders = folders.union(select(Folder.id).join(folders, Folder.parent_id == folders.c.id))
|
||||
shared = select(SharedChat.chat_id).where(
|
||||
SharedChat.chat['share_mode'].as_string() == 'continue', grant('shared_chat', SharedChat.chat_id)
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user