|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from datetime import datetime |
| 4 | +from typing import Optional |
| 5 | + |
| 6 | +from app.db.session import Base |
| 7 | +from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, Text |
| 8 | +from sqlalchemy.orm import Mapped, mapped_column, relationship |
| 9 | + |
| 10 | + |
| 11 | +class APIKey(Base): |
| 12 | + __tablename__ = "api_keys" |
| 13 | + |
| 14 | + id: Mapped[int] = mapped_column(Integer, primary_key=True) |
| 15 | + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) |
| 16 | + name: Mapped[str] = mapped_column(String(100)) |
| 17 | + # Store only a hash of the secret part; never the raw key |
| 18 | + secret_hash: Mapped[str] = mapped_column(String(128), unique=True, index=True) |
| 19 | + # Showable prefix to help users identify which key (e.g., "tsk_live_2f9a") |
| 20 | + prefix: Mapped[str] = mapped_column(String(32), index=True) |
| 21 | + scopes: Mapped[Optional[str]] = mapped_column(Text, nullable=True) # JSON-encoded list if you want |
| 22 | + expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), index=True) |
| 23 | + revoked: Mapped[bool] = mapped_column(Boolean, default=False) |
| 24 | + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=False), default=datetime.utcnow) |
| 25 | + revoked_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True) |
| 26 | + |
| 27 | + user = relationship("User", back_populates="api_keys") |
| 28 | + |
| 29 | + |
| 30 | +Index("ix_api_keys_user_active", APIKey.user_id, APIKey.revoked) |
0 commit comments