Home > Enterprise >  Django Rest Framework/Djoser sending role information to frontend (Vue)
Django Rest Framework/Djoser sending role information to frontend (Vue)

Time:08-04

I am working on a simple site with a login functionality. To handle auth in the backend I am using the Djoser library. I have login functionality working. However now I want to create a site on my frontend which has restricted access based on a users roles.

What I want is that if a users is admin/staff then the frontend site has another page in the navbar. So my question is, how should I go about handling this. My first thought is that, when the user is logging in, then the token is sent to the frontend and stored, and then with the token I would also send the users role and store this aswell. However I am not sure how to extend Djoser to do this.

Another option would be to simply say that after the user has logged in and received the token and stored it in the frontend, I would make a subsequent request to the backend to get that users information including its role and store that aswell. This of course takes 2 backend calls instead of one as in the first option.

To me it seems optimal to use the first option, however I am not sure how to extend the Djoser login path to send both a token and the users role.

Solved it myself, see my answer below to see how I did it.

However if anybody is familiar with a smarter way to achieve what I am trying to, then please post a comment!

CodePudding user response:

Okay, I figured it out myself. Leaving this here if anybody needs it.

First I create a serializer file in my project directory (original app). Then I took the TokenSerializer from Djoser and extended it to the following,

from rest_framework import serializers
from djoser.conf import settings

class TokenSerializer(serializers.ModelSerializer):
    auth_token = serializers.CharField(source="key")
    is_staff = serializers.BooleanField(source="user.is_staff", read_only=True, default=False)

    class Meta:
        model = settings.TOKEN_MODEL
        fields = ("auth_token", "is_staff")

I did not realize that you can use the source keyword, with this I can access the user model attached to the token, and the retrieve the is_staff field.

This now makes it so that a user requests a login to /auth/token/login/, with the login details, it responds with a token and whether or not the user has is_staff field set.

  • Related