Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion openlibrary/accounts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
21 changes: 19 additions & 2 deletions openlibrary/utils/request_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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"),
Expand Down