gateway/routes/routeGeneral.py

81 lines
No EOL
2.7 KiB
Python

from fastapi import APIRouter, HTTPException, Depends, Body, status, Response
from fastapi.responses import FileResponse
from fastapi.security import OAuth2PasswordRequestForm
from typing import Dict, Any
from datetime import timedelta
import pathlib
import os
from modules.configuration import APP_CONFIG
from modules.auth import (
createAccessToken,
getCurrentActiveUser,
getUserContext,
ACCESS_TOKEN_EXPIRE_MINUTES
)
import modules.gatewayModel as gatewayModel
from modules.gatewayInterface import getGatewayInterface
router = APIRouter()
# Static folder for favicon
baseDir = pathlib.Path(__file__).parent.parent
staticFolder = baseDir / "static"
@router.get("/favicon.ico")
async def favicon():
return FileResponse(str(staticFolder / "favicon.ico"), media_type="image/x-icon")
@router.get("/", tags=["General"])
async def root():
"""API status endpoint"""
return {"status": "online", "message": "Data Platform API is active"}
@router.get("/api/test", tags=["General"])
async def getTest():
return f"Status: OK. Alowed origins: {APP_CONFIG.get('APP_ALLOWED_ORIGINS')}"
@router.options("/{fullPath:path}", tags=["General"])
async def optionsRoute(fullPath: str):
return Response(status_code=200)
@router.get("/api/environment", tags=["General"])
async def get_environment():
"""Get environment configuration for frontend"""
return {
"apiBaseUrl": APP_CONFIG.get("APP_API_URL", ""),
"environment": APP_CONFIG.get("APP_ENV", "development"),
"instanceLabel": APP_CONFIG.get("APP_ENV_LABEL", "Development"),
# Add other environment variables the frontend might need
}
@router.post("/api/token", response_model=gatewayModel.Token, tags=["General"])
async def loginForAccessToken(formData: OAuth2PasswordRequestForm = Depends()):
# Initialize Gateway interface without context
gateway = getGatewayInterface()
# Authenticate user
user = gateway.authenticateUser(formData.username, formData.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid username or password",
headers={"WWW-Authenticate": "Bearer"},
)
# Create token with tenant ID
accessTokenExpires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
accessToken = createAccessToken(
data={
"sub": user["username"],
"mandateId": user["mandateId"]
},
expiresDelta=accessTokenExpires
)
return {"accessToken": accessToken, "tokenType": "bearer"}
@router.get("/api/user/me", response_model=Dict[str, Any], tags=["General"])
async def readUserMe(currentUser: Dict[str, Any] = Depends(getCurrentActiveUser)):
return currentUser