SurfSense/surfsense_backend/app/app.py
2025-03-14 18:53:14 -07:00

80 lines
2.2 KiB
Python

from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import User, create_db_and_tables, get_async_session
from app.retriver.chunks_hybrid_search import ChucksHybridSearchRetriever
from app.schemas import UserCreate, UserRead, UserUpdate
from app.users import (
SECRET,
auth_backend,
fastapi_users,
google_oauth_client,
current_active_user,
)
from app.routes import router as crud_router
@asynccontextmanager
async def lifespan(app: FastAPI):
# Not needed if you setup a migration system like Alembic
await create_db_and_tables()
yield
app = FastAPI(lifespan=lifespan)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
)
app.include_router(
fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
)
app.include_router(
fastapi_users.get_register_router(UserRead, UserCreate),
prefix="/auth",
tags=["auth"],
)
app.include_router(
fastapi_users.get_reset_password_router(),
prefix="/auth",
tags=["auth"],
)
app.include_router(
fastapi_users.get_verify_router(UserRead),
prefix="/auth",
tags=["auth"],
)
app.include_router(
fastapi_users.get_users_router(UserRead, UserUpdate),
prefix="/users",
tags=["users"],
)
app.include_router(
fastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET, is_verified_by_default=True),
prefix="/auth/google",
tags=["auth"],
)
app.include_router(crud_router, prefix="/api/v1", tags=["crud"])
@app.get("/authenticated-route")
async def authenticated_route(user: User = Depends(current_active_user), session: AsyncSession = Depends(get_async_session)):
retriever = ChucksHybridSearchRetriever(session)
results = await retriever.hybrid_search(
query_text="SurfSense",
top_k=1,
user_id=user.id,
search_space_id=1,
document_type="CRAWLED_URL"
)
return results