Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /auth_simple.py
| """ | |
| Einfache JWT Authentication für Zen-AI Pentest API | |
| """ | |
| import os | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Dict, Optional | |
| import jwt | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPBearer | |
| from jwt import InvalidTokenError | |
| from passlib.context import CryptContext | |
| # Konfiguration | |
| SECRET_KEY = os.getenv("JWT_SECRET_KEY") or os.getenv("SECRET_KEY") | |
| if not SECRET_KEY or SECRET_KEY == "your-secret-key-change-in-production": | |
| raise RuntimeError( | |
| "CRITICAL: JWT_SECRET_KEY environment variable is not set or uses default value. " | |
| "Please generate a secure key: export JWT_SECRET_KEY=$(openssl rand -hex 32)" | |
| ) | |
| ALGORITHM = "HS256" | |
| # Token expiration: 60 minutes (OWASP recommendation: 15-60 minutes) | |
| ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60")) | |
| # Password hashing - Using bcrypt (more secure than sha256_crypt) | |
| pwd_context = CryptContext( | |
| schemes=["bcrypt"], | |
| deprecated="auto", | |
| bcrypt__rounds=12, # OWASP recommended minimum | |
| ) | |
| # Security scheme | |
| security = HTTPBearer(auto_error=False) | |
| # In-memory user store (Production: Datenbank nutzen!) | |
| # Format: {username: {"password": hashed_password, "role": "admin|user"}} | |
| # Admin password MUST be set via ADMIN_PASSWORD environment variable | |
| _admin_password = os.getenv("ADMIN_PASSWORD") | |
| if not _admin_password: | |
| raise RuntimeError( | |
| "CRITICAL: ADMIN_PASSWORD environment variable is not set. " | |
| "Please set a strong password: export ADMIN_PASSWORD=$(openssl rand -hex 32)" | |
| ) | |
| USERS_DB = {"admin": {"password": pwd_context.hash(_admin_password), "role": "admin"}} | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| """Verifiziert Passwort gegen Hash""" | |
| return pwd_context.verify(plain_password, hashed_password) | |
| def get_password_hash(password: str) -> str: | |
| """Erstellt Passwort-Hash""" | |
| return pwd_context.hash(password) | |
| def authenticate_user(username: str, password: str) -> Optional[Dict]: | |
| """Authentifiziert User und gibt User-Daten zurück""" | |
| user = USERS_DB.get(username) | |
| if not user: | |
| return None | |
| if not verify_password(password, user["password"]): | |
| return None | |
| return {"username": username, "role": user["role"]} | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: | |
| """Erstellt JWT Access Token""" | |
| to_encode = data.copy() | |
| expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)) | |
| to_encode.update({"exp": expire}) | |
| return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
| def verify_token( | |
| credentials=Depends(security), | |
| ) -> Dict: | |
| """ | |
| Verifiziert JWT Token aus Authorization Header | |
| Verwendet als Dependency in Protected Routes | |
| """ | |
| if hasattr(credentials, "credentials"): | |
| token = credentials.credentials | |
| elif hasattr(credentials, "headers"): | |
| # Received a Request object directly | |
| auth_header = credentials.headers.get("Authorization", "") | |
| if not auth_header.startswith("Bearer "): | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid authorization header", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| token = auth_header[7:] | |
| else: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Authorization header missing", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| username: str = payload.get("sub") | |
| role: str = payload.get("role", "user") | |
| if username is None: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| return {"username": username, "role": role} | |
| except jwt.ExpiredSignatureError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Token expired", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| except InvalidTokenError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| def require_admin(user: Dict = Depends(verify_token)) -> Dict: | |
| """Prüft ob User Admin-Rechte hat""" | |
| if user.get("role") != "admin": | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Admin privileges required", | |
| ) | |
| return user | |
| # Optional: User Management Funktionen | |
| def create_user(username: str, password: str, role: str = "user") -> bool: | |
| """Erstellt neuen User""" | |
| if username in USERS_DB: | |
| return False | |
| USERS_DB[username] = { | |
| "password": get_password_hash(password), | |
| "role": role, | |
| } | |
| return True | |
| def list_users() -> Dict: | |
| """Listet alle Users (ohne Passwörter)""" | |
| return {k: {"role": v["role"]} for k, v in USERS_DB.items()} | |
Xet Storage Details
- Size:
- 5.23 kB
- Xet hash:
- c5a748268dfbc624ea91c75794e7eca23fc0cca7c41024705806f7b6e2ba71ab
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.