Skip to content

The platform for continuously improving AI agents.

1.4 KB
Raw Blame
from __future__ import annotations

from overbae.models import APIToken, ProjectMembership


def project_ids_for(user, auth=None):
    """The project ids this request may read.

    A project-scoped API key is pinned to ``resourceIds`` and must not reach
    the caller's other memberships. An account-scoped key follows memberships
    the same way a session does. ``auth`` is a plain dict under Clerk, hence
    the isinstance guard.
    """
    if isinstance(auth, APIToken):
        return auth.allowed_project_ids()
    return ProjectMembership.objects.filter(user=user).values_list("project_id", flat=True)


PROJECT_HEADER = "X-Overmind-Project"
PROJECT_REQUIRED = (
    "Name the project to charge: use a project API key or send the X-Overmind-Project header."
)


def charged_project(request) -> str | None:
    """The project a gateway call is charged to: the key's one project, the one the caller
    names in ``X-Overmind-Project``, or the caller's only project."""
    allowed = [str(pk) for pk in project_ids_for(request.user, request.auth)]
    named = request.headers.get(PROJECT_HEADER)
    if named:
        return named if named in allowed else None
    return allowed[0] if len(allowed) == 1 else None


def request_cause_id(request) -> tuple[str, str]:
    """What started a gateway call: the API key, or the signed-in user."""
    if isinstance(request.auth, APIToken):
        return "api_key", str(request.auth.pk)
    return "user", str(request.user.pk)