🐐
This commit is contained in:
0
backend/core/__init__.py
Normal file
0
backend/core/__init__.py
Normal file
48
backend/core/auth.py
Normal file
48
backend/core/auth.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from core.config import JWT_SECRET_KEY
|
||||
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
SECRET_KEY = JWT_SECRET_KEY
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||
REFRESH_TOKEN_EXPIRE_DAYS = 30
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"])
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
def create_access_token(user_id: str) -> str:
|
||||
expire = datetime.now() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
return jwt.encode({"sub": user_id, "exp": expire, "type": "access"}, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
def create_refresh_token(user_id: str) -> str:
|
||||
expire = datetime.now() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
|
||||
return jwt.encode({"sub": user_id, "exp": expire, "type": "refresh"}, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
def decode_refresh_token(token: str) -> str | None:
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
if payload.get("type") != "refresh":
|
||||
return None
|
||||
return payload.get("sub")
|
||||
except JWTError:
|
||||
return None
|
||||
|
||||
def decode_access_token(token: str) -> str | None:
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
if payload.get("type") != "access":
|
||||
return None
|
||||
return payload.get("sub")
|
||||
except JWTError:
|
||||
return None
|
||||
24
backend/core/config.py
Normal file
24
backend/core/config.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
|
||||
def require(key: str) -> str:
|
||||
value = os.environ.get(key)
|
||||
if not value:
|
||||
raise RuntimeError(f"Required environment variable {key} is not set")
|
||||
return value
|
||||
|
||||
def optional(key: str, default: str = "") -> str:
|
||||
return os.environ.get(key, default)
|
||||
|
||||
# Required
|
||||
JWT_SECRET_KEY = require("JWT_SECRET_KEY")
|
||||
DATABASE_URL = require("DATABASE_URL")
|
||||
RESEND_API_KEY = require("RESEND_API_KEY")
|
||||
EMAIL_FROM = require("EMAIL_FROM")
|
||||
STRIPE_SECRET_KEY = require("STRIPE_SECRET_KEY")
|
||||
STRIPE_PUBLISHABLE_KEY = require("STRIPE_PUBLISHABLE_KEY")
|
||||
STRIPE_WEBHOOK_SECRET = require("STRIPE_WEBHOOK_SECRET")
|
||||
|
||||
# Optional with sensible defaults for local dev
|
||||
FRONTEND_URL = optional("FRONTEND_URL", "http://localhost:5173")
|
||||
CORS_ORIGINS = optional("CORS_ORIGINS", "http://localhost:5173").split(",")
|
||||
WIKIRANK_USER_AGENT = optional("WIKIRANK_USER_AGENT", "WikiTCG/1.0")
|
||||
22
backend/core/database.py
Normal file
22
backend/core/database.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
||||
|
||||
from core.config import DATABASE_URL
|
||||
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
pool_timeout=30,
|
||||
)
|
||||
SessionLocal = sessionmaker(bind=engine)
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
43
backend/core/dependencies.py
Normal file
43
backend/core/dependencies.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from slowapi import Limiter
|
||||
from slowapi.util import get_remote_address
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.auth import decode_access_token
|
||||
from core.database import get_db
|
||||
from core.models import User as UserModel
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
|
||||
|
||||
# Shared rate limiter — registered on app.state in main.py
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> UserModel:
|
||||
user_id = decode_access_token(token)
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
user = db.query(UserModel).filter(UserModel.id == uuid.UUID(user_id)).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
||||
# Throttle to one write per 5 minutes so every authenticated request doesn't hammer the DB
|
||||
now = datetime.now()
|
||||
if not user.last_active_at or (now - user.last_active_at).total_seconds() > 300:
|
||||
user.last_active_at = now
|
||||
db.commit()
|
||||
return user
|
||||
|
||||
|
||||
# Per-user key for rate limiting authenticated endpoints — prevents shared IPs (NAT/VPN)
|
||||
# from having their limits pooled. Falls back to remote IP for unauthenticated requests.
|
||||
def get_user_id_from_request(request: Request) -> str:
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if auth.startswith("Bearer "):
|
||||
user_id = decode_access_token(auth[7:])
|
||||
if user_id:
|
||||
return f"user:{user_id}"
|
||||
return get_remote_address(request)
|
||||
189
backend/core/models.py
Normal file
189
backend/core/models.py
Normal file
@@ -0,0 +1,189 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import String, Integer, ForeignKey, DateTime, Text, Boolean, UniqueConstraint, CheckConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from sqlalchemy.dialects.postgresql import UUID, JSONB
|
||||
|
||||
from core.database import Base
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
username: Mapped[str] = mapped_column(String, unique=True, nullable=False)
|
||||
email: Mapped[str] = mapped_column(String, unique=True, nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(String, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
|
||||
boosters: Mapped[int] = mapped_column(Integer, default=5, nullable=False)
|
||||
boosters_countdown: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
wins: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
losses: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
shards: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
reset_token: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
reset_token_expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
email_verified: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
email_verification_token: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
email_verification_token_expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
trade_wishlist: Mapped[str | None] = mapped_column(Text, nullable=True, default="")
|
||||
last_active_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
cards: Mapped[list["Card"]] = relationship(back_populates="user", cascade="all, delete-orphan")
|
||||
decks: Mapped[list["Deck"]] = relationship(back_populates="user", cascade="all, delete-orphan")
|
||||
notifications: Mapped[list["Notification"]] = relationship(back_populates="user", cascade="all, delete-orphan")
|
||||
friendships_sent: Mapped[list["Friendship"]] = relationship(
|
||||
foreign_keys="Friendship.requester_id", back_populates="requester", cascade="all, delete-orphan"
|
||||
)
|
||||
friendships_received: Mapped[list["Friendship"]] = relationship(
|
||||
foreign_keys="Friendship.addressee_id", back_populates="addressee", cascade="all, delete-orphan"
|
||||
)
|
||||
proposals_sent: Mapped[list["TradeProposal"]] = relationship(
|
||||
foreign_keys="TradeProposal.proposer_id", back_populates="proposer", cascade="all, delete-orphan"
|
||||
)
|
||||
proposals_received: Mapped[list["TradeProposal"]] = relationship(
|
||||
foreign_keys="TradeProposal.recipient_id", back_populates="recipient", cascade="all, delete-orphan"
|
||||
)
|
||||
challenges_sent: Mapped[list["GameChallenge"]] = relationship(
|
||||
foreign_keys="GameChallenge.challenger_id", back_populates="challenger", cascade="all, delete-orphan"
|
||||
)
|
||||
challenges_received: Mapped[list["GameChallenge"]] = relationship(
|
||||
foreign_keys="GameChallenge.challenged_id", back_populates="challenged", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
|
||||
class Card(Base):
|
||||
__tablename__ = "cards"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
user_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=True)
|
||||
name: Mapped[str] = mapped_column(String, nullable=False)
|
||||
image_link: Mapped[str] = mapped_column(String, nullable=True)
|
||||
card_rarity: Mapped[str] = mapped_column(String, nullable=False)
|
||||
card_type: Mapped[str] = mapped_column(String, nullable=False)
|
||||
text: Mapped[str] = mapped_column(Text, nullable=True)
|
||||
attack: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
defense: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
cost: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
generated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
|
||||
received_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
|
||||
times_played: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
reported: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
ai_used: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_favorite: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
willing_to_trade: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
|
||||
user: Mapped["User | None"] = relationship(back_populates="cards")
|
||||
deck_cards: Mapped[list["DeckCard"]] = relationship(back_populates="card", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class Deck(Base):
|
||||
__tablename__ = "decks"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
name: Mapped[str] = mapped_column(String, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
|
||||
times_played: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
wins: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
losses: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
|
||||
user: Mapped["User"] = relationship(back_populates="decks")
|
||||
deck_cards: Mapped[list["DeckCard"]] = relationship(back_populates="deck", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class Notification(Base):
|
||||
__tablename__ = "notifications"
|
||||
__table_args__ = (
|
||||
CheckConstraint("type IN ('friend_request', 'trade_offer', 'trade_response', 'game_challenge')", name="ck_notifications_type"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
# type is one of: friend_request, trade_offer, trade_response, game_challenge
|
||||
type: Mapped[str] = mapped_column(String, nullable=False)
|
||||
payload: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)
|
||||
read: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
|
||||
expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
user: Mapped["User"] = relationship(back_populates="notifications")
|
||||
|
||||
|
||||
class Friendship(Base):
|
||||
__tablename__ = "friendships"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("requester_id", "addressee_id", name="uq_friendship_requester_addressee"),
|
||||
CheckConstraint("status IN ('pending', 'accepted', 'declined')", name="ck_friendships_status"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
requester_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
addressee_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
# status: pending / accepted / declined
|
||||
status: Mapped[str] = mapped_column(String, nullable=False, default="pending")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
|
||||
|
||||
requester: Mapped["User"] = relationship(foreign_keys=[requester_id], back_populates="friendships_sent")
|
||||
addressee: Mapped["User"] = relationship(foreign_keys=[addressee_id], back_populates="friendships_received")
|
||||
|
||||
|
||||
class TradeProposal(Base):
|
||||
__tablename__ = "trade_proposals"
|
||||
__table_args__ = (
|
||||
CheckConstraint("status IN ('pending', 'accepted', 'declined', 'expired')", name="ck_trade_proposals_status"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
proposer_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
recipient_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
# Both sides stored as JSONB lists of UUID strings so either party can offer 0 or more cards,
|
||||
# mirroring the flexibility of the real-time trade system
|
||||
offered_card_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
|
||||
requested_card_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
|
||||
# status: pending / accepted / declined / expired
|
||||
status: Mapped[str] = mapped_column(String, nullable=False, default="pending")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
|
||||
proposer: Mapped["User"] = relationship(foreign_keys=[proposer_id])
|
||||
recipient: Mapped["User"] = relationship(foreign_keys=[recipient_id])
|
||||
|
||||
|
||||
class GameChallenge(Base):
|
||||
__tablename__ = "game_challenges"
|
||||
__table_args__ = (
|
||||
CheckConstraint("status IN ('pending', 'accepted', 'declined', 'expired')", name="ck_game_challenges_status"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
challenger_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
challenged_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
challenger_deck_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("decks.id", ondelete="CASCADE"), nullable=False)
|
||||
# status: pending / accepted / declined / expired
|
||||
status: Mapped[str] = mapped_column(String, nullable=False, default="pending")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
|
||||
challenger: Mapped["User"] = relationship(foreign_keys=[challenger_id], back_populates="challenges_sent")
|
||||
challenged: Mapped["User"] = relationship(foreign_keys=[challenged_id], back_populates="challenges_received")
|
||||
challenger_deck: Mapped["Deck"] = relationship(foreign_keys=[challenger_deck_id])
|
||||
|
||||
|
||||
class DeckCard(Base):
|
||||
__tablename__ = "deck_cards"
|
||||
|
||||
deck_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("decks.id", ondelete="CASCADE"), primary_key=True)
|
||||
card_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("cards.id", ondelete="CASCADE"), primary_key=True)
|
||||
|
||||
deck: Mapped["Deck"] = relationship(back_populates="deck_cards")
|
||||
card: Mapped["Card"] = relationship(back_populates="deck_cards")
|
||||
|
||||
|
||||
class ProcessedWebhookEvent(Base):
|
||||
__tablename__ = "processed_webhook_events"
|
||||
|
||||
# stripe_event_id is the primary key — acts as unique constraint to prevent duplicate processing
|
||||
stripe_event_id: Mapped[str] = mapped_column(String, primary_key=True)
|
||||
processed_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now, nullable=False)
|
||||
Reference in New Issue
Block a user