TT-003: complete request-module integration into modular platform
- integrated request-module into module registry - moved backend into modules/request-module - added manifest.json and module.py - implemented dynamic router mounting - implemented dynamic static mounting - removed direct dependencies from platform core - verified startup with request-module - verified startup without request-module - added implementation_report_003.md
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
"""Core module."""
|
||||
|
||||
from .security import decode_platform_token, get_user_id_from_token, get_roles_from_token
|
||||
from .database import get_db, engine, init_db
|
||||
from .exceptions import AppException, NotFoundException, UnauthorizedException
|
||||
from .middleware import add_security_headers, add_cors_middleware
|
||||
from .platform_client import PlatformUser, PlatformClient, get_platform_client
|
||||
|
||||
__all__ = [
|
||||
"decode_platform_token",
|
||||
"get_user_id_from_token",
|
||||
"get_roles_from_token",
|
||||
"get_db",
|
||||
"engine",
|
||||
"init_db",
|
||||
"AppException",
|
||||
"NotFoundException",
|
||||
"UnauthorizedException",
|
||||
"add_security_headers",
|
||||
"add_cors_middleware",
|
||||
"PlatformUser",
|
||||
"PlatformClient",
|
||||
"get_platform_client",
|
||||
]
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Authentication dependencies for platform integration."""
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.security import decode_platform_token, get_user_id_from_token
|
||||
from request_app.core.platform_client import PlatformUser, get_platform_client
|
||||
from request_app.models.user import User
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
def get_current_user_id(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
) -> int:
|
||||
"""Extract user ID from platform JWT token."""
|
||||
token = credentials.credentials
|
||||
try:
|
||||
return get_user_id_from_token(token)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
|
||||
def _sync_platform_user_to_local(db: Session, payload: dict) -> User:
|
||||
"""Create or update local user from platform JWT claims."""
|
||||
email = payload.get("email", "")
|
||||
first_name = payload.get("first_name", "")
|
||||
last_name = payload.get("last_name", "")
|
||||
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
is_active=True,
|
||||
source="platform",
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
else:
|
||||
user.first_name = first_name or user.first_name
|
||||
user.last_name = last_name or user.last_name
|
||||
user.is_active = payload.get("is_active", True)
|
||||
user.source = "platform"
|
||||
db.commit()
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Get current authenticated user, auto-syncing from platform."""
|
||||
token = credentials.credentials
|
||||
try:
|
||||
user_id = get_user_id_from_token(token)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
payload = decode_platform_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
user = _sync_platform_user_to_local(db, payload)
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is deactivated")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_current_platform_user(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
) -> PlatformUser:
|
||||
"""Get PlatformUser from JWT (for role checks)."""
|
||||
token = credentials.credentials
|
||||
try:
|
||||
user_id = get_user_id_from_token(token)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
payload = decode_platform_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
return PlatformUser(
|
||||
id=user_id,
|
||||
email=payload.get("email", ""),
|
||||
first_name=payload.get("first_name", ""),
|
||||
last_name=payload.get("last_name", ""),
|
||||
is_active=payload.get("is_active", True),
|
||||
roles=payload.get("roles", []),
|
||||
)
|
||||
|
||||
|
||||
def require_admin(
|
||||
user: PlatformUser = Depends(get_current_platform_user),
|
||||
) -> PlatformUser:
|
||||
"""Require admin role."""
|
||||
if not user.has_role("admin"):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
||||
return user
|
||||
|
||||
|
||||
def require_role(role_name: str):
|
||||
"""Dependency factory: require a specific role."""
|
||||
def _check_role(user: PlatformUser = Depends(get_current_platform_user)) -> PlatformUser:
|
||||
if not user.has_role(role_name):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"Role '{role_name}' required")
|
||||
return user
|
||||
return _check_role
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Database utilities and session management."""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from typing import Generator
|
||||
from request_app.settings import get_settings
|
||||
from request_app.models.base import Base
|
||||
|
||||
# Create database engine
|
||||
settings = get_settings()
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
pool_pre_ping=True,
|
||||
echo=settings.APP_DEBUG
|
||||
)
|
||||
|
||||
# Create session factory
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
"""
|
||||
Dependency function to get database session.
|
||||
Yields a session and ensures it's closed after use.
|
||||
"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Initialize database - create all tables and default data."""
|
||||
from request_app.models import (
|
||||
user, priority, status, category,
|
||||
ticket, comment, notification, extra
|
||||
)
|
||||
from request_app.models.role import Role
|
||||
from request_app.models.user_role import UserRole
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Create default roles
|
||||
db = SessionLocal()
|
||||
try:
|
||||
default_roles = [
|
||||
("admin", "Administrator with full access", True),
|
||||
("support_agent", "Support agent - create and update tickets", True),
|
||||
("manager", "Manager - view all tickets, create teams", True),
|
||||
("customer", "Customer - read-only, create tickets", True),
|
||||
]
|
||||
for name, description, is_system in default_roles:
|
||||
if not db.query(Role).filter(Role.name == name).first():
|
||||
db.add(Role(name=name, description=description, is_system=is_system))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""Initialize database when running as script."""
|
||||
init_db()
|
||||
print("Database initialized successfully!")
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Custom exception handlers."""
|
||||
|
||||
from fastapi import Request, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from pydantic import ValidationError
|
||||
from request_app.core.exceptions import AppException
|
||||
|
||||
|
||||
async def app_exception_handler(request: Request, exc: Exception):
|
||||
"""Handle all unhandled exceptions."""
|
||||
if isinstance(exc, AppException):
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"message": exc.message,
|
||||
"error_code": exc.error_code,
|
||||
"success": False
|
||||
}
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
content={
|
||||
"message": "Internal server error",
|
||||
"success": False
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
"""Handle validation errors."""
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
content={
|
||||
"message": "Validation error",
|
||||
"errors": exc.errors(),
|
||||
"success": False
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def pydantic_validation_exception_handler(request: Request, exc: ValidationError):
|
||||
"""Handle Pydantic validation errors."""
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
content={
|
||||
"message": "Validation error",
|
||||
"errors": exc.errors(),
|
||||
"success": False
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Custom exception classes."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class AppException(Exception):
|
||||
"""Base application exception."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
status_code: int = 500,
|
||||
error_code: Optional[str] = None
|
||||
):
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
self.error_code = error_code
|
||||
super().__init__(self.message)
|
||||
|
||||
|
||||
class NotFoundException(AppException):
|
||||
"""Resource not found exception."""
|
||||
|
||||
def __init__(self, message: str = "Resource not found"):
|
||||
super().__init__(message, status_code=404, error_code="NOT_FOUND")
|
||||
|
||||
|
||||
class UnauthorizedException(AppException):
|
||||
"""Authentication/authorization exception."""
|
||||
|
||||
def __init__(self, message: str = "Unauthorized access"):
|
||||
super().__init__(message, status_code=401, error_code="UNAUTHORIZED")
|
||||
|
||||
|
||||
class ForbiddenException(AppException):
|
||||
"""Permission denied exception."""
|
||||
|
||||
def __init__(self, message: str = "Permission denied"):
|
||||
super().__init__(message, status_code=403, error_code="FORBIDDEN")
|
||||
|
||||
|
||||
class ValidationException(AppException):
|
||||
"""Validation error exception."""
|
||||
|
||||
def __init__(self, message: str, details: Optional[list] = None):
|
||||
super().__init__(message, status_code=422, error_code="VALIDATION_ERROR")
|
||||
self.details = details or []
|
||||
|
||||
|
||||
class ConflictException(AppException):
|
||||
"""Resource conflict exception."""
|
||||
|
||||
def __init__(self, message: str = "Resource already exists"):
|
||||
super().__init__(message, status_code=409, error_code="CONFLICT")
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Logging configuration with rotation and configurable levels."""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
# Create logs directory
|
||||
LOGS_DIR = Path(__file__).parent.parent.parent / "logs"
|
||||
LOGS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
# Store handlers for dynamic level changes
|
||||
_console_handler = None
|
||||
_file_handler = None
|
||||
_error_handler = None
|
||||
|
||||
# Rotation defaults
|
||||
DEFAULT_MAX_BYTES = 5 * 1024 * 1024 # 5 MB per file
|
||||
DEFAULT_BACKUP_COUNT = 5 # Keep 5 rotated files
|
||||
|
||||
LOG_LEVELS = {
|
||||
"DEBUG": logging.DEBUG,
|
||||
"INFO": logging.INFO,
|
||||
"WARNING": logging.WARNING,
|
||||
"ERROR": logging.ERROR,
|
||||
}
|
||||
|
||||
|
||||
def setup_logging(console_level: str = "INFO", file_level: str = "DEBUG",
|
||||
max_bytes: int = DEFAULT_MAX_BYTES, backup_count: int = DEFAULT_BACKUP_COUNT):
|
||||
"""Setup application logging with rotation."""
|
||||
global _console_handler, _file_handler, _error_handler
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(logging.DEBUG)
|
||||
|
||||
file_format = logging.Formatter(
|
||||
'%(asctime)s %(levelname)-8s %(name)s [%(filename)s:%(lineno)d]: %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
console_format = logging.Formatter(
|
||||
'%(asctime)s %(levelname)-8s %(name)s: %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
# Console handler
|
||||
_console_handler = logging.StreamHandler(sys.stdout)
|
||||
_console_handler.setLevel(LOG_LEVELS.get(console_level.upper(), logging.INFO))
|
||||
_console_handler.setFormatter(console_format)
|
||||
|
||||
# Rotating file handler for all logs
|
||||
_file_handler = RotatingFileHandler(
|
||||
LOGS_DIR / "app.log",
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding='utf-8'
|
||||
)
|
||||
_file_handler.setLevel(LOG_LEVELS.get(file_level.upper(), logging.DEBUG))
|
||||
_file_handler.setFormatter(file_format)
|
||||
|
||||
# Rotating file handler for errors only
|
||||
_error_handler = RotatingFileHandler(
|
||||
LOGS_DIR / "error.log",
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding='utf-8'
|
||||
)
|
||||
_error_handler.setLevel(logging.ERROR)
|
||||
_error_handler.setFormatter(file_format)
|
||||
|
||||
root_logger.addHandler(_console_handler)
|
||||
root_logger.addHandler(_file_handler)
|
||||
root_logger.addHandler(_error_handler)
|
||||
|
||||
# Reduce noise from libraries
|
||||
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
||||
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
|
||||
|
||||
return root_logger
|
||||
|
||||
|
||||
def set_log_level(console_level: str = None, file_level: str = None):
|
||||
"""Change log levels at runtime."""
|
||||
changed = []
|
||||
if console_level and console_level.upper() in LOG_LEVELS:
|
||||
_console_handler.setLevel(LOG_LEVELS[console_level.upper()])
|
||||
changed.append(f"console={console_level.upper()}")
|
||||
if file_level and file_level.upper() in LOG_LEVELS:
|
||||
_file_handler.setLevel(LOG_LEVELS[file_level.upper()])
|
||||
changed.append(f"file={file_level.upper()}")
|
||||
if changed:
|
||||
logger.info(f"Log levels changed: {', '.join(changed)}")
|
||||
return bool(changed)
|
||||
|
||||
|
||||
def get_log_config() -> dict:
|
||||
"""Return current logging configuration."""
|
||||
return {
|
||||
"console_level": logging.getLevelName(_console_handler.level) if _console_handler else "N/A",
|
||||
"file_level": logging.getLevelName(_file_handler.level) if _file_handler else "N/A",
|
||||
"max_bytes": _file_handler.maxBytes if _file_handler else 0,
|
||||
"backup_count": _file_handler.backupCount if _file_handler else 0,
|
||||
}
|
||||
|
||||
|
||||
# Logger instances
|
||||
logger = logging.getLogger("app")
|
||||
email_logger = logging.getLogger("app.email")
|
||||
sms_logger = logging.getLogger("app.sms")
|
||||
auth_logger = logging.getLogger("app.auth")
|
||||
ticket_logger = logging.getLogger("app.ticket")
|
||||
notification_logger = logging.getLogger("app.notification")
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Middleware for authentication and security headers."""
|
||||
|
||||
from fastapi import Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
from fastapi import FastAPI
|
||||
import os
|
||||
|
||||
|
||||
def add_security_headers(app: FastAPI):
|
||||
"""Add security headers to all responses."""
|
||||
|
||||
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
response: Response = await call_next(request)
|
||||
|
||||
# Security headers
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
response.headers["X-XSS-Protection"] = "1; mode=block"
|
||||
response.headers["Content-Security-Policy"] = "frame-ancestors *"
|
||||
|
||||
# CORS headers
|
||||
response.headers["Access-Control-Allow-Origin"] = os.getenv(
|
||||
"APP_CORS_ORIGINS",
|
||||
"http://localhost:3000"
|
||||
)
|
||||
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
|
||||
response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
|
||||
|
||||
return response
|
||||
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
|
||||
|
||||
def add_cors_middleware(app: FastAPI):
|
||||
"""Add CORS middleware."""
|
||||
|
||||
cors_origins = os.getenv("APP_CORS_ORIGINS", "http://localhost:3000").split(",")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Client for interacting with the common platform API."""
|
||||
|
||||
import httpx
|
||||
from typing import Optional, List, Dict, Any
|
||||
from request_app.settings import get_settings
|
||||
from request_app.core.logging import logger
|
||||
|
||||
|
||||
class PlatformUser:
|
||||
"""Wrapper for user data from the platform."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
id: int,
|
||||
email: str,
|
||||
first_name: str = "",
|
||||
last_name: str = "",
|
||||
is_active: bool = True,
|
||||
roles: Optional[List[str]] = None,
|
||||
):
|
||||
self.id = id
|
||||
self.email = email
|
||||
self.first_name = first_name
|
||||
self.last_name = last_name
|
||||
self.is_active = is_active
|
||||
self.roles = roles or []
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
if self.first_name or self.last_name:
|
||||
return f"{self.first_name} {self.last_name}".strip()
|
||||
return self.email
|
||||
|
||||
def has_role(self, role_name: str) -> bool:
|
||||
return role_name in self.roles
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": self.id,
|
||||
"email": self.email,
|
||||
"first_name": self.first_name,
|
||||
"last_name": self.last_name,
|
||||
"is_active": self.is_active,
|
||||
"roles": self.roles,
|
||||
}
|
||||
|
||||
|
||||
class PlatformClient:
|
||||
"""Client for the common platform REST API."""
|
||||
|
||||
def __init__(self):
|
||||
settings = get_settings()
|
||||
self.base_url = settings.PLATFORM_API_URL.rstrip("/")
|
||||
self.api_key = settings.PLATFORM_API_KEY
|
||||
self.timeout = 10.0
|
||||
|
||||
def _get_headers(self, token: Optional[str] = None) -> Dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
headers["X-API-Key"] = self.api_key
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
return headers
|
||||
|
||||
async def validate_token(self, token: str) -> Optional[PlatformUser]:
|
||||
"""Validate JWT token with the platform and return user data."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.post(
|
||||
f"{self.base_url}/api/v1/auth/validate",
|
||||
headers=self._get_headers(token),
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return PlatformUser(
|
||||
id=data["user_id"],
|
||||
email=data.get("email", ""),
|
||||
first_name=data.get("first_name", ""),
|
||||
last_name=data.get("last_name", ""),
|
||||
is_active=data.get("is_active", True),
|
||||
roles=data.get("roles", []),
|
||||
)
|
||||
logger.warning(f"Token validation failed: {response.status_code}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Platform token validation error: {e}")
|
||||
return None
|
||||
|
||||
async def get_user_info(self, user_id: int) -> Optional[PlatformUser]:
|
||||
"""Get user information from the platform."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/api/v1/users/{user_id}",
|
||||
headers=self._get_headers(),
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return PlatformUser(
|
||||
id=data["id"],
|
||||
email=data.get("email", ""),
|
||||
first_name=data.get("first_name", ""),
|
||||
last_name=data.get("last_name", ""),
|
||||
is_active=data.get("is_active", True),
|
||||
roles=data.get("roles", []),
|
||||
)
|
||||
logger.warning(f"Get user info failed: {response.status_code}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Platform get user error: {e}")
|
||||
return None
|
||||
|
||||
async def get_user_roles(self, user_id: int) -> List[str]:
|
||||
"""Get user roles from the platform."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/api/v1/users/{user_id}/roles",
|
||||
headers=self._get_headers(),
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return data.get("roles", [])
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(f"Platform get user roles error: {e}")
|
||||
return []
|
||||
|
||||
async def get_users(
|
||||
self, page: int = 1, page_size: int = 100, search: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get paginated list of users from the platform."""
|
||||
try:
|
||||
params = {"page": page, "page_size": page_size}
|
||||
if search:
|
||||
params["search"] = search
|
||||
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/api/v1/users",
|
||||
headers=self._get_headers(),
|
||||
params=params,
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
users = [
|
||||
PlatformUser(
|
||||
id=u["id"],
|
||||
email=u.get("email", ""),
|
||||
first_name=u.get("first_name", ""),
|
||||
last_name=u.get("last_name", ""),
|
||||
is_active=u.get("is_active", True),
|
||||
roles=u.get("roles", []),
|
||||
)
|
||||
for u in data.get("users", [])
|
||||
]
|
||||
return {
|
||||
"users": users,
|
||||
"total": data.get("total", 0),
|
||||
}
|
||||
return {"users": [], "total": 0}
|
||||
except Exception as e:
|
||||
logger.error(f"Platform get users error: {e}")
|
||||
return {"users": [], "total": 0}
|
||||
|
||||
async def check_permission(self, user_id: int, permission: str) -> bool:
|
||||
"""Check if user has a specific permission on the platform."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/api/v1/users/{user_id}/permissions/{permission}",
|
||||
headers=self._get_headers(),
|
||||
)
|
||||
return response.status_code == 200 and response.json().get(
|
||||
"allowed", False
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Platform check permission error: {e}")
|
||||
return False
|
||||
|
||||
|
||||
_platform_client: Optional[PlatformClient] = None
|
||||
|
||||
|
||||
def get_platform_client() -> PlatformClient:
|
||||
"""Get or create the platform client singleton."""
|
||||
global _platform_client
|
||||
if _platform_client is None:
|
||||
_platform_client = PlatformClient()
|
||||
return _platform_client
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Core module for security and authentication utilities."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
from jose import JWTError, jwt
|
||||
import bcrypt
|
||||
from request_app.settings import get_settings
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Hash a password."""
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
"""Verify a password against its hash."""
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def create_local_token(user_id: int, email: str) -> str:
|
||||
"""Create a local JWT token for standalone mode."""
|
||||
settings = get_settings()
|
||||
expire = datetime.utcnow() + timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
payload = {"sub": str(user_id), "email": email, "exp": expire}
|
||||
return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_platform_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
"""Decode and verify a JWT token (from platform or local)."""
|
||||
settings = get_settings()
|
||||
|
||||
# Try platform key first
|
||||
if settings.PLATFORM_JWT_PUBLIC_KEY:
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
settings.PLATFORM_JWT_PUBLIC_KEY,
|
||||
algorithms=[settings.PLATFORM_JWT_ALGORITHM],
|
||||
)
|
||||
except JWTError:
|
||||
pass
|
||||
|
||||
# Try local key
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
settings.JWT_SECRET_KEY,
|
||||
algorithms=[settings.JWT_ALGORITHM],
|
||||
)
|
||||
except JWTError:
|
||||
return None
|
||||
|
||||
|
||||
def get_user_id_from_token(token: str) -> int:
|
||||
"""Extract user ID from platform JWT token."""
|
||||
payload = decode_platform_token(token)
|
||||
if not payload:
|
||||
raise ValueError("Invalid token")
|
||||
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise ValueError("Invalid token: missing 'sub' claim")
|
||||
|
||||
return int(user_id)
|
||||
|
||||
|
||||
def get_roles_from_token(token: str) -> list:
|
||||
"""Extract roles from platform JWT token."""
|
||||
payload = decode_platform_token(token)
|
||||
if not payload:
|
||||
return []
|
||||
return payload.get("roles", [])
|
||||
Reference in New Issue
Block a user