<commit_before>import jwt

from calendar import timegm
from datetime import datetime, timedelta

from django.contrib.auth import authenticate
from django.utils.translation import ugettext as _
from rest_framework_3 import serializers
from .compat import Serializer

from rest_framework_jwt_courb.settings import api_settings
from rest_framework_jwt_courb.compat import (
    get_user_model, get_username_field, PasswordField
)


User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER


class JSONWebTokenSerializer(Serializer):
    """
    Serializer class used to validate a username and password.

    'username' is identified by the custom UserModel.USERNAME_FIELD.

    Returns a JSON Web Token that can be used to authenticate later calls.
    """
    def __init__(self, *args, **kwargs):
        """
        Dynamically add the USERNAME_FIELD to self.fields.
        """
        super(JSONWebTokenSerializer, self).__init__(*args, **kwargs)

        self.fields[self.username_field] = serializers.CharField()
        self.fields['password'] = PasswordField(write_only=True)

    @property
    def username_field(self):
        return get_username_field()

    def validate(self, attrs):
        """
        Updating validation to retrieve username
        via email
        """
        email = attrs.get(self.username_field)

        # get user (this is a little inefficient as User DB is being called twice)
        user = User.objects.filter(email=email).first()

        credentials = {
            self.username_field: user.username,
            'password': attrs.get('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 login with provided credentials.')<commit_msg>error handle if user does not exist<commit_after>import jwt

from calendar import timegm
from datetime import datetime, timedelta

from django.contrib.auth import authenticate
from django.utils.translation import ugettext as _
from rest_framework_3 import serializers
from .compat import Serializer

from rest_framework_jwt_courb.settings import api_settings
from rest_framework_jwt_courb.compat import (
    get_user_model, get_username_field, PasswordField
)


User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER


class JSONWebTokenSerializer(Serializer):
    """
    Serializer class used to validate a username and password.

    'username' is identified by the custom UserModel.USERNAME_FIELD.

    Returns a JSON Web Token that can be used to authenticate later calls.
    """
    def __init__(self, *args, **kwargs):
        """
        Dynamically add the USERNAME_FIELD to self.fields.
        """
        super(JSONWebTokenSerializer, self).__init__(*args, **kwargs)

        self.fields[self.username_field] = serializers.CharField()
        self.fields['password'] = PasswordField(write_only=True)

    @property
    def username_field(self):
        return get_username_field()

    def validate(self, attrs):
        """
        Updating validation to retrieve username
        via email
        """
        email = attrs.get(self.username_field)

        # get user (this is a little inefficient as User DB is being called twice)
        user = User.objects.filter(email=email).first()
        if not user:
            msg = _('Unable to login with provided credentials.')
            raise serializers.ValidationError(msg)

        credentials = {
            self.username_field: user.username,
            'password': attrs.get('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 login with provided credentials.')
{'fraction_non_alphanumeric': 0.07424118129614438, 'fraction_numerical': 0.00041017227235438887, 'mean_word_length': 2.6504491017964074, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6705694', 'n_tokens_mistral': 1358, 'n_tokens_neox': 1300, 'n_words': 347}