2015-12-17 19 views
5

Tôi đang sử dụng django-rest-jwt để xác thực trong ứng dụng của mình.Django Rest JWT đăng nhập bằng tên người dùng hoặc email?

Theo mặc định, trường tên người dùng người dùng để xác thực người dùng nhưng tôi muốn cho phép người dùng đăng nhập bằng cách sử dụng email hoặc tên người dùng.

Có phương tiện nào được hỗ trợ bởi django-rest-jwt để thực hiện việc này hay không. Tôi biết tùy chọn cuối cùng sẽ viết phương thức đăng nhập của riêng tôi.

Trả lời

0

Tìm ra giải pháp thay thế.

@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) 

Tôi kiểm tra xem văn bản tôi nhận được có phải là tên người dùng hay email không.

Nếu email sau đó tôi tra cứu tên người dùng cho điều đó và sau đó chỉ cần vượt qua đó để /signin_jwt/

6

Không cần phải viết một xác thực tùy chỉnh phụ trợ hoặc tùy chỉnh phương pháp đăng nhập.

Trình chỉnh sửa tùy chỉnh kế thừa JSONWebTokenSerializer, đổi tên phương thức 'username_field' và ghi đè xác thực().

Điều này hoạt động hoàn hảo cho trường 'username_or_email' và 'mật khẩu' nơi người dùng có thể nhập tên người dùng hoặc email của mình và nhận JSONWebToken cho thông tin đăng nhập chính xác.

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) 

Trong urls.py:

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

độc đáo làm @ Shikhar-thapliyal –

+0

@OhadtheLad nhờ :) –

Các vấn đề liên quan