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:
@@ -0,0 +1,4 @@
|
||||
"""Routers package for OpenRouter Monitor."""
|
||||
from openrouter_monitor.routers import auth
|
||||
|
||||
__all__ = ["auth"]
|
||||
|
||||
135
src/openrouter_monitor/routers/auth.py
Normal file
135
src/openrouter_monitor/routers/auth.py
Normal 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"}
|
||||
Reference in New Issue
Block a user