Saqib Ali
Saqib Ali

Reputation: 12535

How to make a Django view ONLY accessible to Unauthenticated users?

I'm building a Django API view by extending the rest_framework.views.APIView class.

I have successfully built many APIs that are only callable by an authenticated user. I have done this by adding: permission_classes = [permissions.IsAuthenticated,]

There are some APIs that I only want unauthenticated users to call. Such as "ForgotPassword". Basically, I want to ensure that the API caller doesn't send in the JWT Token in the request header. How can I enforce that? There is no permissions.IsUnAuthenticated.

Upvotes: 2

Views: 2121

Answers (4)

Muhammad Zubair
Muhammad Zubair

Reputation: 574

The following answer is for Django not Django REST Framework

For a Class-Based View, make a custom mixin like this

class IsNotAuthenticatedMixin(UserPassesTestMixin):
    """
    Allows access only to non authenticated users.
    """

    def test_func(self):
        return not self.request.user.is_authenticated

    def handle_no_permission(self):
        return redirect('home')

You can inherit any Class based view from IsNotAuthenticatedMixin

Upvotes: 0

KHD
KHD

Reputation: 21

Or you can do it in permissions.py like this (For who were getting bool object error)

from rest_framework import permissions

class IsNotAuthenticated(permissions.BasePermission):
    def has_permission(self, request, view):
        return not request.user.is_authenticated

And in the main view

 from .permissions import IsNotAuthenticated
 
 permission_classes = [IsNotAuthenticated]

Upvotes: 0

Muema
Muema

Reputation: 302

In case you are using function based view then it would be good if you use the following.

from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: not u.is_authenticated())

Upvotes: 0

pahko
pahko

Reputation: 2630

you can easily create your own IsNotAuthenticated class

something like this:

from rest_framework.permissions import BasePermission


class IsNotAuthenticated(BasePermission):
    """
    Allows access only to non authenticated users.
    """
    def has_permission(self, request, view):
        return not request.user.is_authenticated()

then: permission_classes = (myapp.permissions.IsNotAuthenticated,)

regards.

Upvotes: 8

Related Questions