Skip to content

Authentication🔗

In this section, we'll cover how to log users in and out with GraphQL mutations using Django's session authentication. Undine doesn't include ready-made authentication entrypoints. Instead, you can use Django's authentication functions in function entrypoints directly.

The examples on this page assume that SessionMiddleware and AuthenticationMiddleware are in your MIDDLEWARE setting.

Current user🔗

The request is available from the GQLInfo object as info.context.request, and the current user as info.context.request.user. An entrypoint that returns the current user, or null for anonymous users, can be written like this:

from django.contrib.auth.models import User

from undine import Entrypoint, Field, GQLInfo, QueryType, RootType


class UserType(QueryType[User], auto=False):
    username = Field()
    email = Field()


class Query(RootType):
    @Entrypoint
    def me(self, info: GQLInfo) -> UserType | None:
        user = info.context.request.user
        if not user.is_authenticated:
            return None
        return user
1
2
3
4
5
6
7
8
type UserType {
  email: Email!
  username: String!
}

type Query {
  me: UserType
}

Logging in🔗

To log a user in, call authenticate() to check the credentials, and then login() to store the user in the session.

from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User

from undine import Entrypoint, Field, GQLInfo, QueryType, RootType
from undine.exceptions import GraphQLValidationError


class UserType(QueryType[User], auto=False):
    username = Field()
    email = Field()


class Mutation(RootType):
    @Entrypoint
    def login(self, info: GQLInfo, username: str, password: str) -> UserType:
        request = info.context.request
        user = authenticate(request, username=username, password=password)
        if user is None:
            msg = "Invalid username or password."
            raise GraphQLValidationError(msg)

        login(request, user)
        return user
1
2
3
type Mutation {
  login(username: String!, password: String!): UserType!
}

Note that the request is info.context.request, not info.context.

After a successful login, the response sets the session cookie, so the following requests from the client are made as the logged-in user.

Django rotates the CSRF token when a user logs in. If you use CSRF protection, the client must read the new token from the csrftoken cookie before making the next mutation.

Logging out🔗

To log a user out, call logout(). This removes the user from the session.

from django.contrib.auth import logout

from undine import Entrypoint, GQLInfo, RootType


class Mutation(RootType):
    @Entrypoint
    def logout(self, info: GQLInfo) -> bool:
        logout(info.context.request)
        return True
1
2
3
type Mutation {
  logout: Boolean!
}

Async🔗

When using Undine in async mode, use the async versions of the functions: aauthenticate(), alogin() and alogout(). Read the current user with await request.auser().

from django.contrib.auth import aauthenticate, alogin, alogout
from django.contrib.auth.models import User

from undine import Entrypoint, Field, GQLInfo, QueryType, RootType
from undine.exceptions import GraphQLValidationError


class UserType(QueryType[User], auto=False):
    username = Field()
    email = Field()


class Query(RootType):
    @Entrypoint
    async def me(self, info: GQLInfo) -> UserType | None:
        user = await info.context.request.auser()
        if not user.is_authenticated:
            return None
        return user


class Mutation(RootType):
    @Entrypoint
    async def login(self, info: GQLInfo, username: str, password: str) -> UserType:
        request = info.context.request
        user = await aauthenticate(request, username=username, password=password)
        if user is None:
            msg = "Invalid username or password."
            raise GraphQLValidationError(msg)

        await alogin(request, user)
        return user

    @Entrypoint
    async def logout(self, info: GQLInfo) -> bool:
        await alogout(info.context.request)
        return True

WebSockets🔗

Logging in and out is not supported over WebSockets. A WebSocket connection is authenticated once, when the connection opens, with the session cookie that the browser sends in the handshake. After that, the server cannot set cookies on the connection, so a login during the connection could not be stored for the client.

Log in with a normal HTTP request before opening the WebSocket connection. If the user logs in or out while the connection is open, open a new connection.