Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /poc /backend /app /routers /auth.py
| """ | |
| Authentication router for login, register, and token management. | |
| """ | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Optional | |
| import jwt | |
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm | |
| from passlib.context import CryptContext | |
| from sqlalchemy import or_ | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy.future import select | |
| from app.core.config import settings | |
| from app.core.database import get_db | |
| from app.models.user import User, UserRole | |
| from app.schemas.auth import ( | |
| LoginResponse, | |
| RefreshTokenRequest, | |
| RegisterRequest, | |
| TokenPayload, | |
| UserResponse, | |
| ) | |
| router = APIRouter() | |
| # Password hashing | |
| pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | |
| # OAuth2 scheme | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login") | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| """Verify a password against its hash.""" | |
| return pwd_context.verify(plain_password, hashed_password) | |
| def get_password_hash(password: str) -> str: | |
| """Hash a password.""" | |
| return pwd_context.hash(password) | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: | |
| """Create a JWT access token.""" | |
| to_encode = data.copy() | |
| if expires_delta: | |
| expire = datetime.now(timezone.utc) + expires_delta | |
| else: | |
| expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"exp": expire, "type": "access"}) | |
| encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM) | |
| return encoded_jwt | |
| def create_refresh_token(data: dict) -> str: | |
| """Create a JWT refresh token.""" | |
| to_encode = data.copy() | |
| expire = datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS) | |
| to_encode.update({"exp": expire, "type": "refresh"}) | |
| encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM) | |
| return encoded_jwt | |
| async def get_current_user(token: str = Depends(oauth2_scheme), db: AsyncSession = Depends(get_db)) -> User: | |
| """Get the current user from the JWT token.""" | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM]) | |
| user_id: str = payload.get("sub") | |
| token_type: str = payload.get("type") | |
| if user_id is None or token_type != "access": | |
| raise credentials_exception | |
| token_data = TokenPayload(user_id=user_id) | |
| except (jwt.ExpiredSignatureError, jwt.InvalidTokenError): | |
| raise credentials_exception | |
| result = await db.execute(select(User).where(User.id == token_data.user_id)) | |
| user = result.scalar_one_or_none() | |
| if user is None: | |
| raise credentials_exception | |
| if not user.is_active: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="User account is deactivated", | |
| ) | |
| return user | |
| async def get_current_active_user( | |
| current_user: User = Depends(get_current_user), | |
| ) -> User: | |
| """Get the current active user.""" | |
| if not current_user.is_active: | |
| raise HTTPException(status_code=400, detail="Inactive user") | |
| return current_user | |
| async def require_admin( | |
| current_user: User = Depends(get_current_user), | |
| ) -> User: | |
| """Require admin role.""" | |
| if current_user.role != UserRole.ADMIN: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Admin access required", | |
| ) | |
| return current_user | |
| async def register(register_data: RegisterRequest, db: AsyncSession = Depends(get_db)): | |
| """Register a new user.""" | |
| # Check if user already exists | |
| result = await db.execute( | |
| select(User).where( | |
| or_( | |
| User.email == register_data.email, | |
| User.username == register_data.username, | |
| ) | |
| ) | |
| ) | |
| existing_user = result.scalar_one_or_none() | |
| if existing_user: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="User with this email or username already exists", | |
| ) | |
| # Create new user | |
| hashed_password = get_password_hash(register_data.password) | |
| new_user = User( | |
| email=register_data.email, | |
| username=register_data.username, | |
| hashed_password=hashed_password, | |
| full_name=register_data.full_name, | |
| role=UserRole.VIEWER, # Default role | |
| is_active=True, | |
| is_verified=False, | |
| ) | |
| db.add(new_user) | |
| await db.commit() | |
| await db.refresh(new_user) | |
| return UserResponse(success=True, data=new_user.to_dict()) | |
| async def login( | |
| form_data: OAuth2PasswordRequestForm = Depends(), | |
| db: AsyncSession = Depends(get_db), | |
| ): | |
| """Login with email/username and password.""" | |
| # Find user by email or username | |
| result = await db.execute( | |
| select(User).where( | |
| or_( | |
| User.email == form_data.username, | |
| User.username == form_data.username, | |
| ) | |
| ) | |
| ) | |
| user = result.scalar_one_or_none() | |
| if not user or not verify_password(form_data.password, user.hashed_password): | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Incorrect email/username or password", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| if not user.is_active: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="User account is deactivated", | |
| ) | |
| # Update last login | |
| user.last_login = datetime.now(timezone.utc) | |
| await db.commit() | |
| # Create tokens | |
| access_token = create_access_token(data={"sub": str(user.id)}) | |
| refresh_token = create_refresh_token(data={"sub": str(user.id)}) | |
| return LoginResponse( | |
| success=True, | |
| data={ | |
| "access_token": access_token, | |
| "refresh_token": refresh_token, | |
| "token_type": "bearer", | |
| "user": user.to_dict(), | |
| }, | |
| ) | |
| async def refresh_token(refresh_data: RefreshTokenRequest, db: AsyncSession = Depends(get_db)): | |
| """Refresh access token using refresh token.""" | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| payload = jwt.decode( | |
| refresh_data.refresh_token, | |
| settings.SECRET_KEY, | |
| algorithms=[settings.JWT_ALGORITHM], | |
| ) | |
| user_id: str = payload.get("sub") | |
| token_type: str = payload.get("type") | |
| if user_id is None or token_type != "refresh": | |
| raise credentials_exception | |
| except (jwt.ExpiredSignatureError, jwt.InvalidTokenError): | |
| raise credentials_exception | |
| # Get user | |
| result = await db.execute(select(User).where(User.id == user_id)) | |
| user = result.scalar_one_or_none() | |
| if user is None or not user.is_active: | |
| raise credentials_exception | |
| # Create new tokens | |
| access_token = create_access_token(data={"sub": str(user.id)}) | |
| refresh_token = create_refresh_token(data={"sub": str(user.id)}) | |
| return LoginResponse( | |
| success=True, | |
| data={ | |
| "access_token": access_token, | |
| "refresh_token": refresh_token, | |
| "token_type": "bearer", | |
| "user": user.to_dict(), | |
| }, | |
| ) | |
| async def get_me(current_user: User = Depends(get_current_active_user)): | |
| """Get current user information.""" | |
| return UserResponse(success=True, data=current_user.to_dict()) | |
| async def logout(current_user: User = Depends(get_current_active_user)): | |
| """Logout user (client should discard tokens).""" | |
| # In a more complex implementation, you might want to blacklist the token | |
| return {"success": True, "message": "Successfully logged out"} | |
Xet Storage Details
- Size:
- 8.51 kB
- Xet hash:
- 927bf1fd1ac27fe778e79922d5458a3084a9bbf3b6115fe71af4241076b9abe0
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.