|
| 1 | +# Copyright 2026 ByBren, LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Authentication API endpoints. |
| 16 | +
|
| 17 | +Provides user registration, login, token refresh, and logout. |
| 18 | +Rate-limited via Redis-backed sliding window (REN-70). |
| 19 | +Audit-logged via structlog -- passwords and tokens are NEVER logged. |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +from typing import TYPE_CHECKING |
| 25 | + |
| 26 | +import structlog |
| 27 | +from fastapi import APIRouter, Depends, HTTPException, status |
| 28 | +from passlib.hash import bcrypt |
| 29 | +from pydantic import BaseModel, ConfigDict, EmailStr, Field |
| 30 | +from sqlalchemy import select |
| 31 | + |
| 32 | +if TYPE_CHECKING: |
| 33 | + from sqlalchemy.ext.asyncio import AsyncSession |
| 34 | + |
| 35 | +from core.auth.jwt import ( |
| 36 | + TokenType, |
| 37 | + create_access_token, |
| 38 | + create_refresh_token, |
| 39 | + verify_token, |
| 40 | +) |
| 41 | +from core.auth.rate_limit import login_limiter, refresh_limiter, register_limiter |
| 42 | +from core.database import get_db_session |
| 43 | +from core.models.base import User |
| 44 | + |
| 45 | +logger = structlog.get_logger(__name__) |
| 46 | + |
| 47 | +# --------------------------------------------------------------------------- |
| 48 | +# Request / Response Schemas |
| 49 | +# --------------------------------------------------------------------------- |
| 50 | + |
| 51 | + |
| 52 | +class RegisterRequest(BaseModel): |
| 53 | + """Registration payload.""" |
| 54 | + |
| 55 | + email: EmailStr |
| 56 | + name: str = Field(min_length=1, max_length=255) |
| 57 | + password: str = Field(min_length=8) |
| 58 | + |
| 59 | + |
| 60 | +class LoginRequest(BaseModel): |
| 61 | + """Login credentials payload.""" |
| 62 | + |
| 63 | + email: EmailStr |
| 64 | + password: str |
| 65 | + |
| 66 | + |
| 67 | +class RefreshRequest(BaseModel): |
| 68 | + """Token refresh payload.""" |
| 69 | + |
| 70 | + refresh_token: str |
| 71 | + |
| 72 | + |
| 73 | +class TokenResponse(BaseModel): |
| 74 | + """JWT token pair returned on successful authentication.""" |
| 75 | + |
| 76 | + access_token: str |
| 77 | + refresh_token: str |
| 78 | + token_type: str = "bearer" # noqa: S105 |
| 79 | + |
| 80 | + |
| 81 | +class UserResponse(BaseModel): |
| 82 | + """Public user representation (no sensitive fields).""" |
| 83 | + |
| 84 | + id: str |
| 85 | + email: str |
| 86 | + name: str |
| 87 | + is_active: bool |
| 88 | + |
| 89 | + model_config = ConfigDict(from_attributes=True) |
| 90 | + |
| 91 | + |
| 92 | +class RegisterResponse(BaseModel): |
| 93 | + """Registration response containing user info and tokens.""" |
| 94 | + |
| 95 | + user: UserResponse |
| 96 | + tokens: TokenResponse |
| 97 | + |
| 98 | + |
| 99 | +class MessageResponse(BaseModel): |
| 100 | + """Generic message response.""" |
| 101 | + |
| 102 | + message: str |
| 103 | + |
| 104 | + |
| 105 | +# --------------------------------------------------------------------------- |
| 106 | +# Router |
| 107 | +# --------------------------------------------------------------------------- |
| 108 | + |
| 109 | +router = APIRouter(prefix="/auth") |
| 110 | + |
| 111 | + |
| 112 | +def _issue_tokens(user_id: str) -> TokenResponse: |
| 113 | + """Create an access + refresh token pair for the given user ID. |
| 114 | +
|
| 115 | + Args: |
| 116 | + user_id: The user's UUID as a string. |
| 117 | +
|
| 118 | + Returns: |
| 119 | + TokenResponse with both tokens and token_type. |
| 120 | + """ |
| 121 | + return TokenResponse( |
| 122 | + access_token=create_access_token({"sub": user_id}), |
| 123 | + refresh_token=create_refresh_token({"sub": user_id}), |
| 124 | + ) |
| 125 | + |
| 126 | + |
| 127 | +# --------------------------------------------------------------------------- |
| 128 | +# POST /auth/register |
| 129 | +# --------------------------------------------------------------------------- |
| 130 | + |
| 131 | + |
| 132 | +@router.post( |
| 133 | + "/register", |
| 134 | + response_model=RegisterResponse, |
| 135 | + status_code=status.HTTP_201_CREATED, |
| 136 | + dependencies=[Depends(register_limiter)], |
| 137 | +) |
| 138 | +async def register( |
| 139 | + payload: RegisterRequest, |
| 140 | + session: AsyncSession = Depends(get_db_session), |
| 141 | +) -> RegisterResponse: |
| 142 | + """Create a new user account and return JWT tokens. |
| 143 | +
|
| 144 | + Raises: |
| 145 | + HTTPException 409: If the email is already registered. |
| 146 | + """ |
| 147 | + # Check for existing email |
| 148 | + result = await session.execute( |
| 149 | + select(User).where(User.email == payload.email), |
| 150 | + ) |
| 151 | + if result.scalar_one_or_none() is not None: |
| 152 | + logger.info("registration_email_conflict", email_domain=payload.email.split("@")[1]) |
| 153 | + raise HTTPException( |
| 154 | + status_code=status.HTTP_409_CONFLICT, |
| 155 | + detail="Email already registered", |
| 156 | + ) |
| 157 | + |
| 158 | + # Create user |
| 159 | + hashed = bcrypt.hash(payload.password) |
| 160 | + user = User( |
| 161 | + email=payload.email, |
| 162 | + name=payload.name, |
| 163 | + hashed_password=hashed, |
| 164 | + is_active=True, |
| 165 | + is_admin=False, |
| 166 | + ) |
| 167 | + session.add(user) |
| 168 | + await session.flush() |
| 169 | + |
| 170 | + logger.info("user_registered", user_id=str(user.id)) |
| 171 | + |
| 172 | + tokens = _issue_tokens(str(user.id)) |
| 173 | + return RegisterResponse( |
| 174 | + user=UserResponse( |
| 175 | + id=str(user.id), |
| 176 | + email=user.email, |
| 177 | + name=user.name, |
| 178 | + is_active=user.is_active, |
| 179 | + ), |
| 180 | + tokens=tokens, |
| 181 | + ) |
| 182 | + |
| 183 | + |
| 184 | +# --------------------------------------------------------------------------- |
| 185 | +# POST /auth/login |
| 186 | +# --------------------------------------------------------------------------- |
| 187 | + |
| 188 | + |
| 189 | +@router.post( |
| 190 | + "/login", |
| 191 | + response_model=TokenResponse, |
| 192 | + dependencies=[Depends(login_limiter)], |
| 193 | +) |
| 194 | +async def login( |
| 195 | + payload: LoginRequest, |
| 196 | + session: AsyncSession = Depends(get_db_session), |
| 197 | +) -> TokenResponse: |
| 198 | + """Authenticate with email and password, returning JWT tokens. |
| 199 | +
|
| 200 | + Raises: |
| 201 | + HTTPException 401: Invalid credentials or inactive account. |
| 202 | + """ |
| 203 | + invalid_credentials = HTTPException( |
| 204 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 205 | + detail="Invalid email or password", |
| 206 | + headers={"WWW-Authenticate": "Bearer"}, |
| 207 | + ) |
| 208 | + |
| 209 | + # Look up user by email |
| 210 | + result = await session.execute( |
| 211 | + select(User).where(User.email == payload.email), |
| 212 | + ) |
| 213 | + user = result.scalar_one_or_none() |
| 214 | + |
| 215 | + if user is None: |
| 216 | + logger.info("login_failed", reason="user_not_found") |
| 217 | + raise invalid_credentials |
| 218 | + |
| 219 | + # Verify password |
| 220 | + if not bcrypt.verify(payload.password, user.hashed_password): |
| 221 | + logger.info("login_failed", reason="invalid_password", user_id=str(user.id)) |
| 222 | + raise invalid_credentials |
| 223 | + |
| 224 | + # Check active status |
| 225 | + if not user.is_active: |
| 226 | + logger.warning("login_failed", reason="inactive_account", user_id=str(user.id)) |
| 227 | + raise HTTPException( |
| 228 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 229 | + detail="Account is inactive", |
| 230 | + headers={"WWW-Authenticate": "Bearer"}, |
| 231 | + ) |
| 232 | + |
| 233 | + logger.info("login_success", user_id=str(user.id)) |
| 234 | + return _issue_tokens(str(user.id)) |
| 235 | + |
| 236 | + |
| 237 | +# --------------------------------------------------------------------------- |
| 238 | +# POST /auth/refresh |
| 239 | +# --------------------------------------------------------------------------- |
| 240 | + |
| 241 | + |
| 242 | +@router.post( |
| 243 | + "/refresh", |
| 244 | + response_model=TokenResponse, |
| 245 | + dependencies=[Depends(refresh_limiter)], |
| 246 | +) |
| 247 | +async def refresh( |
| 248 | + payload: RefreshRequest, |
| 249 | + session: AsyncSession = Depends(get_db_session), |
| 250 | +) -> TokenResponse: |
| 251 | + """Exchange a valid refresh token for a new access + refresh token pair. |
| 252 | +
|
| 253 | + Raises: |
| 254 | + HTTPException 401: Invalid, expired, or wrong-type token. |
| 255 | + """ |
| 256 | + token_data = verify_token(payload.refresh_token) |
| 257 | + |
| 258 | + # Ensure this is actually a refresh token, not an access token |
| 259 | + if token_data.token_type != TokenType.REFRESH: |
| 260 | + logger.warning("refresh_wrong_token_type", token_type=token_data.token_type) |
| 261 | + raise HTTPException( |
| 262 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 263 | + detail="Invalid token type: expected refresh token", |
| 264 | + headers={"WWW-Authenticate": "Bearer"}, |
| 265 | + ) |
| 266 | + |
| 267 | + # Verify user still exists and is active |
| 268 | + result = await session.execute( |
| 269 | + select(User).where(User.id == token_data.sub), |
| 270 | + ) |
| 271 | + user = result.scalar_one_or_none() |
| 272 | + |
| 273 | + if user is None: |
| 274 | + logger.warning("refresh_user_not_found", user_id=token_data.sub) |
| 275 | + raise HTTPException( |
| 276 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 277 | + detail="User not found", |
| 278 | + headers={"WWW-Authenticate": "Bearer"}, |
| 279 | + ) |
| 280 | + |
| 281 | + if not user.is_active: |
| 282 | + logger.warning("refresh_inactive_user", user_id=token_data.sub) |
| 283 | + raise HTTPException( |
| 284 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 285 | + detail="Account is inactive", |
| 286 | + headers={"WWW-Authenticate": "Bearer"}, |
| 287 | + ) |
| 288 | + |
| 289 | + logger.info("token_refreshed", user_id=str(user.id)) |
| 290 | + return _issue_tokens(str(user.id)) |
| 291 | + |
| 292 | + |
| 293 | +# --------------------------------------------------------------------------- |
| 294 | +# POST /auth/logout |
| 295 | +# --------------------------------------------------------------------------- |
| 296 | + |
| 297 | + |
| 298 | +@router.post( |
| 299 | + "/logout", |
| 300 | + response_model=MessageResponse, |
| 301 | +) |
| 302 | +async def logout() -> MessageResponse: |
| 303 | + """Log out the current user. |
| 304 | +
|
| 305 | + .. note:: |
| 306 | + This is a placeholder. Actual token revocation (server-side |
| 307 | + blocklist) will be implemented in REN-72. |
| 308 | +
|
| 309 | + Returns: |
| 310 | + Confirmation message. |
| 311 | + """ |
| 312 | + # TODO(REN-72): Implement token revocation via Redis blocklist. |
| 313 | + # Accept the Authorization header, decode the token, and add its |
| 314 | + # ``jti`` to a Redis set with TTL matching the token's remaining |
| 315 | + # lifetime. ``verify_token`` should then check the blocklist. |
| 316 | + logger.info("logout_placeholder_called") |
| 317 | + return MessageResponse(message="Logged out successfully") |
0 commit comments