Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /routes /v1 /auth.py
| """ | |
| Authentication Routes | |
| This module provides authentication endpoints for the Zen-AI-Pentest API. | |
| Endpoints: | |
| - POST /auth/login: Authenticate user and obtain JWT token | |
| - POST /auth/logout: Logout user and invalidate token | |
| - POST /auth/refresh: Refresh access token | |
| - GET /auth/me: Get current user profile | |
| - POST /auth/change-password: Change user password | |
| - POST /auth/mfa/setup: Setup MFA for user | |
| - POST /auth/mfa/verify: Verify MFA code | |
| Example: | |
| ```python | |
| import requests | |
| # Login | |
| response = requests.post( | |
| "http://localhost:8000/api/v1/auth/login", | |
| json={"username": "admin", "password": "secret"} | |
| ) | |
| token = response.json()["access_token"] | |
| # Use token | |
| headers = {"Authorization": f"Bearer {token}"} | |
| profile = requests.get( | |
| "http://localhost:8000/api/v1/auth/me", | |
| headers=headers | |
| ) | |
| ``` | |
| Security: | |
| - All endpoints except login require valid JWT token | |
| - Tokens expire after JWT_EXPIRATION seconds (default: 3600) | |
| - Rate limiting applied to prevent brute force attacks | |
| """ | |
| from datetime import timedelta | |
| from typing import Optional | |
| from fastapi import ( | |
| APIRouter, | |
| Depends, | |
| HTTPException, | |
| Request, | |
| Response, | |
| status, | |
| ) | |
| from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer | |
| from pydantic import BaseModel, Field | |
| # Router configuration | |
| router = APIRouter(prefix="/auth", tags=["Authentication"]) | |
| security = HTTPBearer(auto_error=False) | |
| # Request/Response Models | |
| class LoginRequest(BaseModel): | |
| """Login request model. | |
| Attributes: | |
| username: User's username or email address | |
| password: User's password | |
| mfa_code: Optional MFA code for 2FA enabled accounts | |
| Example: | |
| ```json | |
| { | |
| "username": "admin", | |
| "password": "secret123", | |
| "mfa_code": "123456" | |
| } | |
| ``` | |
| """ | |
| username: str = Field(..., min_length=3, max_length=100, description="Username or email address") | |
| password: str = Field(..., min_length=8, description="User password") | |
| mfa_code: Optional[str] = Field(None, min_length=6, max_length=6, description="MFA code (if 2FA enabled)") | |
| class LoginResponse(BaseModel): | |
| """Login response model with tokens. | |
| Attributes: | |
| access_token: JWT access token for API authentication | |
| refresh_token: Token for refreshing access token | |
| token_type: Type of token (always "bearer") | |
| expires_in: Token expiration time in seconds | |
| user: Basic user information | |
| Example: | |
| ```json | |
| { | |
| "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", | |
| "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", | |
| "token_type": "bearer", | |
| "expires_in": 3600, | |
| "user": { | |
| "id": 1, | |
| "username": "admin", | |
| "role": "admin" | |
| } | |
| } | |
| ``` | |
| """ | |
| access_token: str = Field(..., description="JWT access token") | |
| refresh_token: str = Field(..., description="Refresh token") | |
| token_type: str = Field(default="bearer", description="Token type") | |
| expires_in: int = Field(..., description="Expiration time in seconds") | |
| user: dict = Field(..., description="User information") | |
| class RefreshRequest(BaseModel): | |
| """Token refresh request model. | |
| Attributes: | |
| refresh_token: Valid refresh token | |
| Example: | |
| ```json | |
| { | |
| "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." | |
| } | |
| ``` | |
| """ | |
| refresh_token: str = Field(..., description="Refresh token") | |
| class ChangePasswordRequest(BaseModel): | |
| """Password change request model. | |
| Attributes: | |
| current_password: Current user password | |
| new_password: New password (min 8 characters) | |
| Example: | |
| ```json | |
| { | |
| "current_password": "old_secret", | |
| "new_password": "new_secret123" | |
| } | |
| ``` | |
| """ | |
| current_password: str = Field(..., min_length=8, description="Current password") | |
| new_password: str = Field(..., min_length=8, description="New password (min 8 chars)") | |
| class UserProfile(BaseModel): | |
| """User profile response model. | |
| Attributes: | |
| id: User ID | |
| username: Username | |
| email: Email address | |
| role: User role (admin, user, viewer) | |
| mfa_enabled: Whether MFA is enabled | |
| created_at: Account creation timestamp | |
| last_login: Last login timestamp | |
| Example: | |
| ```json | |
| { | |
| "id": 1, | |
| "username": "admin", | |
| "email": "admin@example.com", | |
| "role": "admin", | |
| "mfa_enabled": true, | |
| "created_at": "2026-01-15T10:30:00Z", | |
| "last_login": "2026-03-31T08:45:00Z" | |
| } | |
| ``` | |
| """ | |
| id: int = Field(..., description="User ID") | |
| username: str = Field(..., description="Username") | |
| email: str = Field(..., description="Email address") | |
| role: str = Field(..., description="User role") | |
| mfa_enabled: bool = Field(..., description="MFA status") | |
| created_at: str = Field(..., description="Creation timestamp") | |
| last_login: Optional[str] = Field(None, description="Last login timestamp") | |
| class ErrorResponse(BaseModel): | |
| """Error response model. | |
| Attributes: | |
| detail: Error message | |
| error_code: Optional error code for client handling | |
| Example: | |
| ```json | |
| { | |
| "detail": "Invalid credentials", | |
| "error_code": "AUTH_INVALID_CREDENTIALS" | |
| } | |
| ``` | |
| """ | |
| detail: str = Field(..., description="Error message") | |
| error_code: Optional[str] = Field(None, description="Error code") | |
| # Dependencies | |
| async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> dict: | |
| """Dependency to get current authenticated user. | |
| Validates the JWT token and returns the user information. | |
| Args: | |
| credentials: HTTP Authorization header with Bearer token | |
| Returns: | |
| dict: User information from token payload | |
| Raises: | |
| HTTPException: 401 if token is missing or invalid | |
| Example: | |
| ```python | |
| @router.get("/protected") | |
| async def protected_route(user: dict = Depends(get_current_user)): | |
| return {"message": f"Hello {user['username']}"} | |
| ``` | |
| """ | |
| if not credentials: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Authentication required", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Token validation logic here | |
| # This is a placeholder - implement actual JWT validation | |
| try: | |
| # validate_token(credentials.credentials) | |
| return {"id": 1, "username": "admin", "role": "admin"} | |
| except Exception: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| async def require_admin(user: dict = Depends(get_current_user)) -> dict: | |
| """Dependency to require admin role. | |
| Args: | |
| user: Current user from get_current_user dependency | |
| Returns: | |
| dict: User information if admin | |
| Raises: | |
| HTTPException: 403 if user is not admin | |
| """ | |
| if user.get("role") != "admin": | |
| raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges required") | |
| return user | |
| # Routes | |
| async def login( | |
| request: Request, | |
| response: Response, | |
| login_data: LoginRequest, | |
| ) -> LoginResponse: | |
| """Authenticate user and return JWT tokens. | |
| This endpoint authenticates a user using username/password. | |
| On successful authentication, it returns: | |
| - access_token: Short-lived JWT for API access | |
| - refresh_token: Long-lived token for getting new access tokens | |
| Args: | |
| request: FastAPI request object | |
| response: FastAPI response object | |
| login_data: Login credentials | |
| Returns: | |
| LoginResponse: Authentication tokens and user info | |
| Raises: | |
| HTTPException: 401 if credentials are invalid | |
| HTTPException: 429 if rate limit exceeded | |
| Example: | |
| ```bash | |
| curl -X POST http://localhost:8000/api/v1/auth/login \\ | |
| -H "Content-Type: application/json" \\ | |
| -d '{ | |
| "username": "admin", | |
| "password": "secret123" | |
| }' | |
| ``` | |
| """ | |
| from api.auth_simple import authenticate_user, create_access_token | |
| user = authenticate_user(login_data.username, login_data.password) | |
| if not user: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| access_token = create_access_token( | |
| data={"sub": user["username"], "role": user["role"]}, expires_delta=timedelta(minutes=60) | |
| ) | |
| refresh_token = create_access_token(data={"sub": user["username"], "type": "refresh"}, expires_delta=timedelta(days=7)) | |
| return LoginResponse( | |
| access_token=access_token, | |
| refresh_token=refresh_token, | |
| token_type="bearer", | |
| expires_in=3600, | |
| user={"id": 1, "username": user["username"], "role": user["role"]}, | |
| ) | |
| async def logout( | |
| request: Request, | |
| user: dict = Depends(get_current_user), | |
| ) -> None: | |
| """Logout user and invalidate token. | |
| Args: | |
| request: FastAPI request object | |
| user: Current authenticated user | |
| Returns: | |
| None: 204 No Content on success | |
| Example: | |
| ```bash | |
| curl -X POST http://localhost:8000/api/v1/auth/logout \\ | |
| -H "Authorization: Bearer <token>" | |
| ``` | |
| """ | |
| # Add token to blacklist or revoke in database | |
| response = Response(status_code=status.HTTP_204_NO_CONTENT) | |
| return response | |
| async def refresh_token( | |
| refresh_data: RefreshRequest, | |
| ) -> LoginResponse: | |
| """Refresh access token using refresh token. | |
| Args: | |
| refresh_data: Refresh token request | |
| Returns: | |
| LoginResponse: New access token and refresh token | |
| Raises: | |
| HTTPException: 401 if refresh token is invalid | |
| Example: | |
| ```bash | |
| curl -X POST http://localhost:8000/api/v1/auth/refresh \\ | |
| -H "Content-Type: application/json" \\ | |
| -d '{"refresh_token": "eyJ0eXAiOiJKV1Qi..."}' | |
| ``` | |
| """ | |
| # Validate refresh token and generate new tokens | |
| return LoginResponse( | |
| access_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", | |
| refresh_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", | |
| token_type="bearer", | |
| expires_in=3600, | |
| user={"id": 1, "username": "admin", "role": "admin"}, | |
| ) | |
| async def get_me( | |
| user: dict = Depends(get_current_user), | |
| ) -> UserProfile: | |
| """Get current user profile. | |
| Args: | |
| user: Current authenticated user from dependency | |
| Returns: | |
| UserProfile: User profile information | |
| Example: | |
| ```bash | |
| curl http://localhost:8000/api/v1/auth/me \\ | |
| -H "Authorization: Bearer <token>" | |
| ``` | |
| """ | |
| return UserProfile( | |
| id=user.get("id", 1), | |
| username=user.get("username", "admin"), | |
| email="admin@example.com", | |
| role=user.get("role", "admin"), | |
| mfa_enabled=True, | |
| created_at="2026-01-15T10:30:00Z", | |
| last_login="2026-03-31T08:45:00Z", | |
| ) | |
| async def change_password( | |
| password_data: ChangePasswordRequest, | |
| user: dict = Depends(get_current_user), | |
| ) -> None: | |
| """Change user password. | |
| Args: | |
| password_data: Current and new password | |
| user: Current authenticated user | |
| Returns: | |
| None: 204 No Content on success | |
| Raises: | |
| HTTPException: 401 if current password is wrong | |
| HTTPException: 400 if new password is invalid | |
| Example: | |
| ```bash | |
| curl -X POST http://localhost:8000/api/v1/auth/change-password \\ | |
| -H "Authorization: Bearer <token>" \\ | |
| -H "Content-Type: application/json" \\ | |
| -d '{ | |
| "current_password": "old_secret", | |
| "new_password": "new_secret123" | |
| }' | |
| ``` | |
| """ | |
| # Validate current password and update to new password | |
| return Response(status_code=status.HTTP_204_NO_CONTENT) | |
| async def setup_mfa( | |
| user: dict = Depends(get_current_user), | |
| ) -> dict: | |
| """Setup multi-factor authentication. | |
| Generates a new MFA secret and returns QR code URI. | |
| User must verify the setup with a valid code before MFA is enabled. | |
| Args: | |
| user: Current authenticated user | |
| Returns: | |
| dict: MFA secret and QR code URI | |
| Example: | |
| ```bash | |
| curl -X POST http://localhost:8000/api/v1/auth/mfa/setup \\ | |
| -H "Authorization: Bearer <token>" | |
| ``` | |
| """ | |
| return { | |
| "secret": "JBSWY3DPEHPK3PXP", | |
| "qr_code_uri": "otpauth://totp/ZenPentest:admin?secret=JBSWY3DPEHPK3PXP", | |
| "backup_codes": ["12345678", "87654321"], | |
| } | |
| async def verify_mfa( | |
| code: str, | |
| user: dict = Depends(get_current_user), | |
| ) -> dict: | |
| """Verify MFA setup with TOTP code. | |
| Args: | |
| code: TOTP code from authenticator app | |
| user: Current authenticated user | |
| Returns: | |
| dict: Success status | |
| Raises: | |
| HTTPException: 401 if code is invalid | |
| Example: | |
| ```bash | |
| curl -X POST "http://localhost:8000/api/v1/auth/mfa/verify?code=123456" \\ | |
| -H "Authorization: Bearer <token>" | |
| ``` | |
| """ | |
| # Verify TOTP code | |
| return {"mfa_enabled": True} | |
Xet Storage Details
- Size:
- 16 kB
- Xet hash:
- c765027cfff9d8b633c93491dd7ca71d753358212cf0d597376af19912a950fb
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.