Spaces:
Running on Zero
Running on Zero
File size: 2,366 Bytes
119c847 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | """
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})>"
)
|