如何从JWT获取用户ID

时间:2017-11-06 16:56:52

标签: python django django-rest-framework

如何从JWT令牌获取用户ID。 我的JWT令牌有这样的有效载荷:

{
  "username": "Steve",
  "is_admin": false,
  "id": 1
}

如何访问user id? 我实际上想根据id更新数据库中的某些字段,这是针对特定用户的。

其次,在获取访问权限之后如何更新字段?

models.py

class Profile(models.Model):
    branch = models.CharField(max_length=20, null=True)
    year = models.IntegerField(null=True)
    image = models.ImageField(upload_to="accounts/images/", null=True, blank=True)

serializer.py

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('branch', 'year' ,'image',)

更新这些字段的视图是什么?

2 个答案:

答案 0 :(得分:1)

您应该使用与当前User对象关联的request对象。这假设cookie存在意味着用户在访问相关视图时已登录会话,

def update_profile(request):
    current_user = request.user
    profile = Profile.objects.get(user=current_user.pk)
    profile.update(field_a="value a", field_b="value b")  # etc, example only
    profile.save()

为了实现这一目标,您还需要将用户关系添加为OneToOne对象中的Profile字段:

from django.contrib.auth import User  # assuming no customisation has been done to User model

# All your other imports and code

class Profile(models.Model):
    branch = models.CharField(max_length=20, null=True)
    year = models.IntegerField(null=True)
    image = models.ImageField(upload_to="accounts/images/", null=True, blank=True)
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        primary_key=False,
    )

答案 1 :(得分:1)

<强> serializers.py

from django.contrib.auth import get_user_model
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        exclude = ()

<强> views.py

import base64
import json
from django.contrib.auth import get_user_model
from rest_framework.generics import RetrieveUpdateAPIView

class MyUserViewset(RetrieveUpdateAPIView):
    queryset = get_user_model().objects.all()
    serializer_class = MyUserSerializer
    pagination_class = None

    def get_object(self):
        request = self.request
        token = http_auth = request.META.get('HTTP_AUTHORIZATION', None)
        token = token.replace("Token ", "")
        user_json = json.loads(base64.b64decode(token.split(".")[1]))
        user_id = user_json['id']
        User = get_user_model()
        user_obj = User.objects.get(id=user_id)
        return user_obj