<commit_before>from __future__ import unicode_literals

import base64
import logging
from datetime import timedelta

from django.utils import timezone
from django.contrib.auth import authenticate
from django.core.exceptions import ObjectDoesNotExist
from oauthlib.oauth2 import RequestValidator

from .compat import unquote_plus
from .models import Grant, AccessToken, RefreshToken, get_application_model
from .settings import oauth2_settings

Application = get_application_model()

log = logging.getLogger('oauth2_provider')

GRANT_TYPE_MAPPING = {
    'authorization_code': (Application.GRANT_AUTHORIZATION_CODE,),
    'password': (Application.GRANT_PASSWORD,),
    'client_credentials': (Application.GRANT_CLIENT_CREDENTIALS,),
    'refresh_token': (Application.GRANT_AUTHORIZATION_CODE, Application.GRANT_PASSWORD,
                      Application.GRANT_CLIENT_CREDENTIALS)
}


class OAuth2Validator(RequestValidator):
    def _extract_basic_auth(self, request):
        """
        Return authentication string if request contains basic auth credentials, else return None
        """
        auth = request.headers.get('HTTP_AUTHORIZATION', None)
        if not auth:
            return None

        auth_type, auth_string = auth.split(' ', 1)
        if auth_type != "Basic":
            return None

        return auth_string

    def _authenticate_basic_auth(self, request):
        """
        Authenticates with HTTP Basic Auth.

        Note: as stated in rfc:`2.3.1`, client_id and client_secret must be encoded with
        "application/x-www-form-urlencoded" encoding algorithm.
        """
        auth_string = self._extract_basic_auth(request)
        if not auth_string:
            return False

        encoding = request.encoding or 'utf-8'

        try:
            b64_decoded = base64.b64decode(auth_string)
        except TypeError:
            log.debug("Failed basic auth: %s can't be decoded as base64", auth_string)
            return False

        try:
            auth_string_decoded = b64_decoded.decode(encoding)
        except UnicodeDecodeError:
            log.debug("Failed basic auth: %s can't be decoded as unicode by %s",
                      auth_string,
                      encoding)
            return False

        client_id, client_secret = map(unquote_plus, auth_string_decoded.split(':', 1))

        if self._load_application(client_id, request) is None:<commit_msg>Fixed py3 compat problem:<commit_after>from __future__ import unicode_literals

import base64
import binascii
import logging
from datetime import timedelta

from django.utils import timezone
from django.contrib.auth import authenticate
from django.core.exceptions import ObjectDoesNotExist
from oauthlib.oauth2 import RequestValidator

from .compat import unquote_plus
from .models import Grant, AccessToken, RefreshToken, get_application_model
from .settings import oauth2_settings

Application = get_application_model()

log = logging.getLogger('oauth2_provider')

GRANT_TYPE_MAPPING = {
    'authorization_code': (Application.GRANT_AUTHORIZATION_CODE,),
    'password': (Application.GRANT_PASSWORD,),
    'client_credentials': (Application.GRANT_CLIENT_CREDENTIALS,),
    'refresh_token': (Application.GRANT_AUTHORIZATION_CODE, Application.GRANT_PASSWORD,
                      Application.GRANT_CLIENT_CREDENTIALS)
}


class OAuth2Validator(RequestValidator):
    def _extract_basic_auth(self, request):
        """
        Return authentication string if request contains basic auth credentials, else return None
        """
        auth = request.headers.get('HTTP_AUTHORIZATION', None)
        if not auth:
            return None

        auth_type, auth_string = auth.split(' ', 1)
        if auth_type != "Basic":
            return None

        return auth_string

    def _authenticate_basic_auth(self, request):
        """
        Authenticates with HTTP Basic Auth.

        Note: as stated in rfc:`2.3.1`, client_id and client_secret must be encoded with
        "application/x-www-form-urlencoded" encoding algorithm.
        """
        auth_string = self._extract_basic_auth(request)
        if not auth_string:
            return False

        encoding = request.encoding or 'utf-8'

        try:
            b64_decoded = base64.b64decode(auth_string)
        except (TypeError, binascii.Error):
            log.debug("Failed basic auth: %s can't be decoded as base64", auth_string)
            return False

        try:
            auth_string_decoded = b64_decoded.decode(encoding)
        except UnicodeDecodeError:
            log.debug("Failed basic auth: %s can't be decoded as unicode by %s",
                      auth_string,
                      encoding)
            return False

        client_id, client_secret = map(unquote_plus, auth_string_decoded.split(':', 1))

        if self._load_application(client_id, request) is None:
{'fraction_non_alphanumeric': 0.07505112474437628, 'fraction_numerical': 0.009202453987730062, 'mean_word_length': 2.9253611556982344, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '3935823', 'n_tokens_mistral': 1402, 'n_tokens_neox': 1325, 'n_words': 355}