agrovia-detection-api / app /models /api_token.py
Kaaado's picture
feat: migrate full production detection service architecture with 8-model hub sync
119c847
Raw History Blame Contribute Delete
2.37 kB
"""
Detection Service — API Token ORM Model
Shares the same api_tokens table across services.
Enterprise DB-backed token system with scope, expiry, and per-token rate limiting.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from enum import Enum as PyEnum
from sqlalchemy import Boolean, DateTime, Integer, String, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ServiceScope(str, PyEnum):
"""Allowed service scopes for API tokens."""
DETECTION = "DETECTION"
CLASSIFICATION = "CLASSIFICATION"
DETECTION_AND_CLASSIFICATION = "DETECTION_AND_CLASSIFICATION"
CURE = "CURE"
DETECTION_AND_CURE = "DETECTION_AND_CURE"
CLASSIFICATION_AND_CURE = "CLASSIFICATION_AND_CURE"
FULL_ACCESS = "FULL_ACCESS"
class ApiToken(Base):
__tablename__ = "api_tokens"
id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
)
org_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), nullable=True
)
name: Mapped[str] = mapped_column(String(100), default="Default")
token_hash: Mapped[str] = mapped_column(
String(256), unique=True, index=True, nullable=False
)
token_prefix: Mapped[str] = mapped_column(String(12), nullable=False)
scope: Mapped[str] = mapped_column(
String(50), nullable=False, default=ServiceScope.FULL_ACCESS.value
)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
rate_limit_per_minute: Mapped[int] = mapped_column(
Integer, default=60, nullable=False
)
daily_quota: Mapped[int] = mapped_column(
Integer, default=1000, nullable=False
)
total_usage: Mapped[int] = mapped_column(
Integer, default=0, nullable=False
)
last_used_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=True
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
expires_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=True
)
def __repr__(self) -> str:
return (
f"<ApiToken(id={self.id}, scope={self.scope}, "
f"active={self.is_active})>"
)