diff --git a/openlibrary/accounts/__init__.py b/openlibrary/accounts/__init__.py index 2b3fa68cacb..6787fa8c596 100644 --- a/openlibrary/accounts/__init__.py +++ b/openlibrary/accounts/__init__.py @@ -2,6 +2,8 @@ import web +from openlibrary.utils.request_context import site + # FIXME: several modules import things from accounts.model # directly through openlibrary.accounts from .model import * # noqa: F403 @@ -54,7 +56,7 @@ def get_current_user() -> "User | None": """ Returns the currently logged in user. None if not logged in. """ - return web.ctx.site.get_user() + return site.get().get_user() def find( diff --git a/openlibrary/utils/request_context.py b/openlibrary/utils/request_context.py index 62d7fb95699..d9a3dad1e00 100644 --- a/openlibrary/utils/request_context.py +++ b/openlibrary/utils/request_context.py @@ -7,10 +7,12 @@ from contextvars import ContextVar from dataclasses import dataclass +from urllib.parse import unquote import web from fastapi import Request +from infogami import config from infogami.infobase.client import Site from infogami.utils.delegate import create_site @@ -36,6 +38,21 @@ class RequestContextVars: site: ContextVar[Site] = ContextVar("site") +def setup_site(request: Request | None = None): + """ + When called from web.py, web.ctx._parsed_cookies is already set. + When called from FastAPI, we need to set it. + create_site() automatically uses the cookie to set the auth token + """ + if request: + cookie_name = config.get("login_cookie_name", "session") + cookie_value = request.cookies.get(cookie_name) + cookie_value = unquote(cookie_value) if cookie_value else "" + web.ctx._parsed_cookies = {cookie_name: cookie_value} + + site.set(create_site()) + + def _compute_is_bot(user_agent: str | None, hhcl: str | None) -> bool: """Determine if the request is from a bot. @@ -152,7 +169,7 @@ def set_context_from_legacy_web_py() -> None: hhcl=web.ctx.env.get("HTTP_X_HHCL"), ) - site.set(create_site()) + setup_site() req_context.set( RequestContextVars( x_forwarded_for=web.ctx.env.get("HTTP_X_FORWARDED_FOR"), @@ -180,7 +197,7 @@ def set_context_from_fastapi(request: Request) -> None: hhcl=request.headers.get("X-HHCL"), ) - site.set(create_site()) + setup_site(request) req_context.set( RequestContextVars( x_forwarded_for=request.headers.get("X-Forwarded-For"),