2015-12-17 11 views
5

Sto usando django-rest-jwt per l'autenticazione nella mia app.Login Django Rest JWT utilizzando il nome utente o l'e-mail?

Per impostazione predefinita, il campo nome utente utente consente di autenticare un utente ma io desidero consentire agli utenti di accedere utilizzando l'email o il nome utente.

C'è qualche mezzo supportato da django-rest-jwt per realizzare questo. So che l'ultima opzione sarebbe scrivere il mio metodo di accesso.

risposta

0

Ha trovato una soluzione alternativa.

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

ho verificare che se il testo che ho ricevuto è un nome utente o di una e-mail.

Se e-mail poi ho ricerca il nome utente per questo e poi basta passare che per /signin_jwt/

6

Non c'è bisogno di scrivere un metodo di login di autenticazione personalizzato back-end o personalizzato.

Un serializzatore personalizzato che eredita JSONWebTokenSerializer, rinominando "nome_utente" e sovrascrivendo il metodo def validate().

Questo funziona perfettamente per i campi "username_or_email" e "password" in cui l'utente può immettere il nome utente o l'e-mail e ottenere il JSONWebToken per le credenziali corrette.

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) 

In urls.py:

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

ben fatto @ Shikhar-thapliyal –

+0

@OhadtheLad grazie :) –

Problemi correlati