user9714967
user9714967

Reputation: 1972

How to check if the current user is logged in django rest framework? how to notify other django app that the current user is logged?

I use ListCreateAPIView for POST and GET requests. I want to check if current user is logged in GET request. How to get current user (if he logged) in GET methods ? To make it work, i have to send with token , t's not what I want because if user is logout, user can not access listView. I thought django signals,or to rewrite authorization.

I thought django signals, or to rewrite Permissions or Authorization.

class PropertyList(generics.ListCreateAPIView):
    """To create a property"""
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, ]
    queryset = Property.objects.filter(published=True)
    serializer_class = PropertySerializer
    filterset_class = PropertyFilter
    pagination_class = LimitOffsetPagination

    #
    # def perform_create(self, serializer):
    #     serializer.save(created_by=self.request.user)

    # for _ in range(100):
    #      logger.info("Your log message is here")

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['is_create'] = True
        print(self.request.user)

        if self.request.user.is_authenticated:
            print(self.request.user)
            current_user = self.request.user
            context['user_favs'] =  (Bookmark.objects.filter(
                bookUser = current_user
            ).values(
                ))
        else:
            context['user_favs'] = False

        return context

In get_serializer_context(self) , i want to get current user because i return properties that user has bookmarked. I need to add token in my Get request to have current user but that's mean , we have to login to see properties , it's not what I want

settings

REST_FRAMEWORK = {
    "DATE_INPUT_FORMATS": ["%d-%m-%Y"],
    # 'DATETIME_FORMAT': "%d-%m-%Y %H:%M:%S",
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        # 'rest_framework_simplejwt.authentication.JWTAuthentication',

    ),
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
    'EXCEPTION_HANDLER': 'dooba.utils.custom_exception_handler',
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
    # 'DEFAULT_PARSER_CLASSES': (
    #     'rest_framework.parsers.JSONParser',
    #     'rest_framework.parsers.FormParser',
    #     'rest_framework.parsers.MultiPartParser',
    # )

}

As you can see enter image description here

enter image description here

Upvotes: 3

Views: 6292

Answers (1)

cagrias
cagrias

Reputation: 1847

You can access user object in your APIView methods by self.request.user if there is no logged-in user, it should be AnonymousUser or else you should get the logged in user.

EDIT: Further research revealed that when you use JSONWebTokenAuthentication with IsAuthenticatedOrReadOnly returns 401 with expired tokens even if you make GET request. I recommend you to never put Authenticate header when making a GET request to your PropertyList view, that will solve your problem.

Upvotes: 1

Related Questions