feat(infrastructure): add basic project deployment

This commit is contained in:
2025-09-23 23:47:17 +02:00
parent c7d33465ca
commit f4c2b28864
16 changed files with 241 additions and 24 deletions

View File

@@ -1,11 +1,24 @@
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_user, fastapi_users
from .users import auth_backend, current_active_verified_user, fastapi_users
app = FastAPI()
# CORS for frontend dev server
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:5173",
"http://127.0.0.1:5173",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(
fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
)
@@ -32,7 +45,7 @@ app.include_router(
@app.get("/authenticated-route")
async def authenticated_route(user: User = Depends(current_active_user)):
async def authenticated_route(user: User = Depends(current_active_verified_user)):
return {"message": f"Hello {user.email}!"}

47
backend/app/queue.py Normal file
View File

@@ -0,0 +1,47 @@
import json
import os
from typing import Any, Dict
import asyncio
RABBITMQ_URL = os.getenv("RABBITMQ_URL") or (
f"amqp://{os.getenv('RABBITMQ_USERNAME', 'user')}:"
f"{os.getenv('RABBITMQ_PASSWORD', 'bitnami123')}@"
f"{os.getenv('RABBITMQ_HOST', 'localhost')}:"
f"{os.getenv('RABBITMQ_PORT', '5672')}"
)
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()
await channel.declare_queue(QUEUE_NAME, durable=True)
body = json.dumps(message).encode("utf-8")
await channel.default_exchange.publish(
aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT),
routing_key=QUEUE_NAME,
)
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))

View File

@@ -1,3 +1,4 @@
import os
import uuid
from typing import Optional
@@ -12,7 +13,9 @@ from fastapi_users.db import SQLAlchemyUserDatabase
from .db import User, get_user_db
SECRET = "SECRET"
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]):
@@ -20,7 +23,8 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
verification_token_secret = SECRET
async def on_after_register(self, user: User, request: Optional[Request] = None):
print(f"User {user.id} has registered.")
# 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(
self, user: User, token: str, request: Optional[Request] = None
@@ -30,7 +34,26 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
async def on_after_request_verify(
self, user: User, token: str, request: Optional[Request] = None
):
print(f"Verification requested for user {user.id}. Verification token: {token}")
# 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"
body = (
"Ahoj,\n\n"
"děkujeme za registraci. Prosíme, ověř svůj účet kliknutím na tento odkaz:\n"
f"{verify_frontend_link}\n\n"
"Pokud by odkaz nefungoval, můžeš použít i přímý odkaz na backend:\n"
f"{verify_backend_link}\n\n"
"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)):
@@ -53,3 +76,4 @@ auth_backend = AuthenticationBackend(
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)