From be972cd532965c876f8fa53ab42847caa542447a Mon Sep 17 00:00:00 2001 From: Andrei Duvakin Date: Thu, 6 Feb 2025 20:44:07 +0500 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=BE=D1=87=D0=B8=D0=BD=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D1=83=D1=80=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8E=20=D0=B1=D0=B0=D0=B7=D1=8B=20=D0=B8=20=D0=B8=D0=B7?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D0=B8=D0=BB=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8?= =?UTF-8?q?=D1=81=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82?= =?UTF-8?q?=D0=B5=D0=BB=D1=8F=20=D0=BD=D0=B0=20=D0=B0=D1=81=D0=B8=D0=BD?= =?UTF-8?q?=D1=85=D1=80=D0=BE=D0=BD=D0=BD=D1=8B=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/app/application/users_repository.py | 33 +++++++++-------- api/app/controllers/auth_routes.py | 36 ++++++++++++++----- ...87eaaa57_починил_внешние_ключи_у_таблиц.py | 32 +++++++++++++++++ .../61aeb99662ba_initial_migrationa.py | 32 +++++++++++++++++ api/app/domain/entities/auth.py | 5 +-- .../domain/models/mailing_delivery_methods.py | 2 +- api/app/domain/models/mailing_options.py | 4 +-- api/app/domain/models/patients.py | 2 +- api/app/domain/models/recipients.py | 4 +-- api/app/infrastructure/auth_service.py | 2 +- api/app/main.py | 31 ++++++++++++++-- api/app/run.py | 14 -------- api/app/settings.py | 11 +++--- 13 files changed, 153 insertions(+), 55 deletions(-) create mode 100644 api/app/database/migrations/versions/463487eaaa57_починил_внешние_ключи_у_таблиц.py create mode 100644 api/app/database/migrations/versions/61aeb99662ba_initial_migrationa.py delete mode 100644 api/app/run.py diff --git a/api/app/application/users_repository.py b/api/app/application/users_repository.py index 2357e85..fbc0fd3 100644 --- a/api/app/application/users_repository.py +++ b/api/app/application/users_repository.py @@ -1,4 +1,5 @@ from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select from sqlalchemy.orm import joinedload from app.domain.models.users import User @@ -8,26 +9,28 @@ class UsersRepository: def __init__(self, db: AsyncSession): self.db = db - def get_all(self): - return self.db.query(User).all() + async def get_all(self): + stmt = select(User) + result = await self.db.execute(stmt) + return result.scalars().all() - def get_by_id(self, user_id: int): - return self.db.query(User).filter(User.id == user_id).first() + async def get_by_id(self, user_id: int): + stmt = select(User).filter(User.id == user_id) + result = await self.db.execute(stmt) + return result.scalars().first() - def get_by_login(self, user_login: str): - return ( - self.db - .query(User) + async def get_by_login(self, user_login: str): + stmt = ( + select(User) .filter(User.login == user_login) - .options( - joinedload(User.role) - ) - .first() + .options(joinedload(User.role)) ) + result = await self.db.execute(stmt) + return result.scalars().first() - def create(self, user: User): + async def create(self, user: User): self.db.add(user) - self.db.commit() - self.db.refresh(user) + await self.db.commit() + await self.db.refresh(user) return user diff --git a/api/app/controllers/auth_routes.py b/api/app/controllers/auth_routes.py index 4ea1eeb..49e9a77 100644 --- a/api/app/controllers/auth_routes.py +++ b/api/app/controllers/auth_routes.py @@ -1,7 +1,5 @@ -from fastapi import APIRouter, Depends, HTTPException -from fastapi.openapi.models import Response +from fastapi import APIRouter, Depends, HTTPException, Response, status from sqlalchemy.ext.asyncio import AsyncSession -from starlette import status from app.database.session import get_db from app.domain.entities.auth import AuthEntity @@ -10,18 +8,38 @@ from app.infrastructure.auth_service import AuthService router = APIRouter() -@router.post('/login/') -async def auth_user(response: Response, user_data: AuthEntity, db: AsyncSession = Depends(get_db)): +@router.post( + "/login/", + response_model=dict, + responses={401: {"description": "Неверный логин или пароль"}}, + summary="Аутентификация пользователя", + description="Производит вход пользователя и выдает `access_token` в `cookie`.", +) +async def auth_user( + response: Response, + user_data: AuthEntity, + db: AsyncSession = Depends(get_db) +): auth_service = AuthService(db) - check = await auth_service.authenticate_user(login=user_data.login, password=user_data.password) + + check = await auth_service.authenticate_user( + login=user_data.login, password=user_data.password + ) if check is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail='Неверный логин или пароль', + detail="Неверный логин или пароль", ) access_token = auth_service.create_access_token({"sub": str(check.id)}) - response.set_cookie(key="users_access_token", value=access_token, httponly=True) - return {'access_token': access_token, 'refresh_token': None} + response.set_cookie( + key="users_access_token", + value=access_token, + httponly=True, + samesite="Lax", + ) + + return {"access_token": access_token, "refresh_token": None} + diff --git a/api/app/database/migrations/versions/463487eaaa57_починил_внешние_ключи_у_таблиц.py b/api/app/database/migrations/versions/463487eaaa57_починил_внешние_ключи_у_таблиц.py new file mode 100644 index 0000000..4eed1b3 --- /dev/null +++ b/api/app/database/migrations/versions/463487eaaa57_починил_внешние_ключи_у_таблиц.py @@ -0,0 +1,32 @@ +"""Починил внешние ключи у таблиц + +Revision ID: 463487eaaa57 +Revises: 61aeb99662ba +Create Date: 2025-02-06 20:40:11.324094 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '463487eaaa57' +down_revision: Union[str, None] = '61aeb99662ba' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint('recipients_patient_id_fkey', 'recipients', type_='foreignkey') + op.create_foreign_key(None, 'recipients', 'patients', ['patient_id'], ['id']) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'recipients', type_='foreignkey') + op.create_foreign_key('recipients_patient_id_fkey', 'recipients', 'mailing_delivery_methods', ['patient_id'], ['id']) + # ### end Alembic commands ### diff --git a/api/app/database/migrations/versions/61aeb99662ba_initial_migrationa.py b/api/app/database/migrations/versions/61aeb99662ba_initial_migrationa.py new file mode 100644 index 0000000..7266c42 --- /dev/null +++ b/api/app/database/migrations/versions/61aeb99662ba_initial_migrationa.py @@ -0,0 +1,32 @@ +"""Initial migrationA + +Revision ID: 61aeb99662ba +Revises: f8f3f414b162 +Create Date: 2025-02-06 20:37:40.995282 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '61aeb99662ba' +down_revision: Union[str, None] = 'f8f3f414b162' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint('mailing_options_option_id_fkey', 'mailing_options', type_='foreignkey') + op.create_foreign_key(None, 'mailing_options', 'mailing_delivery_methods', ['option_id'], ['id']) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'mailing_options', type_='foreignkey') + op.create_foreign_key('mailing_options_option_id_fkey', 'mailing_options', 'patients', ['option_id'], ['id']) + # ### end Alembic commands ### diff --git a/api/app/domain/entities/auth.py b/api/app/domain/entities/auth.py index 83d11f1..fc3dd35 100644 --- a/api/app/domain/entities/auth.py +++ b/api/app/domain/entities/auth.py @@ -2,5 +2,6 @@ from pydantic import BaseModel, Field class AuthEntity(BaseModel): - login: str = Field(...) - password: str = Field(..., min_length=5) + login: str = Field(..., example="user@example.com") + password: str = Field(..., min_length=5, example="strongpassword") + diff --git a/api/app/domain/models/mailing_delivery_methods.py b/api/app/domain/models/mailing_delivery_methods.py index 3fce573..38dc20d 100644 --- a/api/app/domain/models/mailing_delivery_methods.py +++ b/api/app/domain/models/mailing_delivery_methods.py @@ -10,4 +10,4 @@ class MailingDeliveryMethod(Base): id = Column(Integer, primary_key=True, autoincrement=True) title = Column(VARCHAR(200), nullable=False) - mailing = relationship('MailingOption', back_populates='option') + mailing = relationship('MailingOption', back_populates='method') diff --git a/api/app/domain/models/mailing_options.py b/api/app/domain/models/mailing_options.py index 69c27b9..17cb992 100644 --- a/api/app/domain/models/mailing_options.py +++ b/api/app/domain/models/mailing_options.py @@ -9,8 +9,8 @@ class MailingOption(Base): id = Column(Integer, primary_key=True, autoincrement=True) - option_id = Column(Integer, ForeignKey('patients.id'), nullable=False) + option_id = Column(Integer, ForeignKey('mailing_delivery_methods.id'), nullable=False) mailing_id = Column(Integer, ForeignKey('mailing.id'), nullable=False) - option = relationship('Patient', back_populates='mailing') + method = relationship('MailingDeliveryMethod', back_populates='mailing') mailing = relationship('Mailing', back_populates='mailing_options') diff --git a/api/app/domain/models/patients.py b/api/app/domain/models/patients.py index bd60eb3..f133d8a 100644 --- a/api/app/domain/models/patients.py +++ b/api/app/domain/models/patients.py @@ -20,4 +20,4 @@ class Patient(Base): lens_issues = relationship('LensIssue', back_populates='patient') appointments = relationship('Appointment', back_populates='patient') - mailing = relationship('Mailing', back_populates='patient') + mailing = relationship('Recipient', back_populates='patient') diff --git a/api/app/domain/models/recipients.py b/api/app/domain/models/recipients.py index c850eee..03d8a19 100644 --- a/api/app/domain/models/recipients.py +++ b/api/app/domain/models/recipients.py @@ -9,8 +9,8 @@ class Recipient(Base): id = Column(Integer, primary_key=True, autoincrement=True) - patient_id = Column(Integer, ForeignKey('mailing_delivery_methods.id'), nullable=False) + patient_id = Column(Integer, ForeignKey('patients.id'), nullable=False) mailing_id = Column(Integer, ForeignKey('mailing.id'), nullable=False) - patient = relationship('MailingDeliveryMethod', back_populates='mailing') + patient = relationship('Patient', back_populates='mailing') mailing = relationship('Mailing', back_populates='recipients') diff --git a/api/app/infrastructure/auth_service.py b/api/app/infrastructure/auth_service.py index f6ebdfc..10d7b2e 100644 --- a/api/app/infrastructure/auth_service.py +++ b/api/app/infrastructure/auth_service.py @@ -1,6 +1,6 @@ import datetime -from jose import jwt +import jwt from sqlalchemy.ext.asyncio import AsyncSession from app.application.users_repository import UsersRepository diff --git a/api/app/main.py b/api/app/main.py index 0326539..b95ef02 100644 --- a/api/app/main.py +++ b/api/app/main.py @@ -1,4 +1,29 @@ -from app.run import start_app +from fastapi import FastAPI +from starlette.middleware.cors import CORSMiddleware -if __name__ == '__main__': - start_app() +from app.controllers.auth_routes import router as auth_router +from app.settings import settings + + +def start_app(): + api_app = FastAPI() + + api_app.add_middleware( + CORSMiddleware, + allow_origins=['*'], + allow_credentials=True, + allow_methods=['GET', 'POST', 'PUT', 'DELETE'], + allow_headers=['*'], + ) + + api_app.include_router(auth_router, prefix=settings.APP_PREFIX) + + return api_app + + +app = start_app() + + +@app.get("/") +async def root(): + return {"message": "OK"} diff --git a/api/app/run.py b/api/app/run.py deleted file mode 100644 index 72730f2..0000000 --- a/api/app/run.py +++ /dev/null @@ -1,14 +0,0 @@ -from fastapi import FastAPI -from starlette.middleware.cors import CORSMiddleware - - -def start_app(): - app = FastAPI() - - app.add_middleware( - CORSMiddleware, - allow_origins=['*'], - allow_credentials=True, - allow_methods=['GET', 'POST', 'PUT', 'DELETE'], - allow_headers=['*'], - ) diff --git a/api/app/settings.py b/api/app/settings.py index 80a1638..48cd631 100644 --- a/api/app/settings.py +++ b/api/app/settings.py @@ -3,18 +3,19 @@ from pydantic_settings import BaseSettings class Settings(BaseSettings): DATABASE_URL: str - LOG_LEVEL: str = "info" - LOG_FILE: str = "logs/app.log" + LOG_LEVEL: str = 'info' + LOG_FILE: str = 'logs/app.log' SECRET_KEY: str ALGORITHM: str + APP_PREFIX: str = '/api/v1' class Config: - env_file = ".env" - env_file_encoding = "utf-8" + env_file = '.env' + env_file_encoding = 'utf-8' settings = Settings() def get_auth_data(): - return {"secret_key": settings.SECRET_KEY, "algorithm": settings.ALGORITHM} + return {'secret_key': settings.SECRET_KEY, 'algorithm': settings.ALGORITHM}