Implement a comprehensive web-based dashboard for managing Telegram and Discord bots with real-time monitoring, process control, and beautiful UI. Backend (FastAPI): - Complete REST API with OpenAPI documentation - WebSocket support for real-time log streaming and statistics - SQLAlchemy models for bots, logs, and users - JWT-based authentication system - Process management with subprocess and psutil - Auto-restart functionality with configurable backoff - System and bot resource monitoring (CPU, RAM, network) - Comprehensive error handling and logging Frontend (Next.js 14 + TypeScript): - Modern React application with App Router - shadcn/ui components with Tailwind CSS - TanStack Query for data fetching and caching - Real-time WebSocket integration - Responsive design for mobile, tablet, and desktop - Beautiful dark theme with glassmorphism effects - Bot cards with status badges and controls - System statistics dashboard Example Bots: - Telegram userbot using Telethon - Telegram bot using python-telegram-bot - Discord bot using discord.py - Full command examples and error handling Infrastructure: - Docker and Docker Compose configurations - Multi-stage builds for optimal image sizes - Nginx reverse proxy with WebSocket support - Production and development compose files - Rate limiting and security headers Documentation: - Comprehensive README with setup instructions - API documentation examples - Configuration guides - Troubleshooting section - Makefile for common commands Features: - Start/stop/restart bots with one click - Real-time log streaming via WebSocket - Live system and bot statistics - Auto-restart on crashes - Bot configuration management - Process monitoring and resource tracking - Search and filter bots - Responsive UI with loading states - Toast notifications for all actions Security: - JWT token-based authentication - Password hashing with bcrypt - CORS configuration - Environment variable management - Input validation and sanitization - Rate limiting in nginx - Security headers configured
93 lines
2.5 KiB
Python
93 lines
2.5 KiB
Python
"""Security utilities for authentication and authorization."""
|
|
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional, Dict, Any
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
|
|
from app.config import settings
|
|
|
|
# Password hashing context
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
"""
|
|
Verify a password against a hashed password.
|
|
|
|
Args:
|
|
plain_password: Plain text password
|
|
hashed_password: Hashed password from database
|
|
|
|
Returns:
|
|
True if password matches, False otherwise
|
|
"""
|
|
return pwd_context.verify(plain_password, hashed_password)
|
|
|
|
|
|
def get_password_hash(password: str) -> str:
|
|
"""
|
|
Hash a password using bcrypt.
|
|
|
|
Args:
|
|
password: Plain text password
|
|
|
|
Returns:
|
|
Hashed password string
|
|
"""
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def create_access_token(data: Dict[str, Any]) -> str:
|
|
"""
|
|
Create a JWT access token.
|
|
|
|
Args:
|
|
data: Dictionary of claims to encode in token
|
|
|
|
Returns:
|
|
Encoded JWT token string
|
|
"""
|
|
to_encode = data.copy()
|
|
expire = datetime.utcnow() + 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, Any]) -> str:
|
|
"""
|
|
Create a JWT refresh token with longer expiration.
|
|
|
|
Args:
|
|
data: Dictionary of claims to encode in token
|
|
|
|
Returns:
|
|
Encoded JWT token string
|
|
"""
|
|
to_encode = data.copy()
|
|
expire = datetime.utcnow() + 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
|
|
|
|
|
|
def verify_token(token: str, token_type: str = "access") -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Verify and decode a JWT token.
|
|
|
|
Args:
|
|
token: JWT token string
|
|
token_type: Expected token type ("access" or "refresh")
|
|
|
|
Returns:
|
|
Decoded token payload if valid, None otherwise
|
|
"""
|
|
try:
|
|
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
|
|
if payload.get("type") != token_type:
|
|
return None
|
|
return payload
|
|
except JWTError:
|
|
return None
|