diff --git a/backend/alembic/versions/79acd316403a_add_api_key_table.py b/backend/alembic/versions/79acd316403a_add_api_key_table.py new file mode 100644 index 000000000000..e8b0885fdae9 --- /dev/null +++ b/backend/alembic/versions/79acd316403a_add_api_key_table.py @@ -0,0 +1,46 @@ +"""Add api_key table +Revision ID: 79acd316403a +Revises: 904e5138fffb +Create Date: 2024-01-11 17:56:37.934381 +""" +from alembic import op +import fastapi_users_db_sqlalchemy +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = "79acd316403a" +down_revision = "904e5138fffb" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "api_key", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("hashed_api_key", sa.String(), nullable=False), + sa.Column("api_key_display", sa.String(), nullable=False), + sa.Column( + "user_id", + fastapi_users_db_sqlalchemy.generics.GUID(), + nullable=False, + ), + sa.Column( + "owner_id", + fastapi_users_db_sqlalchemy.generics.GUID(), + nullable=True, + ), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("api_key_display"), + sa.UniqueConstraint("hashed_api_key"), + ) + + +def downgrade() -> None: + op.drop_table("api_key") diff --git a/backend/danswer/db/models.py b/backend/danswer/db/models.py index dabe66d21128..e2f1f52c7d8e 100644 --- a/backend/danswer/db/models.py +++ b/backend/danswer/db/models.py @@ -97,6 +97,21 @@ class AccessToken(SQLAlchemyBaseAccessTokenTableUUID, Base): pass +class ApiKey(Base): + __tablename__ = "api_key" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + hashed_api_key: Mapped[str] = mapped_column(String, unique=True) + api_key_display: Mapped[str] = mapped_column(String, unique=True) + # the ID of the "user" who represents the access credentials for the API key + user_id: Mapped[UUID] = mapped_column(ForeignKey("user.id"), nullable=False) + # the ID of the user who owns the key + owner_id: Mapped[UUID | None] = mapped_column(ForeignKey("user.id"), nullable=True) + created_at: Mapped[datetime.datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now() + ) + + """ Association Tables NOTE: must be at the top since they are referenced by other tables diff --git a/backend/requirements/dev.txt b/backend/requirements/dev.txt index c59796bb7bcb..e855436db4ec 100644 --- a/backend/requirements/dev.txt +++ b/backend/requirements/dev.txt @@ -10,6 +10,7 @@ types-beautifulsoup4==4.12.0.3 types-html5lib==1.1.11.13 types-oauthlib==3.2.0.9 types-setuptools==68.0.0.3 +types-passlib==1.7.7.20240106 types-psutil==5.9.5.17 types-psycopg2==2.9.21.10 types-python-dateutil==2.8.19.13