Added DB connection and started creating api calls for the pages

This commit is contained in:
gulimabr
2025-11-30 15:17:23 -03:00
parent b5381ae376
commit bbbe65067b
20 changed files with 1403 additions and 152 deletions

View File

@@ -1,17 +1,60 @@
from contextlib import asynccontextmanager
from typing import List
from fastapi import FastAPI, Depends, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import RedirectResponse
from src.models import TokenResponse, UserInfo
from sqlalchemy.ext.asyncio import AsyncSession
from src.models import TokenResponse, UserInfo, GroupResponse
from src.controller import AuthController
from src.config import get_openid, get_settings
from src.database import init_db, close_db, get_db
from src.repositories import RoleRepository, GroupRepository
import logging
# Initialize the FastAPI app
app = FastAPI(title="Keycloak Auth API", version="1.0.0")
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Get settings
settings = get_settings()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Application lifespan manager.
Handles startup and shutdown events.
"""
# Startup
logger.info("Starting up application...")
logger.info("Initializing database...")
await init_db()
logger.info("Database initialized successfully")
# Ensure default roles exist
from src.database import AsyncSessionLocal
async with AsyncSessionLocal() as session:
role_repo = RoleRepository(session)
await role_repo.ensure_default_roles_exist()
await session.commit()
logger.info("Default roles ensured")
yield
# Shutdown
logger.info("Shutting down application...")
await close_db()
logger.info("Database connection closed")
# Initialize the FastAPI app
app = FastAPI(
title="Keycloak Auth API",
version="1.0.0",
lifespan=lifespan
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
@@ -65,15 +108,15 @@ async def login(request: Request):
# Define the callback endpoint
@app.get("/api/callback", include_in_schema=False)
async def callback(request: Request):
async def callback(request: Request, db: AsyncSession = Depends(get_db)):
"""
OAuth callback endpoint that exchanges the authorization code for a token
and sets it as an HTTP-only cookie.
OAuth callback endpoint that exchanges the authorization code for a token,
provisions the user in the database if needed, and sets it as an HTTP-only cookie.
"""
# Extract the code from the URL
keycode = request.query_params.get('code')
return AuthController.login(str(keycode), request)
return await AuthController.login(str(keycode), request, db)
# Define the auth/me endpoint to get current user from cookie
@@ -116,3 +159,20 @@ async def protected_endpoint(
UserInfo: Information about the authenticated user.
"""
return AuthController.protected_endpoint(credentials)
# ===========================================
# Groups Endpoints
# ===========================================
@app.get("/api/groups", response_model=List[GroupResponse])
async def get_groups(db: AsyncSession = Depends(get_db)):
"""
Get all groups.
Returns:
List of all groups with their names and colors.
"""
group_repo = GroupRepository(db)
groups = await group_repo.get_all()
return [GroupResponse.model_validate(g) for g in groups]