<commit_before>from datetime import datetime

from django.core.exceptions import ObjectDoesNotExist
from django.template import loader, RequestContext
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _


class BearerAuthHandler():
    """Handles Bearer token authentication calls.

    SPEC: http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer

    """

    _token = None
    _request = None
    _response = None
    _error = None
    _scope = None

    def __init__(self, request, scope):
        self._request = request
        self._scope = scope

        self.fetch_token()
        self.validate_token()
        self.prepare_response()

    def fetch_token(self):
        token = None

        # Authorization Request Header Field
        authorization_method = self._request.META.get('HTTP_AUTHORIZATION')
        if authorization_method is not None:
            auth_method_type, auth_method_value = authorization_method.split(' ', 1)
            if auth_method_type == 'Bearer':
                token = auth_method_value
        else:
            # Form-Encoded Body Parameter or URI Query Parameter
            token = self._request.REQUEST.get('access_token')

        if token is None:
            self._error = 'invalid_request'
        else:
            self._token = token

    def validate_token(self):

        if self._token is None:
            return False

        from oauthost.models import Token
        try:
            token = Token.objects.get(access_token=self._token)
        except ObjectDoesNotExist:
            self._error = 'invalid_token'
            return False

        # If token found is granted to all the different token type.
        if token.access_token_type != 'bearer':
            self._error = 'invalid_token'
            return False

        # Token has expired.
        if token.expires_at is not None and token.expires_at <= datetime.now():
            self._error = 'invalid_token'
            return False

        # If target scope is defined, let's verify that the token has access to it.
        if self._scope is not None:
            if not token.scopes.filter(identifier=self._scope).count():
                self._error = 'insufficient_scope'
                return False

        return True

    def prepare_response(self):
<commit_msg>Added automatic login for token owner for Bearer auth.<commit_after>from datetime import datetime

from django.contrib.auth import login
from django.core.exceptions import ObjectDoesNotExist
from django.template import loader, RequestContext
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _


class BearerAuthHandler():
    """Handles Bearer token authentication calls.

    SPEC: http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer

    """

    _token = None
    _request = None
    _response = None
    _error = None
    _scope = None

    def __init__(self, request, scope):
        self._request = request
        self._scope = scope

        self.fetch_token()
        self.validate_token()
        self.prepare_response()

    def fetch_token(self):
        token = None

        # Authorization Request Header Field
        authorization_method = self._request.META.get('HTTP_AUTHORIZATION')
        if authorization_method is not None:
            auth_method_type, auth_method_value = authorization_method.split(' ', 1)
            if auth_method_type == 'Bearer':
                token = auth_method_value
        else:
            # Form-Encoded Body Parameter or URI Query Parameter
            token = self._request.REQUEST.get('access_token')

        if token is None:
            self._error = 'invalid_request'
        else:
            self._token = token

    def validate_token(self):

        if self._token is None:
            return False

        from oauthost.models import Token
        try:
            token = Token.objects.get(access_token=self._token)
        except ObjectDoesNotExist:
            self._error = 'invalid_token'
            return False

        # If token found is granted to all the different token type.
        if token.access_token_type != 'bearer':
            self._error = 'invalid_token'
            return False

        # Token has expired.
        if token.expires_at is not None and token.expires_at <= datetime.now():
            self._error = 'invalid_token'
            return False

        # If target scope is defined, let's verify that the token has access to it.
        if self._scope is not None:
            if not token.scopes.filter(identifier=self._scope).count():
                self._error = 'insufficient_scope'
                return False

        # Token is valid and now we'll log it's owner in.

        # Manual .backend attribute is set as an alternative to `authenticate()`.
        # For now this hardcoded backend will do.
        token.user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(self._request, token.user)

        return True

    def prepare_response(self):

{'fraction_non_alphanumeric': 0.072992700729927, 'fraction_numerical': 0.000789110278161373, 'mean_word_length': 2.1947069943289224, 'pattern_counts': {'":': 0, '<': 5, '<?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': '2979528', 'n_tokens_mistral': 1361, 'n_tokens_neox': 1302, 'n_words': 401}