Views (durin.views)

Durin provides four views that handle token management for you. And two additional views to allow sessions management.

Auth Management Views


LoginView

class durin.views.LoginView(**kwargs)[source]

Bases: rest_framework.views.APIView

Durin’s Login View.

This view will return a JSON response when valid username, password and (if not overwritten) client fields are POSTed to the view using form data or JSON.

It uses the default serializer provided by Django-Rest-Framework (rest_framework.authtoken.serializers.AuthTokenSerializer) to validate the user credentials.

It is possible to customize LoginView behaviour by overriding the following helper methods:

static format_expiry_datetime(expiry: datetime.datetime) → str[source]

To format the expiry datetime object at your convenience.

get_client_obj(request)durin.models.Client[source]

To get and return the associated durin.models.Client object.

:raises rest_framework.exceptions.ValidationError

get_context()[source]

to change the context passed to the UserSerializer.

get_post_response_data(request, token_obj: durin.models.AuthToken) → dict[source]

Override this to return a fully customized payload.

get_token_obj(request, client: durin.models.Client)durin.models.AuthToken[source]

Flow used to return the durin.models.AuthToken object.

get_user_serializer_class()[source]

To change the class used for serializing the user.

renew_token(request, token: durin.models.AuthToken) → None[source]

How to renew the token instance in case settings.REFRESH_TOKEN_ON_LOGIN is set to True.

Response Data and User Serialization

When the endpoint authenticates a request, a JSON object will be returned containing the token as a string, expiry as a timestamp for when the token expires.

This is because USER_SERIALIZER setting is None by default.

If you wish to return custom data upon successful authentication like first_name, last_name, and username then the included UserSerializer class can be used inside REST_DURIN settings by adding durin.serializers.UserSerializer.

Obviously, if your app uses a custom user model that does not have these fields, a custom serializer must be used.

Client Configuration

In most cases, you would want to customize how the login view gets the client object to associate with the token. By default, it is the client attribute in POSTed request body. Here’s an example snippet of how you can override this behaviour:

### views.py:

from durin.models import Client as APIClient
from durin.views import LoginView as DurinLoginView

class LoginView(DurinLoginView):

    @staticmethod
    def get_client_obj(request):
        # get the client's name from a request header
        client_name = request.META.get("X-my-personal-header", None)
        if not client_name:
            raise ParseError("No client specified.", status.HTTP_400_BAD_REQUEST)
        return APIClient.objects.get_or_create(name=client_name)


### urls.py:

from durin import views as durin_views
from yourapp.views import LoginView

urlpatterns = [
    url(r'login/', LoginView.as_view(), name='durin_login'),
    url(r'refresh/', durin_views.RefreshView.as_view(), name='durin_refresh'),
    url(r'logout/', durin_views.LogoutView.as_view(), name='durin_logout'),
    url(r'logoutall/', durin_views.LogoutAllView.as_view(), name='durin_logoutall'),
]

RefreshView

class durin.views.RefreshView(**kwargs)[source]

Bases: rest_framework.views.APIView

Durin’s Refresh View

This view accepts only a post request with an empty body. It responds to Durin Token Authentication. On a successful request,

  1. The given token’s expiry is extended by it’s associated durin.models.Client.token_ttl duration and a JSON object will be returned containing a single expiry key as the new timestamp for when the token expires.

  2. durin.signals.token_renewed() is called.

static format_expiry_datetime(expiry: datetime.datetime) → str[source]

To format the expiry datetime object at your convenience.

renew_token(request, token: durin.models.AuthToken) → datetime.datetime[source]

How to renew the token instance.


LogoutView

class durin.views.LogoutView(**kwargs)[source]

Bases: rest_framework.views.APIView

Durin’s Logout View.

This view accepts only a post request with an empty body. It responds to Durin Token Authentication. On a successful request,

  1. The token used to authenticate is deleted from the database and can no longer be used to authenticate.

  2. django.contrib.auth.signals.user_logged_out() is called.

Returns

204 (No content)


LogoutAllView

class durin.views.LogoutAllView(**kwargs)[source]

Bases: rest_framework.views.APIView

Durin’s LogoutAllView.

This view accepts only a post request with an empty body. It responds to Durin Token Authentication. On a successful request,

  1. The token used to authenticate, and all other tokens registered to the same User account, are deleted from the system and can no longer be used to authenticate.

  2. django.contrib.auth.signals.user_logged_out() is called.

Returns

204 (No content)

Note

It is not recommended to alter the Logout views. They are designed specifically for token management, and to respond to durin authentication. Modified forms of the class may cause unpredictable results.

Session Management Views


TokenSessionsViewSet

class durin.views.TokenSessionsViewSet(**kwargs)[source]

Bases: rest_framework.mixins.ListModelMixin, rest_framework.mixins.DestroyModelMixin, rest_framework.viewsets.GenericViewSet

Durin’s TokenSessionsViewSet.

  • Returns list of active sessions of authed user.

  • Only list() and delete() operations.

New in version 1.0.0.


APIAccessTokenView

class durin.views.APIAccessTokenView(**kwargs)[source]

Bases: rest_framework.views.APIView

Durin’s APIAccessTokenView.

  • GET -> get token-client pair info

  • POST -> create and get token-client pair info

  • DELETE -> delete existing API access token

New in version 1.0.0.