Home > Net >  add more model info to the JWT token
add more model info to the JWT token

Time:08-14

I'm creating a messaging app. I have 3 models in my backend Django. I have a profile model that stores user & which room they are connected with(so that every time they log in, their rooms will pop up in side bar like WhatsApp). in profile model I have a many to many relationship with Room model that stores rooms list. As I'm using JWT web token for authentication, I want users profile model/rooms like of that user to be added in the token. so that I can fetch the info from token directly but I don't know how to add that fields info into the token views. I've already customized my token obtain view where I added users name as extra but I need to add the list of rooms too.

Thanks in advance for helping.

#model.py
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.contrib.auth.models import User
# Create your models here.


class Room(models.Model):
    name = models.CharField(max_length=100,blank=True,null=True)


class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    rooms = models.ManyToManyField(Room)

 

class Message(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,blank=False,null=True)
    message = models.TextField(max_length=500,blank=False,null=True)
    name = models.CharField(max_length=100,blank=True,null=True)
    room = models.ForeignKey(Room,on_delete=models.CASCADE,null=True)
    time = models.DateTimeField(auto_now_add=True)
    received = models.BooleanField(default=False,null=True)

#views.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        token['name'] = user.username
        **here i want to have a token['room'] that will return me the list of rooms**
  

        return token

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

CodePudding user response:

At first get the Profile: without reverse relation it can be retrieved via

profile = Profile.objects.get(user=user) 

Then get the rooms:

rooms = profile.rooms.all()

At the end you should consider what information about the rooms you are storing into the token. The name can be blank and does not need to be unique. So it is better to store the id:

token['rooms'] = [r.id for r in rooms]

CodePudding user response:

well, i found out by myself. it's very easy. just get all the profile data of that user. now iterate through the list of the rooms using rooms.all()

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['name'] = user.username
        room = Profile.objects.get(user=user)
        token['rooms'] = [[r.name,r.id] for r in room.rooms.all()]
        print([r for r in room.rooms.all()])
        # ...

        return token
  • Related