不为用户返回令牌

时间:2019-01-23 11:14:22

标签: django django-rest-framework django-rest-framework-jwt

我正在使用djangorestframework-jwt为我的项目创建用户身份验证 当我尝试使用超级用户的电子邮件和密码登录时,我已经创建了一个超级用户,我将拥有一个令牌,但是当我尝试注册一个新用户时,它会被注册,但是如果我登录它,它会显示

{
    "non_field_errors": [
        "Unable to log in with provided credentials."
    ]
}

即使我输入正确的凭据

首先,我创建了一个有效的用户注册

models.py

   class UserManager(BaseUserManager):

def _create_user(self, email, password, **extra_fields):
    if not email:
        raise ValueError('The given email must be set')
    try:
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    except:
        raise

def create_user(self, email, password=None, **extra_fields):
    extra_fields.setdefault('is_staff', False)
    extra_fields.setdefault('is_superuser', False)
    return self._create_user(email, password, **extra_fields)

def create_superuser(self, email, password, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)

    return self._create_user(email, password=password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=40, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']

def save(self, *args, **kwargs):
    super(User, self).save(*args, **kwargs)
    return self

views.py

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class CreateUserAPIView(APIView):
permission_classes = (AllowAny,)

def post(self, request):
    user = request.data
    serializer = UserSerializer(data=user)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data, status=status.HTTP_201_CREATED)


@api_view(['POST'])
@permission_classes([AllowAny, ])
def authenticate_user(request):
try:
    email = request.data['email']
    password = request.data['password']

    user = User.objects.get(email=email, password=password)
    if user:
        try:
            payload = jwt_payload_handler(user)
            token = jwt.encode(payload, settings.SECRET_KEY)
            user_details = {}
            user_details['name'] = f'{user.first_name}{user.last_name}'
            user_details['token'] = token
            user_logged_in.send(sender=user.__class__,
                                request=request, user=user)
            return Response(user_details, status=status.HTTP_200_OK)

        except Exception as e:
            raise e
    else:
        res = {
            'error': 'can not authenticate with the given credentials or the account has been deactivated'}
        return Response(res, status=status.HTTP_403_FORBIDDEN)
except KeyError:
    res = {'error': 'please provide a email and a password'}
    return Response(res)

有什么帮助吗?我该如何纠正?我已经在 settings.py 中设置了所有设置,但尚未设置AUTHENTICATION_BACKENDS

1 个答案:

答案 0 :(得分:0)

我曾经遇到过这个问题。我解决了它在创建用户的视图中调用方法user.set_password(password)的问题。 在负责创建用户的序列化程序内部,我使用了方法user.set_password(validated_data['password'])。 超级用户在模型中拥有此方法,您可以在class UserManager(BaseUserManager):上看到它。 但是我没有经验来判断这是否是正确的方法。