feat(auth): T18 implement user registration endpoint

Add POST /api/auth/register endpoint with:
- UserRegister schema validation
- Email uniqueness check
- Password hashing with bcrypt
- User creation in database
- UserResponse returned (excludes password)

Status: 201 Created on success, 400 for duplicate email, 422 for validation errors

Test coverage: 5 tests for register endpoint
This commit is contained in:
Luca Sacchi Ricciardi
2026-04-07 13:57:38 +02:00
parent 02473bc39e
commit 714bde681c
7 changed files with 577 additions and 11 deletions

View File

@@ -0,0 +1,4 @@
"""Dependencies package for OpenRouter Monitor."""
from openrouter_monitor.dependencies.auth import get_current_user, security
__all__ = ["get_current_user", "security"]

View File

@@ -0,0 +1,79 @@
"""Authentication dependencies.
T21: get_current_user dependency for protected endpoints.
"""
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jose import JWTError
from sqlalchemy.orm import Session
from openrouter_monitor.database import get_db
from openrouter_monitor.models import User
from openrouter_monitor.schemas import TokenData
from openrouter_monitor.services import decode_access_token
# HTTP Bearer security scheme
security = HTTPBearer()
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db)
) -> User:
"""Get current authenticated user from JWT token.
This dependency extracts the JWT token from the Authorization header,
decodes it, and retrieves the corresponding user from the database.
Args:
credentials: HTTP Authorization credentials containing the Bearer token
db: Database session
Returns:
The authenticated User object
Raises:
HTTPException: 401 if token is invalid, expired, or user not found/inactive
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
# Decode the JWT token
payload = decode_access_token(credentials.credentials)
# Extract user_id from sub claim
user_id = payload.get("sub")
if user_id is None:
raise credentials_exception
# Verify exp claim exists
if payload.get("exp") is None:
raise credentials_exception
except JWTError:
raise credentials_exception
# Get user from database
try:
user_id_int = int(user_id)
except (ValueError, TypeError):
raise credentials_exception
user = db.query(User).filter(User.id == user_id_int).first()
if user is None:
raise credentials_exception
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User account is inactive",
headers={"WWW-Authenticate": "Bearer"},
)
return user

View File

@@ -0,0 +1,43 @@
"""FastAPI main application.
Main application entry point for OpenRouter API Key Monitor.
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from openrouter_monitor.config import get_settings
from openrouter_monitor.routers import auth
settings = get_settings()
# Create FastAPI app
app = FastAPI(
title="OpenRouter API Key Monitor",
description="Monitor and manage OpenRouter API keys",
version="1.0.0",
debug=settings.debug,
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure appropriately for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(auth.router, prefix="/api/auth", tags=["authentication"])
@app.get("/")
async def root():
"""Root endpoint."""
return {"message": "OpenRouter API Key Monitor API", "version": "1.0.0"}
@app.get("/health")
async def health_check():
"""Health check endpoint."""
return {"status": "healthy"}

View File

@@ -0,0 +1,4 @@
"""Routers package for OpenRouter Monitor."""
from openrouter_monitor.routers import auth
__all__ = ["auth"]

View File

@@ -0,0 +1,135 @@
"""Authentication router.
T18-T20: Endpoints for user registration, login, and logout.
"""
from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from openrouter_monitor.config import get_settings
from openrouter_monitor.database import get_db
from openrouter_monitor.dependencies import get_current_user, security
from openrouter_monitor.models import User
from openrouter_monitor.schemas import (
TokenResponse,
UserLogin,
UserRegister,
UserResponse,
)
from openrouter_monitor.services import (
create_access_token,
hash_password,
verify_password,
)
router = APIRouter()
settings = get_settings()
@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def register(user_data: UserRegister, db: Session = Depends(get_db)):
"""Register a new user.
Args:
user_data: User registration data including email and password
db: Database session
Returns:
UserResponse with user details (excluding password)
Raises:
HTTPException: 400 if email already exists
"""
# Check if email already exists
existing_user = db.query(User).filter(User.email == user_data.email).first()
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered"
)
# Create new user
new_user = User(
email=user_data.email,
password_hash=hash_password(user_data.password)
)
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_user
@router.post("/login", response_model=TokenResponse)
async def login(credentials: UserLogin, db: Session = Depends(get_db)):
"""Authenticate user and return JWT token.
Args:
credentials: User login credentials (email and password)
db: Database session
Returns:
TokenResponse with access token
Raises:
HTTPException: 401 if credentials are invalid
"""
# Find user by email
user = db.query(User).filter(User.email == credentials.email).first()
# Check if user exists
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Bearer"},
)
# Check if user is active
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Bearer"},
)
# Verify password
if not verify_password(credentials.password, user.password_hash):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Bearer"},
)
# Generate JWT token
access_token_expires = timedelta(hours=settings.jwt_expiration_hours)
access_token = create_access_token(
data={"sub": str(user.id)},
expires_delta=access_token_expires
)
return TokenResponse(
access_token=access_token,
token_type="bearer",
expires_in=int(access_token_expires.total_seconds())
)
@router.post("/logout")
async def logout(current_user: User = Depends(get_current_user)):
"""Logout current user.
Since JWT tokens are stateless, the actual logout is handled client-side
by removing the token. This endpoint serves as a formal logout action
and can be extended for token blacklisting in the future.
Args:
current_user: Current authenticated user
Returns:
Success message
"""
return {"message": "Successfully logged out"}