File: utils.py

package info (click to toggle)
strawberry-graphql-django 0.62.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,968 kB
  • sloc: python: 27,530; sh: 17; makefile: 16
file content (58 lines) | stat: -rw-r--r-- 1,547 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from typing import Literal, overload

from asgiref.sync import sync_to_async
from strawberry.types import Info

from strawberry_django.utils.requests import get_request
from strawberry_django.utils.typing import UserType


@overload
def get_current_user(info: Info, *, strict: Literal[True]) -> UserType: ...


@overload
def get_current_user(info: Info, *, strict: bool = False) -> UserType: ...


def get_current_user(info: Info, *, strict: bool = False) -> UserType:
    """Get and return the current user based on various scenarios."""
    request = get_request(info)

    try:
        user = request.user
    except AttributeError:
        try:
            # queries/mutations in ASGI move the user into consumer scope
            user = request.consumer.scope["user"]  # type: ignore
        except AttributeError:
            # websockets / subscriptions move scope inside of the request
            user = request.scope.get("user")  # type: ignore

    if user is None:
        raise ValueError("No user found in the current request")

    # Access an attribute inside the user object to force loading it in async contexts.
    _ = user.is_authenticated

    return user


@overload
async def aget_current_user(
    info: Info,
    *,
    strict: Literal[True],
) -> UserType: ...


@overload
async def aget_current_user(
    info: Info,
    *,
    strict: bool = False,
) -> UserType: ...


async def aget_current_user(info: Info, *, strict: bool = False) -> UserType:
    return await sync_to_async(get_current_user)(info, strict=strict)