Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /routes /auth_oauth.py
| """ | |
| OAuth2 Authentication API Routes | |
| ================================ | |
| Endpoints for OAuth2 login flow | |
| """ | |
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from fastapi.responses import RedirectResponse | |
| from sqlalchemy.orm import Session | |
| from auth.jwt_handler import ( | |
| create_access_token, | |
| create_refresh_token, | |
| get_current_user, | |
| ) | |
| from auth.oauth import ( | |
| OAuthProvider, | |
| OAuthUserManager, | |
| get_available_providers, | |
| get_oauth_manager, | |
| ) | |
| from database.models import get_db | |
| router = APIRouter(prefix="/auth/oauth", tags=["OAuth Authentication"]) | |
| async def list_oauth_providers(): | |
| """List available OAuth providers""" | |
| return {"providers": get_available_providers()} | |
| async def oauth_login(provider: str, redirect: str = "/"): | |
| """Initiate OAuth login flow | |
| Security: redirect URL is validated to prevent open redirect attacks. | |
| Only relative paths or same-origin URLs are allowed. | |
| """ | |
| try: | |
| manager = get_oauth_manager(provider) | |
| # SECURITY: Validate redirect URL to prevent open redirect attacks | |
| # Only allow relative paths or URLs without protocol/host | |
| if redirect.startswith(("http://", "https://", "//", "javascript:", "data:")): | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Invalid redirect URL: absolute URLs not allowed", | |
| ) | |
| # Only allow paths starting with / (relative paths) | |
| if not redirect.startswith("/"): | |
| redirect = "/" | |
| # Store redirect URL in state | |
| import base64 | |
| import json | |
| state = base64.b64encode(json.dumps({"redirect": redirect}).encode()).decode() | |
| auth_url = manager.get_authorize_url(state=state) | |
| return RedirectResponse(url=auth_url) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail=f"OAuth initialization failed: {str(e)}", | |
| ) | |
| async def oauth_callback( | |
| provider: str, | |
| code: str = None, | |
| state: str = None, | |
| error: str = None, | |
| db: Session = Depends(get_db), | |
| ): | |
| """Handle OAuth callback""" | |
| if error: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail=f"OAuth error: {error}", | |
| ) | |
| if not code: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Authorization code missing", | |
| ) | |
| try: | |
| manager = get_oauth_manager(provider) | |
| # Exchange code for token | |
| token_data = await manager.exchange_code(code) | |
| access_token = token_data.get("access_token") | |
| if not access_token: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Failed to obtain access token", | |
| ) | |
| # Get user info | |
| user_info = await manager.get_user_info(access_token) | |
| normalized_info = manager.normalize_user_info(user_info) | |
| # Create or get user | |
| user_manager = OAuthUserManager(db) | |
| user = await user_manager.get_or_create_oauth_user( | |
| provider=OAuthProvider(provider), | |
| provider_id=normalized_info["provider_id"], | |
| email=normalized_info["email"], | |
| name=normalized_info["name"], | |
| picture=normalized_info["picture"], | |
| ) | |
| # Create JWT tokens | |
| jwt_access = create_access_token(data={"sub": user.username, "role": user.role}) | |
| jwt_refresh = create_refresh_token(data={"sub": user.username}) | |
| # Parse state for redirect | |
| redirect_url = "/" | |
| if state: | |
| try: | |
| import base64 | |
| import json | |
| state_data = json.loads(base64.b64decode(state).decode()) | |
| redirect_url = state_data.get("redirect", "/") | |
| except Exception: | |
| pass | |
| # Return tokens (in production, you might redirect with tokens in URL fragment) | |
| return { | |
| "access_token": jwt_access, | |
| "refresh_token": jwt_refresh, | |
| "token_type": "bearer", | |
| "user": { | |
| "id": user.id, | |
| "username": user.username, | |
| "email": user.email, | |
| "role": user.role, | |
| }, | |
| "redirect": redirect_url, | |
| } | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail=f"OAuth callback failed: {str(e)}", | |
| ) | |
| async def link_oauth_account( | |
| provider: str, | |
| code: str, | |
| current_user=Depends(get_current_user), # You'll need to implement this | |
| db: Session = Depends(get_db), | |
| ): | |
| """Link OAuth account to existing user""" | |
| try: | |
| manager = get_oauth_manager(provider) | |
| # Exchange code for token | |
| token_data = await manager.exchange_code(code) | |
| access_token = token_data.get("access_token") | |
| # Get user info | |
| user_info = await manager.get_user_info(access_token) | |
| normalized_info = manager.normalize_user_info(user_info) | |
| # Update user with OAuth info | |
| current_user.oauth_provider = provider | |
| current_user.oauth_provider_id = normalized_info["provider_id"] | |
| db.commit() | |
| return {"message": "OAuth account linked successfully"} | |
| except Exception as e: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail=f"Failed to link account: {str(e)}", | |
| ) | |
| async def unlink_oauth_account( | |
| provider: str, | |
| current_user=Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """Unlink OAuth account""" | |
| if current_user.oauth_provider != provider: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="This OAuth provider is not linked", | |
| ) | |
| # Check if user has password set | |
| if not current_user.hashed_password: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Cannot unlink OAuth without setting a password first", | |
| ) | |
| current_user.oauth_provider = None | |
| current_user.oauth_provider_id = None | |
| db.commit() | |
| return {"message": "OAuth account unlinked successfully"} | |
Xet Storage Details
- Size:
- 6.61 kB
- Xet hash:
- 70c76507b33b6849b5a496c0dca098526750aa165c0aa7b114149fdaf87f9160
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.