2015-12-17 121 views
5

我正在使用django-rest-jwt在我的應用程序進行身份驗證。Django Rest JWT登錄使用用戶名或電子郵件?

默認情況下,它使用用戶名字段來驗證用戶,但我想讓用戶使用電子郵件或用戶名登錄。

django-rest-jwt是否支持完成此操作? 我知道最後一個選項會寫我自己的登錄方法。

回答

0

找到了解決方法。

@permission_classes((permissions.AllowAny,)) 
def signin_jwt_wrapped(request, *args, **kwargs): 
    request_data = request.data 
    host = request.get_host() 
    username_or_email = request_data['username'] 
    if isEmail(username_or_email): 
     # get the username for this email by model lookup 
     username = Profile.get_username_from_email(username_or_email) 
     if username is None: 
      response_text = {"non_field_errors":["Unable to login with provided credentials."]} 
      return JSONResponse(response_text, status=status.HTTP_400_BAD_REQUEST) 
    else: 
     username = username_or_email 

    data = {'username': username, 'password':request_data['password']} 
    headers = {'content-type': 'application/json'} 
    url = 'http://' + host + '/user/signin_jwt/' 
    response = requests.post(url,data=dumps(data), headers=headers) 

    return JSONResponse(loads(response.text), status=response.status_code) 

我檢查我收到的文本是用戶名還是電子郵件。

如果電子郵件然後我查找該用戶名,然後就傳遞到/signin_jwt/

6

無需編寫自定義認證後端或自定義登錄方法。

自定義序列化器繼承JSONWebTokenSerializer,重命名'username_field'並覆蓋def validate()方法。

這適用於'username_or_email'和'密碼'字段,用戶可以輸入其用戶名或電子郵件並獲取JSONWebToken以獲取正確的憑據。

class CustomJWTSerializer(JSONWebTokenSerializer): 
    username_field = 'username_or_email' 

def validate(self, attrs): 

    password = attrs.get("password") 
    user_obj = User.objects.filter(email=attrs.get("username_or_email")).first() or User.objects.filter(username=attrs.get("username_or_email")).first() 
     if user_obj is not None: 
      credentials = { 
       'username':user_obj.username, 
       'password': password 
      } 
      if all(credentials.values()): 
       user = authenticate(**credentials) 
       if user: 
        if not user.is_active: 
         msg = _('User account is disabled.') 
         raise serializers.ValidationError(msg) 

        payload = jwt_payload_handler(user) 

        return { 
         'token': jwt_encode_handler(payload), 
         'user': user 
        } 
       else: 
        msg = _('Unable to log in with provided credentials.') 
        raise serializers.ValidationError(msg) 

      else: 
       msg = _('Must include "{username_field}" and "password".') 
       msg = msg.format(username_field=self.username_field) 
       raise serializers.ValidationError(msg) 

     else: 
      msg = _('Account with this email/username does not exists') 
      raise serializers.ValidationError(msg) 

在urls.py:

url(r'{Your url name}$', ObtainJSONWebToken.as_view(serializer_class=CustomJWTSerializer)), 
+1

很好地完成@ Shikhar的,thapliyal –

+0

@OhadtheLad謝謝:) –

相關問題