mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 07:16:15 +00:00
149 lines
4.5 KiB
Python
149 lines
4.5 KiB
Python
"""JWT authentication: register, login, and token validation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import bcrypt
|
|
import jwt
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
|
|
|
from app.api.schemas import TokenResponse, UserCreate, UserResponse
|
|
from storage import SQLiteStore
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_TOKEN_EXPIRE_DAYS = 14
|
|
_ALGORITHM = "HS256"
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
|
|
|
auth_router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
|
|
|
|
|
def _get_secret_key() -> str:
|
|
key = os.environ.get("JWT_SECRET_KEY")
|
|
if not key:
|
|
raise RuntimeError("JWT_SECRET_KEY environment variable is not set")
|
|
return key
|
|
|
|
|
|
def _create_token(user_id: int, email: str) -> str:
|
|
now = datetime.now(timezone.utc)
|
|
payload = {
|
|
"sub": str(user_id),
|
|
"email": email,
|
|
"iat": now,
|
|
"exp": now + timedelta(days=_TOKEN_EXPIRE_DAYS),
|
|
}
|
|
return jwt.encode(payload, _get_secret_key(), algorithm=_ALGORITHM)
|
|
|
|
|
|
def _hash_password(password: str) -> str:
|
|
"""Return a bcrypt password hash."""
|
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
|
|
|
|
|
def _verify_password(password: str, password_hash: str) -> bool:
|
|
"""Validate a plaintext password against a stored bcrypt hash."""
|
|
try:
|
|
return bcrypt.checkpw(
|
|
password.encode("utf-8"),
|
|
password_hash.encode("utf-8"),
|
|
)
|
|
except ValueError:
|
|
logger.warning("Encountered an invalid stored password hash.")
|
|
return False
|
|
|
|
|
|
def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
|
|
"""FastAPI dependency that validates the JWT and returns user info."""
|
|
try:
|
|
payload = jwt.decode(
|
|
token, _get_secret_key(), algorithms=[_ALGORITHM]
|
|
)
|
|
user_id = payload.get("sub")
|
|
email = payload.get("email")
|
|
if user_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="login required",
|
|
)
|
|
return {"user_id": int(user_id), "email": email}
|
|
except jwt.ExpiredSignatureError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="login required",
|
|
)
|
|
except jwt.InvalidTokenError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="login required",
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Endpoints
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@auth_router.post(
|
|
"/register",
|
|
response_model=UserResponse,
|
|
status_code=status.HTTP_201_CREATED,
|
|
)
|
|
def register(body: UserCreate) -> UserResponse:
|
|
"""Create a new user account."""
|
|
store = SQLiteStore()
|
|
hashed = _hash_password(body.password)
|
|
now_iso = datetime.now(timezone.utc).isoformat()
|
|
|
|
with store.connect() as conn:
|
|
existing = conn.execute(
|
|
"SELECT id FROM users WHERE email = ?", (body.email,)
|
|
).fetchone()
|
|
if existing:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail="email already registered",
|
|
)
|
|
cursor = conn.execute(
|
|
"""
|
|
INSERT INTO users (email, password_hash, created_at)
|
|
VALUES (?, ?, ?)
|
|
""",
|
|
(body.email, hashed, now_iso),
|
|
)
|
|
user_id = cursor.lastrowid
|
|
|
|
return UserResponse(id=user_id, email=body.email)
|
|
|
|
|
|
@auth_router.post("/login", response_model=TokenResponse)
|
|
def login(form: OAuth2PasswordRequestForm = Depends()) -> TokenResponse:
|
|
"""Authenticate and return a JWT token."""
|
|
store = SQLiteStore()
|
|
|
|
with store.connect() as conn:
|
|
row = conn.execute(
|
|
"SELECT id, email, password_hash FROM users WHERE email = ?",
|
|
(form.username,),
|
|
).fetchone()
|
|
|
|
if row is None or not _verify_password(form.password, row["password_hash"]):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="invalid credentials",
|
|
)
|
|
|
|
conn.execute(
|
|
"UPDATE users SET last_login_at = ? WHERE id = ?",
|
|
(datetime.now(timezone.utc).isoformat(), row["id"]),
|
|
)
|
|
|
|
token = _create_token(row["id"], row["email"])
|
|
return TokenResponse(access_token=token)
|