Fix bugs, convert thumbnail to png, add context menu
This commit is contained in:
parent
c545d4b17d
commit
eb8a302222
37 changed files with 1916 additions and 137 deletions
35
backend/app/auth/dependencies.py
Normal file
35
backend/app/auth/dependencies.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
"""FastAPI dependencies for authentication and security."""
|
||||
|
||||
from fastapi import Request, HTTPException
|
||||
|
||||
from app.auth.session import verify_session
|
||||
from app.config import settings
|
||||
|
||||
def get_current_user(request: Request) -> int:
|
||||
"""
|
||||
Dependency that extracts and validates the session cookie.
|
||||
Raises 401 if missing or invalid.
|
||||
Returns the user_id.
|
||||
"""
|
||||
token = request.cookies.get(settings.COOKIE_NAME)
|
||||
if not token:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
|
||||
user_id = verify_session(token)
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=401, detail="Session expired or invalid")
|
||||
|
||||
return user_id
|
||||
|
||||
|
||||
def verify_csrf(request: Request) -> None:
|
||||
"""
|
||||
Dependency to mitigate CSRF for cookie-based auth.
|
||||
Requires X-Requested-With header on all mutating requests.
|
||||
"""
|
||||
if request.method in ["POST", "PUT", "PATCH", "DELETE"]:
|
||||
if request.headers.get("X-Requested-With") != "XMLHttpRequest":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="CSRF check failed: missing X-Requested-With header"
|
||||
)
|
||||
20
backend/app/auth/hashing.py
Normal file
20
backend/app/auth/hashing.py
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
"""Argon2id password hashing and verification."""
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
# Argon2id is the default for PasswordHasher
|
||||
ph = PasswordHasher()
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hash a plaintext password."""
|
||||
return ph.hash(password)
|
||||
|
||||
def verify_password(hashed: str, password: str) -> bool:
|
||||
"""Verify a password against a hash. Returns True if matched."""
|
||||
try:
|
||||
ph.verify(hashed, password)
|
||||
# Note: We skip check_needs_rehash() for simplicity in this single-user app.
|
||||
return True
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
59
backend/app/auth/rate_limit.py
Normal file
59
backend/app/auth/rate_limit.py
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
"""In-memory rate limiting for login attempts."""
|
||||
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.config import settings
|
||||
|
||||
# In-memory store: IP address -> {"attempts": int, "lockout_until": float}
|
||||
_rate_limits: dict[str, dict[str, float]] = defaultdict(
|
||||
lambda: {"attempts": 0, "lockout_until": 0.0}
|
||||
)
|
||||
|
||||
|
||||
def check_rate_limit(ip: str) -> None:
|
||||
"""
|
||||
Check if the IP is currently locked out.
|
||||
Raises a 429 HTTPException if locked out.
|
||||
"""
|
||||
now = time.time()
|
||||
record = _rate_limits[ip]
|
||||
|
||||
if record["lockout_until"] > now:
|
||||
remaining = int(record["lockout_until"] - now)
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"Too many failed attempts. Try again in {remaining} seconds.",
|
||||
headers={"Retry-After": str(remaining)},
|
||||
)
|
||||
|
||||
# If lockout has expired, reset
|
||||
if record["lockout_until"] > 0 and record["lockout_until"] <= now:
|
||||
record["attempts"] = 0
|
||||
record["lockout_until"] = 0.0
|
||||
|
||||
|
||||
def record_failed_attempt(ip: str) -> None:
|
||||
"""
|
||||
Record a failed login attempt for the IP.
|
||||
Applies lockout if MAX_ATTEMPTS is reached.
|
||||
"""
|
||||
now = time.time()
|
||||
record = _rate_limits[ip]
|
||||
record["attempts"] += 1
|
||||
|
||||
if record["attempts"] >= settings.LOGIN_MAX_ATTEMPTS:
|
||||
record["lockout_until"] = now + settings.LOGIN_LOCKOUT_SECONDS
|
||||
remaining = settings.LOGIN_LOCKOUT_SECONDS
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"Too many failed attempts. Try again in {remaining} seconds.",
|
||||
headers={"Retry-After": str(remaining)},
|
||||
)
|
||||
|
||||
|
||||
def clear_attempts(ip: str) -> None:
|
||||
"""Clear all failed attempts for the IP (e.g., after successful login)."""
|
||||
if ip in _rate_limits:
|
||||
_rate_limits[ip] = {"attempts": 0, "lockout_until": 0.0}
|
||||
49
backend/app/auth/session.py
Normal file
49
backend/app/auth/session.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"""Session token generation and validation."""
|
||||
|
||||
from typing import Any
|
||||
from fastapi import Response
|
||||
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
|
||||
|
||||
from app.config import settings
|
||||
|
||||
def get_serializer() -> URLSafeTimedSerializer:
|
||||
"""Return a configured URLSafeTimedSerializer."""
|
||||
return URLSafeTimedSerializer(settings.SECRET_KEY)
|
||||
|
||||
def create_session(response: Response, user_id: int = 1) -> None:
|
||||
"""Create a new session token and set it as an HTTP-only cookie."""
|
||||
serializer = get_serializer()
|
||||
token = serializer.dumps({"user_id": user_id})
|
||||
|
||||
response.set_cookie(
|
||||
key=settings.COOKIE_NAME,
|
||||
value=token,
|
||||
max_age=settings.COOKIE_MAX_AGE_SECONDS,
|
||||
secure=settings.COOKIE_SECURE,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
)
|
||||
|
||||
def clear_session(response: Response) -> None:
|
||||
"""Clear the session cookie."""
|
||||
response.delete_cookie(
|
||||
key=settings.COOKIE_NAME,
|
||||
secure=settings.COOKIE_SECURE,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
)
|
||||
|
||||
def verify_session(token: str) -> int | None:
|
||||
"""
|
||||
Verify the session token.
|
||||
Returns the user_id if valid, or None if invalid/expired.
|
||||
"""
|
||||
serializer = get_serializer()
|
||||
try:
|
||||
data: dict[str, Any] = serializer.loads(
|
||||
token,
|
||||
max_age=settings.COOKIE_MAX_AGE_SECONDS
|
||||
)
|
||||
return data.get("user_id")
|
||||
except (BadSignature, SignatureExpired):
|
||||
return None
|
||||
Loading…
Add table
Add a link
Reference in a new issue