cognee/cognee/modules/users/models/User.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

52 lines
1.4 KiB
Python

from uuid import UUID as uuid_UUID
from typing import Optional
from sqlalchemy import ForeignKey, Column, UUID
from sqlalchemy.orm import relationship, Mapped
from fastapi_users.db import SQLAlchemyBaseUserTableUUID
from .Principal import Principal
from .UserRole import UserRole
from .Role import Role
from fastapi_users import schemas
class User(SQLAlchemyBaseUserTableUUID, Principal):
__tablename__ = "users"
id = Column(UUID, ForeignKey("principals.id", ondelete="CASCADE"), primary_key=True)
# Foreign key to Tenant (Many-to-One relationship)
tenant_id = Column(UUID, ForeignKey("tenants.id"))
# Many-to-Many Relationship with Roles
roles: Mapped[list["Role"]] = relationship(
"Role",
secondary=UserRole.__tablename__,
back_populates="users",
)
# Relationship to Tenant
tenant = relationship(
"Tenant",
back_populates="users",
foreign_keys=[tenant_id],
)
# ACL Relationship (One-to-Many)
acls = relationship("ACL", back_populates="principal", cascade="all, delete")
__mapper_args__ = {
"polymorphic_identity": "user",
}
# Keep these schemas in sync with User model
class UserRead(schemas.BaseUser[uuid_UUID]):
tenant_id: Optional[uuid_UUID] = None
class UserCreate(schemas.BaseUserCreate):
tenant_id: Optional[uuid_UUID] = None
class UserUpdate(schemas.BaseUserUpdate):
pass