mirror of
https://github.com/dat515-2025/Group-8.git
synced 2026-03-22 23:20:56 +01:00
refactor(backend): refactor project, add database migrations support
This commit is contained in:
0
backend/app/api/.keep
Normal file
0
backend/app/api/.keep
Normal file
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
@@ -1,9 +1,10 @@
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from .db import User, create_db_and_tables
|
||||
from .schemas import UserCreate, UserRead, UserUpdate
|
||||
from .users import auth_backend, current_active_verified_user, fastapi_users
|
||||
from app.models.user import User
|
||||
|
||||
from app.schemas.user import UserCreate, UserRead, UserUpdate
|
||||
from app.services.user_service import auth_backend, current_active_verified_user, fastapi_users
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
@@ -53,9 +54,3 @@ async def root():
|
||||
@app.get("/authenticated-route")
|
||||
async def authenticated_route(user: User = Depends(current_active_verified_user)):
|
||||
return {"message": f"Hello {user.email}!"}
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def on_startup():
|
||||
# Not needed if you setup a migration system like Alembic
|
||||
await create_db_and_tables()
|
||||
|
||||
2
backend/app/core/.keep
Normal file
2
backend/app/core/.keep
Normal file
@@ -0,0 +1,2 @@
|
||||
# Konfigurace a utility
|
||||
|
||||
0
backend/app/core/__init__.py
Normal file
0
backend/app/core/__init__.py
Normal file
4
backend/app/core/base.py
Normal file
4
backend/app/core/base.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
|
||||
|
||||
Base: DeclarativeMeta = declarative_base()
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import os
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from fastapi import Depends
|
||||
from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
||||
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
from app.core.base import Base # Import Base z nového souboru
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_URL")
|
||||
if not DATABASE_URL:
|
||||
@@ -13,21 +9,20 @@ if not DATABASE_URL:
|
||||
mariadb_db = os.getenv("MARIADB_DB", "group_project")
|
||||
mariadb_user = os.getenv("MARIADB_USER", "root")
|
||||
mariadb_password = os.getenv("MARIADB_PASSWORD", "strongpassword")
|
||||
#always use SSL except for localhost - i dont want to include certs
|
||||
if mariadb_host and mariadb_db and mariadb_user and mariadb_password:
|
||||
# Use MariaDB/MySQL over async driver
|
||||
DATABASE_URL = f"mysql+asyncmy://{mariadb_user}:{mariadb_password}@{mariadb_host}:{mariadb_port}/{mariadb_db}"
|
||||
else:
|
||||
raise Exception("Only MariaDB is supported. Please set the DATABASE_URL environment variable.")
|
||||
|
||||
Base: DeclarativeMeta = declarative_base()
|
||||
# Explicitní import všech modelů, aby byly registrovány v Base.metadata
|
||||
from app.models.user import User
|
||||
from app.models.transaction import Transaction
|
||||
|
||||
from app.models.user import User
|
||||
|
||||
class User(SQLAlchemyBaseUserTableUUID, Base):
|
||||
pass
|
||||
# Pokud máš další modely, importuj je zde:
|
||||
# from app.models.other_model import OtherModel
|
||||
|
||||
|
||||
# Nastavení connect_args pro SSL pouze pokud není localhost
|
||||
ssl_enabled = os.getenv("MARIADB_HOST", "localhost") != "localhost"
|
||||
connect_args = {"ssl": {"ssl": True}} if ssl_enabled else {}
|
||||
|
||||
@@ -38,17 +33,3 @@ engine = create_async_engine(
|
||||
connect_args=connect_args,
|
||||
)
|
||||
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
|
||||
async def create_db_and_tables():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
|
||||
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_session_maker() as session:
|
||||
yield session
|
||||
|
||||
|
||||
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
|
||||
yield SQLAlchemyUserDatabase(session, User)
|
||||
@@ -1,7 +1,6 @@
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
import asyncio
|
||||
|
||||
RABBITMQ_URL = os.getenv("RABBITMQ_URL") or (
|
||||
@@ -12,11 +11,8 @@ RABBITMQ_URL = os.getenv("RABBITMQ_URL") or (
|
||||
)
|
||||
QUEUE_NAME = os.getenv("MAIL_QUEUE", "mail_queue")
|
||||
|
||||
|
||||
async def _publish_async(message: Dict[str, Any]) -> None:
|
||||
# Import locally to avoid hard dependency at import-time
|
||||
import aio_pika
|
||||
|
||||
connection = await aio_pika.connect_robust(RABBITMQ_URL)
|
||||
try:
|
||||
channel = await connection.channel()
|
||||
@@ -29,19 +25,12 @@ async def _publish_async(message: Dict[str, Any]) -> None:
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
def enqueue_email(to: str, subject: str, body: str) -> None:
|
||||
"""
|
||||
Enqueue an email to RabbitMQ. If RabbitMQ or aio_pika is not available,
|
||||
this function will raise ImportError/ConnectionError. The caller may
|
||||
implement fallback (e.g., direct send).
|
||||
"""
|
||||
message = {"type": "email", "to": to, "subject": subject, "body": body}
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
# Fire-and-forget task so we don't block the request path
|
||||
loop.create_task(_publish_async(message))
|
||||
except RuntimeError:
|
||||
# No running loop (e.g., called from sync context) – run a short loop
|
||||
asyncio.run(_publish_async(message))
|
||||
# ...existing code...
|
||||
|
||||
2
backend/app/models/.keep
Normal file
2
backend/app/models/.keep
Normal file
@@ -0,0 +1,2 @@
|
||||
# SQLAlchemy modely
|
||||
|
||||
0
backend/app/models/__init__.py
Normal file
0
backend/app/models/__init__.py
Normal file
9
backend/app/models/transaction.py
Normal file
9
backend/app/models/transaction.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from sqlalchemy import Column, Integer, String, Float
|
||||
from ..core.db import Base
|
||||
|
||||
class Transaction(Base):
|
||||
__tablename__ = "transaction"
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
amount = Column(Float, nullable=False)
|
||||
description = Column(String(length=255), nullable=True)
|
||||
|
||||
7
backend/app/models/user.py
Normal file
7
backend/app/models/user.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from sqlalchemy import Column, String
|
||||
from fastapi_users.db import SQLAlchemyBaseUserTableUUID
|
||||
from ..core.base import Base # Import Base z base.py
|
||||
|
||||
class User(SQLAlchemyBaseUserTableUUID, Base):
|
||||
first_name = Column(String(length=100), nullable=True)
|
||||
last_name = Column(String(length=100), nullable=True)
|
||||
@@ -1,15 +0,0 @@
|
||||
import uuid
|
||||
|
||||
from fastapi_users import schemas
|
||||
|
||||
|
||||
class UserRead(schemas.BaseUser[uuid.UUID]):
|
||||
pass
|
||||
|
||||
|
||||
class UserCreate(schemas.BaseUserCreate):
|
||||
pass
|
||||
|
||||
|
||||
class UserUpdate(schemas.BaseUserUpdate):
|
||||
pass
|
||||
2
backend/app/schemas/.keep
Normal file
2
backend/app/schemas/.keep
Normal file
@@ -0,0 +1,2 @@
|
||||
# Pydantic schémata
|
||||
|
||||
0
backend/app/schemas/__init__.py
Normal file
0
backend/app/schemas/__init__.py
Normal file
16
backend/app/schemas/user.py
Normal file
16
backend/app/schemas/user.py
Normal file
@@ -0,0 +1,16 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
from fastapi_users import schemas
|
||||
|
||||
class UserRead(schemas.BaseUser[uuid.UUID]):
|
||||
first_name: Optional[str] = None
|
||||
surname: Optional[str] = None
|
||||
|
||||
class UserCreate(schemas.BaseUserCreate):
|
||||
first_name: Optional[str] = None
|
||||
surname: Optional[str] = None
|
||||
|
||||
class UserUpdate(schemas.BaseUserUpdate):
|
||||
first_name: Optional[str] = None
|
||||
surname: Optional[str] = None
|
||||
|
||||
2
backend/app/services/.keep
Normal file
2
backend/app/services/.keep
Normal file
@@ -0,0 +1,2 @@
|
||||
# Business logika
|
||||
|
||||
0
backend/app/services/__init__.py
Normal file
0
backend/app/services/__init__.py
Normal file
14
backend/app/services/db.py
Normal file
14
backend/app/services/db.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from typing import AsyncGenerator
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from fastapi_users.db import SQLAlchemyUserDatabase
|
||||
|
||||
from ..core.db import async_session_maker
|
||||
from ..models.user import User
|
||||
|
||||
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_session_maker() as session:
|
||||
yield session
|
||||
|
||||
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
|
||||
yield SQLAlchemyUserDatabase(session, User)
|
||||
@@ -11,19 +11,19 @@ from fastapi_users.authentication import (
|
||||
)
|
||||
from fastapi_users.db import SQLAlchemyUserDatabase
|
||||
|
||||
from .db import User, get_user_db
|
||||
from ..models.user import User
|
||||
from ..services.db import get_user_db
|
||||
from ..core.queue import enqueue_email
|
||||
|
||||
SECRET = os.getenv("SECRET", "CHANGE_ME_SECRET")
|
||||
FRONTEND_URL = os.getenv("FRONTEND_URL", "http://localhost:5173")
|
||||
BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:8000")
|
||||
|
||||
|
||||
class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
reset_password_token_secret = SECRET
|
||||
verification_token_secret = SECRET
|
||||
|
||||
async def on_after_register(self, user: User, request: Optional[Request] = None):
|
||||
# Ask FastAPI Users to generate a verification token and trigger the hook below
|
||||
await self.request_verify(user, request)
|
||||
|
||||
async def on_after_forgot_password(
|
||||
@@ -34,7 +34,6 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
async def on_after_request_verify(
|
||||
self, user: User, token: str, request: Optional[Request] = None
|
||||
):
|
||||
# Build verification email and send through RabbitMQ (with direct SMTP fallback)
|
||||
verify_frontend_link = f"{FRONTEND_URL}/verify?token={token}"
|
||||
verify_backend_link = f"{BACKEND_URL}/auth/verify?token={token}"
|
||||
subject = "Ověření účtu"
|
||||
@@ -47,26 +46,20 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
"Pokud jsi registraci neprováděl(a), tento email ignoruj.\n"
|
||||
)
|
||||
try:
|
||||
from .queue import enqueue_email
|
||||
enqueue_email(to=user.email, subject=subject, body=body)
|
||||
except Exception:
|
||||
# Fallback: if queue is unavailable, log the email content (dev fallback)
|
||||
print("[Email Fallback] To:", user.email)
|
||||
print("[Email Fallback] Subject:", subject)
|
||||
print("[Email Fallback] Body:\n", body)
|
||||
|
||||
|
||||
async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
|
||||
yield UserManager(user_db)
|
||||
|
||||
|
||||
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
|
||||
|
||||
|
||||
def get_jwt_strategy() -> JWTStrategy:
|
||||
return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
|
||||
|
||||
|
||||
auth_backend = AuthenticationBackend(
|
||||
name="jwt",
|
||||
transport=bearer_transport,
|
||||
@@ -77,3 +70,4 @@ fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])
|
||||
|
||||
current_active_user = fastapi_users.current_user(active=True)
|
||||
current_active_verified_user = fastapi_users.current_user(active=True, verified=True)
|
||||
|
||||
2
backend/app/workers/.keep
Normal file
2
backend/app/workers/.keep
Normal file
@@ -0,0 +1,2 @@
|
||||
# Background worker
|
||||
|
||||
0
backend/app/workers/__init__.py
Normal file
0
backend/app/workers/__init__.py
Normal file
Reference in New Issue
Block a user