cognee/cognee/modules/users/permissions/methods/check_permission_on_documents.py
Igor Ilic 88ed411f03
feat: user authorization [COG-1189] (#593)
<!-- .github/pull_request_template.md -->

## Description
Added user authorization through JWT header, reworked user and relevant
RBAC models to accompany future User Permission system.

## DCO Affirmation
I affirm that all code in every commit of this pull request conforms to
the terms of the Topoteretes Developer Certificate of Origin


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
  - Introduced an automated workflow to validate server startup.
  - Added secure JWT token generation for improved session handling.
- Enabled a new structure for permission management with role and
tenant-based controls, including endpoints for creating roles, tenants,
and assigning permissions.
- Added methods for assigning default permissions to roles, tenants, and
users.
- Introduced new classes for managing default permissions for roles,
tenants, and users.

- **Refactor**
- Streamlined authentication and user management flows with enhanced
error handling.

- **Tests**
- Upgraded integration tests with improved database initialization and
data pruning for a more stable environment.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Vasilije <8619304+Vasilije1990@users.noreply.github.com>
2025-03-13 13:33:42 +01:00

35 lines
1.2 KiB
Python

import logging
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.orm import joinedload
from cognee.modules.users.exceptions import PermissionDeniedError
from cognee.infrastructure.databases.relational import get_relational_engine
from ...models.User import User
from ...models.ACL import ACL
logger = logging.getLogger(__name__)
async def check_permission_on_documents(user: User, permission_type: str, document_ids: list[UUID]):
user_roles_ids = [role.id for role in user.roles]
db_engine = get_relational_engine()
async with db_engine.get_async_session() as session:
result = await session.execute(
select(ACL)
.join(ACL.permission)
.options(joinedload(ACL.data))
.where(ACL.principal_id.in_([user.id, *user_roles_ids]))
.where(ACL.permission.has(name=permission_type))
)
acls = result.unique().scalars().all()
data_ids = [acl.data.id for acl in acls]
has_permissions = all(document_id in data_ids for document_id in document_ids)
if not has_permissions:
raise PermissionDeniedError(
message=f"User {user.email} does not have {permission_type} permission on documents"
)