<commit_before>#coding: utf-8
import re
from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseForbidden, HttpResponse
from django.conf import settings
from django.shortcuts import render_to_response
from vk_iframe.forms import VkontakteIframeForm

try:
    import vkontakte
    use_vkontakte_pkg = True
except ImportError:
    use_vkontakte_pkg = False

DEFAULT_P3P_POLICY = 'IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'
P3P_POLICY = getattr(settings, 'VK_P3P_POLICY', DEFAULT_P3P_POLICY)

class AuthenticationMiddleware(object):

    def process_request(self, request):

        # все неправильно настроено
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The vk.middleware.AuthenticationMiddleware requires the"
                " Django authentication middleware to be installed.  Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the vk.middleware.AuthenticationMiddleware class.")

        def patch_request_with_vkapi(user):
            if hasattr(request, 'session') and use_vkontakte_pkg:
                token = request.session['vk_startup_vars']['access_token']
                setattr(request,'vk_api',vkontakte.API(token = token))

        # не было попытки авторизоваться через Вконтакте
        if 'viewer_id' not in request.GET:
            patch_request_with_vkapi(request.user)
            return

        # пользователь уже залогинен под тем же именем
        if request.user.is_authenticated():
            if request.user.username == request.GET['viewer_id']:
                patch_request_with_vkapi(request.user)
                return

        # пользователь не залогинен или залогинен под другим именем
        vk_form = VkontakteIframeForm(request.GET)

        user = auth.authenticate(vk_form=vk_form)
        if user:
            request.user = user
            auth.login(request, user)

            if hasattr(request, 'session'):
                # устанавливаем язык пользователя
                lang_code = vk_form.language_code()
                if lang_code:
                    request.session['django_language'] = lang_code

                # сохраняем начальные параметры, тк там точно есть что то полезное
                startup_vars = vk_form.cleaned_data
                del startup_vars['api_result'] # этот большой кусок сохранять в сессию не будем, он уже есть в vk_profile
                request.session['vk_startup_vars'] = startup_vars

                patch_request_with_vkapi(request.user)

        else:
            request.META['VKONTAKTE_LOGIN_ERRORS'] = vk_form.errors


class IFrameFixMiddleware(object):

    def process_request(self, request):
        """
        Safari and Opera default security policies restrict cookie setting in first request in iframe.
        Solution is to create hidden form to preserve GET variables and REPOST it to current URL.

        Inspired by https://gist.github.com/796811 and https://gist.github.com/1511039.
        """
        user_agent = request.META.get('HTTP_USER_AGENT', '')<commit_msg>add check for session item, remove unneeded argument<commit_after>#coding: utf-8
import re
from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseForbidden, HttpResponse
from django.conf import settings
from django.shortcuts import render_to_response
from vk_iframe.forms import VkontakteIframeForm

try:
    import vkontakte
    use_vkontakte_pkg = True
except ImportError:
    use_vkontakte_pkg = False

DEFAULT_P3P_POLICY = 'IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'
P3P_POLICY = getattr(settings, 'VK_P3P_POLICY', DEFAULT_P3P_POLICY)

class AuthenticationMiddleware(object):

    def process_request(self, request):

        # все неправильно настроено
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The vk.middleware.AuthenticationMiddleware requires the"
                " Django authentication middleware to be installed.  Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the vk.middleware.AuthenticationMiddleware class.")

        def patch_request_with_vkapi():
            if use_vkontakte_pkg and hasattr(request, 'session'):
                if 'vk_startup_vars' in request.session:
                    token = request.session['vk_startup_vars']['access_token']
                    setattr(request,'vk_api',vkontakte.API(token = token))

        # не было попытки авторизоваться через Вконтакте
        if 'viewer_id' not in request.GET:
            patch_request_with_vkapi()
            return

        # пользователь уже залогинен под тем же именем
        if request.user.is_authenticated():
            if request.user.username == request.GET['viewer_id']:
                patch_request_with_vkapi()
                return

        # пользователь не залогинен или залогинен под другим именем
        vk_form = VkontakteIframeForm(request.GET)

        user = auth.authenticate(vk_form=vk_form)
        if user:
            request.user = user
            auth.login(request, user)

            if hasattr(request, 'session'):
                # устанавливаем язык пользователя
                lang_code = vk_form.language_code()
                if lang_code:
                    request.session['django_language'] = lang_code

                # сохраняем начальные параметры, тк там точно есть что то полезное
                startup_vars = vk_form.cleaned_data
                del startup_vars['api_result'] # этот большой кусок сохранять в сессию не будем, он уже есть в vk_profile
                request.session['vk_startup_vars'] = startup_vars

                patch_request_with_vkapi()

        else:
            request.META['VKONTAKTE_LOGIN_ERRORS'] = vk_form.errors


class IFrameFixMiddleware(object):

    def process_request(self, request):
        """
        Safari and Opera default security policies restrict cookie setting in first request in iframe.
        Solution is to create hidden form to preserve GET variables and REPOST it to current URL.

        Inspired by https://gist.github.com/796811 and https://gist.github.com/1511039.
        """
        user_agent = request.META.get('HTTP_USER_AGENT', '')
{'fraction_non_alphanumeric': 0.06805004577357339, 'fraction_numerical': 0.00549282880683552, 'mean_word_length': 2.5663764961915123, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 4, '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': '2938133', 'n_tokens_mistral': 2000, 'n_tokens_neox': 1956, 'n_words': 483}