Download src/apps/auth/api/mfa.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/auth/api/mfa.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/apps/auth/api/mfa.py
-
curl -L -o mfa.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/auth/api/mfa.py
12 kB
| """Multi-Factor Authentication API endpoints.""" | |
| from typing import List | |
| from fastapi import APIRouter, Depends, HTTPException, status, Response | |
| from fastapi.responses import StreamingResponse | |
| from sqlmodel import Session | |
| from pydantic import BaseModel | |
| from apps.auth.services.mfa_service import MFAService | |
| from apps.auth.models.user import AuthUser | |
| from core.database import get_db_session | |
| from apps.auth.dependencies import get_current_active_user | |
| router = APIRouter(prefix="/mfa", tags=["MFA"]) | |
| # ============================================================================ | |
| # Request/Response Models | |
| # ============================================================================ | |
| class MFAEnrollmentRequest(BaseModel): | |
| """Request to enroll in MFA.""" | |
| password: str # Require password confirmation for security | |
| class MFAEnrollmentResponse(BaseModel): | |
| """Response with MFA enrollment details.""" | |
| secret: str | |
| provisioning_uri: str | |
| backup_codes: List[str] | |
| qr_code_url: str | |
| class MFAVerifyRequest(BaseModel): | |
| """Request to verify MFA token.""" | |
| token: str | |
| class MFAVerifyResponse(BaseModel): | |
| """Response after MFA verification.""" | |
| verified: bool | |
| message: str | |
| class MFADisableRequest(BaseModel): | |
| """Request to disable MFA.""" | |
| password: str # Require password confirmation | |
| token: str # Require valid TOTP or backup code | |
| class MFAStatusResponse(BaseModel): | |
| """MFA status for current user.""" | |
| mfa_enabled: bool | |
| backup_codes_remaining: int | |
| class BackupCodesResponse(BaseModel): | |
| """Response with new backup codes.""" | |
| backup_codes: List[str] | |
| message: str | |
| # ============================================================================ | |
| # MFA Endpoints | |
| # ============================================================================ | |
| def get_mfa_status( | |
| current_user: AuthUser = Depends(get_current_active_user), | |
| session: Session = Depends(get_db_session) | |
| ): | |
| """ | |
| Get MFA status for current user. | |
| Returns: | |
| MFA enabled status and remaining backup codes count | |
| """ | |
| mfa_service = MFAService(session) | |
| backup_codes_remaining = 0 | |
| if current_user.mfa_enabled: | |
| backup_codes_remaining = mfa_service.get_remaining_backup_codes_count(current_user) | |
| return MFAStatusResponse( | |
| mfa_enabled=current_user.mfa_enabled, | |
| backup_codes_remaining=backup_codes_remaining | |
| ) | |
| def enroll_mfa( | |
| request: MFAEnrollmentRequest, | |
| current_user: AuthUser = Depends(get_current_active_user), | |
| session: Session = Depends(get_db_session) | |
| ): | |
| """ | |
| Enroll in Multi-Factor Authentication. | |
| Generates TOTP secret, provisioning URI, and backup codes. | |
| User must scan QR code with authenticator app (Google Authenticator, Authy, etc.) | |
| Args: | |
| request: Password confirmation | |
| Returns: | |
| Secret, provisioning URI, backup codes, and QR code URL | |
| Raises: | |
| HTTPException: If MFA already enabled or password incorrect | |
| """ | |
| # Verify password | |
| if not current_user.verify_password(request.password): | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid password" | |
| ) | |
| # Check if MFA already enabled | |
| if current_user.mfa_enabled: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="MFA is already enabled for this account" | |
| ) | |
| mfa_service = MFAService(session) | |
| # Enable MFA and generate secret + backup codes | |
| secret, backup_codes = mfa_service.enable_mfa(current_user) | |
| # Generate provisioning URI for QR code | |
| provisioning_uri = mfa_service.generate_provisioning_uri(current_user, secret) | |
| return MFAEnrollmentResponse( | |
| secret=secret, | |
| provisioning_uri=provisioning_uri, | |
| backup_codes=backup_codes, | |
| qr_code_url=f"/api/v1/auth/mfa/qr-code?secret={secret}" | |
| ) | |
| def get_qr_code( | |
| secret: str, | |
| current_user: AuthUser = Depends(get_current_active_user), | |
| session: Session = Depends(get_db_session) | |
| ): | |
| """ | |
| Get QR code image for MFA enrollment. | |
| Args: | |
| secret: TOTP secret (from enrollment) | |
| Returns: | |
| PNG image of QR code | |
| Raises: | |
| HTTPException: If secret doesn't match user's secret | |
| """ | |
| # Verify secret belongs to current user | |
| if current_user.mfa_secret != secret: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Invalid secret" | |
| ) | |
| mfa_service = MFAService(session) | |
| provisioning_uri = mfa_service.generate_provisioning_uri(current_user, secret) | |
| qr_code = mfa_service.generate_qr_code(provisioning_uri) | |
| return StreamingResponse(qr_code, media_type="image/png") | |
| def verify_mfa_token( | |
| request: MFAVerifyRequest, | |
| current_user: AuthUser = Depends(get_current_active_user), | |
| session: Session = Depends(get_db_session) | |
| ): | |
| """ | |
| Verify MFA token (TOTP or backup code). | |
| Use this endpoint after enrollment to confirm setup is working. | |
| Also used during login flow (in production). | |
| Args: | |
| request: 6-digit TOTP token or 8-character backup code | |
| Returns: | |
| Verification result | |
| Raises: | |
| HTTPException: If MFA not enabled | |
| """ | |
| if not current_user.mfa_enabled: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="MFA is not enabled for this account" | |
| ) | |
| mfa_service = MFAService(session) | |
| # Check for too many failed attempts (rate limiting) | |
| failed_attempts = mfa_service.get_failed_attempts_count(current_user, since_minutes=30) | |
| if failed_attempts >= 10: | |
| raise HTTPException( | |
| status_code=status.HTTP_429_TOO_MANY_REQUESTS, | |
| detail="Too many failed attempts. Please try again later." | |
| ) | |
| token = request.token.strip().replace(' ', '').replace('-', '') | |
| # Try TOTP first (6 digits) | |
| if len(token) == 6 and token.isdigit(): | |
| verified = mfa_service.verify_totp(current_user, token) | |
| if verified: | |
| return MFAVerifyResponse( | |
| verified=True, | |
| message="TOTP token verified successfully" | |
| ) | |
| # Try backup code (8 characters) | |
| if len(token) == 8: | |
| verified = mfa_service.verify_backup_code(current_user, token.upper()) | |
| if verified: | |
| # Warn user about remaining codes | |
| remaining = mfa_service.get_remaining_backup_codes_count(current_user) | |
| return MFAVerifyResponse( | |
| verified=True, | |
| message=f"Backup code verified. {remaining} backup codes remaining." | |
| ) | |
| return MFAVerifyResponse( | |
| verified=False, | |
| message="Invalid token or backup code" | |
| ) | |
| def disable_mfa( | |
| request: MFADisableRequest, | |
| current_user: AuthUser = Depends(get_current_active_user), | |
| session: Session = Depends(get_db_session) | |
| ): | |
| """ | |
| Disable Multi-Factor Authentication. | |
| Requires password confirmation and valid MFA token for security. | |
| Args: | |
| request: Password and MFA token | |
| Returns: | |
| Success message | |
| Raises: | |
| HTTPException: If password or token invalid | |
| """ | |
| # Verify password | |
| if not current_user.verify_password(request.password): | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid password" | |
| ) | |
| if not current_user.mfa_enabled: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="MFA is not enabled for this account" | |
| ) | |
| mfa_service = MFAService(session) | |
| # Verify token (TOTP or backup code) | |
| token = request.token.strip().replace(' ', '').replace('-', '') | |
| verified = False | |
| if len(token) == 6 and token.isdigit(): | |
| verified = mfa_service.verify_totp(current_user, token) | |
| elif len(token) == 8: | |
| verified = mfa_service.verify_backup_code(current_user, token.upper()) | |
| if not verified: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid MFA token" | |
| ) | |
| # Disable MFA | |
| mfa_service.disable_mfa(current_user) | |
| return { | |
| "message": "MFA has been disabled for your account", | |
| "mfa_enabled": False | |
| } | |
| def regenerate_backup_codes( | |
| current_user: AuthUser = Depends(get_current_active_user), | |
| session: Session = Depends(get_db_session) | |
| ): | |
| """ | |
| Regenerate backup codes. | |
| Expires all existing backup codes and generates new ones. | |
| Use when backup codes are lost or compromised. | |
| Returns: | |
| New backup codes (store securely!) | |
| Raises: | |
| HTTPException: If MFA not enabled | |
| """ | |
| if not current_user.mfa_enabled: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="MFA is not enabled for this account" | |
| ) | |
| mfa_service = MFAService(session) | |
| backup_codes = mfa_service.regenerate_backup_codes(current_user) | |
| return BackupCodesResponse( | |
| backup_codes=backup_codes, | |
| message="New backup codes generated. Previous codes are now invalid." | |
| ) | |
| # ============================================================================ | |
| # Admin Endpoints (MFA Policy Management) | |
| # ============================================================================ | |
| class MFAPolicyRequest(BaseModel): | |
| """Request to set MFA policy for a role.""" | |
| role_id: int | |
| required: bool | |
| grace_period_days: int = 30 | |
| backup_codes_count: int = 10 | |
| def set_mfa_policy( | |
| request: MFAPolicyRequest, | |
| current_user: AuthUser = Depends(get_current_active_user), | |
| session: Session = Depends(get_db_session) | |
| ): | |
| """ | |
| Set MFA policy for a role (Admin only). | |
| Args: | |
| request: MFA policy settings | |
| Returns: | |
| Updated MFA config | |
| Raises: | |
| HTTPException: If user not admin | |
| """ | |
| # TODO: Add admin permission check | |
| # For now, any authenticated user can set policy (will fix in RBAC integration) | |
| mfa_service = MFAService(session) | |
| config = mfa_service.set_mfa_policy( | |
| role_id=request.role_id, | |
| required=request.required, | |
| grace_period_days=request.grace_period_days, | |
| backup_codes_count=request.backup_codes_count | |
| ) | |
| return { | |
| "message": "MFA policy updated successfully", | |
| "config": { | |
| "role_id": config.role_id, | |
| "mfa_required": config.mfa_required, | |
| "grace_period_days": config.grace_period_days, | |
| "backup_codes_count": config.backup_codes_count | |
| } | |
| } | |
| def get_mfa_policy( | |
| role_id: int, | |
| current_user: AuthUser = Depends(get_current_active_user), | |
| session: Session = Depends(get_db_session) | |
| ): | |
| """ | |
| Get MFA policy for a role (Admin only). | |
| Args: | |
| role_id: Role ID | |
| Returns: | |
| MFA config for the role | |
| """ | |
| mfa_service = MFAService(session) | |
| config = mfa_service.get_mfa_config_for_role(role_id) | |
| if not config: | |
| return { | |
| "role_id": role_id, | |
| "mfa_required": False, | |
| "message": "No MFA policy set for this role" | |
| } | |
| return { | |
| "role_id": config.role_id, | |
| "mfa_required": config.mfa_required, | |
| "grace_period_days": config.grace_period_days, | |
| "backup_codes_count": config.backup_codes_count | |
| } | |