Skip to content

Commit

Permalink
Remove connection to the captn wasp db
Browse files Browse the repository at this point in the history
  • Loading branch information
rjambrecic committed Jun 24, 2024
1 parent 97caf17 commit 378d062
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 72 deletions.
45 changes: 8 additions & 37 deletions google_sheets/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import urllib.parse
from os import environ
from pathlib import Path
from typing import Annotated, Any, Dict, List, Tuple, Union
from typing import Annotated, Any, Dict, List, Union

import httpx
from asyncify import asyncify
Expand All @@ -14,7 +14,7 @@
from prisma.errors import RecordNotFoundError

from . import __version__
from .db_helpers import get_db_connection, get_wasp_db_url
from .db_helpers import get_db_connection

__all__ = ["app"]

Expand Down Expand Up @@ -47,23 +47,7 @@
}


async def get_user_id_chat_uuid_from_chat_id(
chat_id: Union[int, str],
) -> Tuple[int, str]:
wasp_db_url = get_wasp_db_url()
async with get_db_connection(db_url=wasp_db_url) as db:
chat = await db.query_first(
f'SELECT * from "Chat" where id={chat_id}' # nosec: [B608]
)
if not chat:
raise HTTPException(status_code=404, detail=f"chat {chat} not found")
user_id = chat["userId"]
chat_uuid = chat["uuid"]
return user_id, chat_uuid


async def is_authenticated_for_ads(user_id: int) -> bool:
await get_user(user_id=user_id)
async with get_db_connection() as db:
data = await db.gauth.find_unique(where={"user_id": user_id})

Expand All @@ -77,7 +61,6 @@ async def is_authenticated_for_ads(user_id: int) -> bool:
async def get_login_url(
request: Request,
user_id: int = Query(title="User ID"),
conv_id: int = Query(title="Conversation ID"),
force_new_login: bool = Query(title="Force new login", default=False),
) -> Dict[str, str]:
if not force_new_login:
Expand All @@ -89,7 +72,7 @@ async def get_login_url(
f"{oauth2_settings['auth_uri']}?client_id={oauth2_settings['clientId']}"
f"&redirect_uri={oauth2_settings['redirectUri']}&response_type=code"
f"&scope={urllib.parse.quote_plus('email https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive.metadata.readonly')}"
f"&access_type=offline&prompt=consent&state={conv_id}"
f"&access_type=offline&prompt=consent&state={user_id}"
)
markdown_url = f"To navigate Google Ads waters, I require access to your account. Please [click here]({google_oauth_url}) to grant permission."
return {"login_url": markdown_url}
Expand All @@ -105,9 +88,9 @@ async def get_login_success() -> Dict[str, str]:
async def login_callback(
code: str = Query(title="Authorization Code"), state: str = Query(title="State")
) -> RedirectResponse:
chat_id = state
user_id, chat_uuid = await get_user_id_chat_uuid_from_chat_id(chat_id)
user = await get_user(user_id=user_id)
if not state.isdigit():
raise HTTPException(status_code=400, detail="User ID must be an integer")
user_id = int(state)

token_request_data = {
"code": code,
Expand Down Expand Up @@ -135,10 +118,10 @@ async def login_callback(
user_info = userinfo_response.json()
async with get_db_connection() as db:
await db.gauth.upsert(
where={"user_id": user["id"]},
where={"user_id": user_id},
data={
"create": {
"user_id": user["id"],
"user_id": user_id,
"creds": json.dumps(token_data),
"info": json.dumps(user_info),
},
Expand All @@ -157,19 +140,7 @@ async def login_callback(
return RedirectResponse(url=f"{base_url}/login/success")


async def get_user(user_id: Union[int, str]) -> Any:
wasp_db_url = get_wasp_db_url()
async with get_db_connection(db_url=wasp_db_url) as db:
user = await db.query_first(
f'SELECT * from "User" where id={user_id}' # nosec: [B608]
)
if not user:
raise HTTPException(status_code=404, detail=f"user_id {user_id} not found")
return user


async def load_user_credentials(user_id: Union[int, str]) -> Any:
await get_user(user_id=user_id)
async with get_db_connection() as db:
try:
data = await db.gauth.find_unique_or_raise(where={"user_id": user_id}) # type: ignore[typeddict-item]
Expand Down
9 changes: 0 additions & 9 deletions google_sheets/db_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,3 @@ async def get_db_connection(
yield db
finally:
await db.disconnect()


def get_wasp_db_url() -> str:
curr_db_url = environ.get("DATABASE_URL")
wasp_db_name = environ.get("WASP_DB_NAME", "waspdb")
wasp_db_url = curr_db_url.replace(curr_db_url.split("/")[-1], wasp_db_name) # type: ignore[union-attr]
if "connect_timeout" not in wasp_db_url:
wasp_db_url += "?connect_timeout=60"
return wasp_db_url
9 changes: 0 additions & 9 deletions tests/app/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,6 @@ def test_openapi(self) -> None:
"required": True,
"schema": {"type": "integer", "title": "User ID"},
},
{
"name": "conv_id",
"in": "query",
"required": True,
"schema": {
"type": "integer",
"title": "Conversation ID",
},
},
{
"name": "force_new_login",
"in": "query",
Expand Down
17 changes: 0 additions & 17 deletions tests/app/test_db_helpers.py

This file was deleted.

0 comments on commit 378d062

Please sign in to comment.