<commit_before># Copyright (c) 2011, SD Elements. See LICENSE.txt for details.

import datetime
import json
import time  # We monkeypatch this.

from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed
from django.core.urlresolvers import reverse
from django.forms import ValidationError
from django.http import HttpResponseForbidden, HttpRequest, HttpResponse
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone

from security.auth import min_length
from security.auth_throttling import (
    attempt_count, default_delay_function, delay_message, increment_counters,
    reset_counters,
)
from security.middleware import (
    BaseMiddleware, ContentSecurityPolicyMiddleware,
    SessionExpiryPolicyMiddleware
)
from security.models import PasswordExpiry
from security.password_expiry import never_expire_password
from security.views import require_ajax, csp_report

from django.conf import settings


def login_user(func):
    """
    A decorator that will create a valid user in the database and
    then log that user in. We expect self to be a DjangoTestCase,
    or some object with a similar interface.
    """
    def wrapper(self, *args, **kwargs):
        username_local = 'a2fcf54f63993b7'
        password_local = '<PASSWORD>'
        email_local = '<EMAIL>'
        user = User.objects.create_user(
            username=username_local,
            email=email_local,
            password=<PASSWORD>,
        )
        user.is_superuser = True
        user.save()
        PasswordExpiry.objects.create(user=user).never_expire()
        self.client.login(username=username_local, password=<PASSWORD>local)
        func(self, *args, **kwargs)
        self.client.logout()
        user.delete()
    return wrapper


class CustomLoginURLMiddleware(object):
    """Used to test the custom url support in the login required middleware."""
    def process_request(self, request):
        request.login_url = '/custom-login/'


class BaseMiddlewareTestMiddleware(BaseMiddleware):
    REQUIRED_SETTINGS = ('R1', 'R2')
    OPTIONAL_SETTINGS = ('O1', 'O2')

    def load_setting(self, setting, value):
        if not hasattr(self, 'loaded_settings'):
            self.loaded_settings = {}
        self.loaded_settings[setting] = value

    def process_response(self, request, response):
        response.loaded_settings = self.loaded_settings
        return response

    def process_exception(self, request, exception):
        return self.process_response(request, HttpResponse())


class BaseMiddlewareTests(TestCase):
    def __init__(self, *args, **kwargs):
        super(BaseMiddlewareTests, self).__init__(*args, **kwargs)
        self.MIDDLEWARE_NAME = \
            BaseMiddlewareTests.__module__ + '.BaseMiddlewareTestMiddleware'

    def test_settings_initially_loaded(self):
        expected_settings = {'R1': 1, 'R2': 2, 'O1': 3, 'O2': 4}
        with self.settings(
            MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,), **expected_settings
        ):
            response = self.client.get('/home/')
            self.assertEqual(expected_settings, response.loaded_settings)

    def test_required_settings(self):
        with self.settings(MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,)):
            self.assertRaises(ImproperlyConfigured, self.client.get, '/home/')

    def test_optional_settings(self):
        with self.settings(
            MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,), R1=True, R2=True
        ):
            response = self.client.get('/home/')
            self.assertEqual(None, response.loaded_settings['O1'])
            self.assertEqual(None, response.loaded_settings['O2'])

    def test_setting_change(self):
        with self.settings(
            MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,), R1=123, R2=True
        ):
            response = self.client.get('/home/')
            self.assertEqual(123, response.loaded_settings['R1'])

            with override_settings(R1=456):
                response = self.client.get('/home/')
                self.assertEqual(456, response.loaded_settings['R1'])

            response = self.client.get('/home/')
            self.assertEqual(123, response.loaded_settings['R1'])


class LoginRequiredMiddlewareTests(TestCase):
    def setUp(self):
        self.login_url = reverse("django.contrib.auth.views.login")

    def test_aborts_if_auth_middleware_missing(self):
        middleware_classes = settings.MIDDLEWARE_CLASSES
        auth_middleware = \
            'django.contrib.auth.middleware.AuthenticationMiddleware'
        middleware_classes = [
            m for m in middleware_classes if m != auth_middleware
        ]
        with self.settings(MIDDLEWARE_CLASSES=middleware_classes):
            self.assertRaises(ImproperlyConfigured, self.client.get, '/home/')

    def test_redirects_unauthenticated_request(self):
        response = self.client.get('/home/')
        self.assertRedirects(response, self.login_url + "?next=/home/")

    def test_redirects_unauthenticated_ajax_request(self):
        response = self.client.get(
            '/home/',
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response.status_code, 401)
        self.assertEqual(
            json.loads(response.content.decode('utf-8')),
            {"login_url": self.login_url},
        )

    def test_redirects_to_custom_login_url(self):
        middlware_classes = list(settings.MIDDLEWARE_CLASSES)
        custom_login_middleware = 'tests.tests.CustomLoginURLMiddleware'
        with self.settings(
            MIDDLEWARE_CLASSES=[custom_login_middleware] + middlware_classes,
        ):
            response = self.client.get('/home/')
            self.assertRedirects(response, '/custom-login/')
            response = self.client.get(
                '/home/',
                HTTP_X_REQUESTED_WITH='XMLHttpRequest',
            )
            self.assertEqual(response.status_code, 401)
            self.assertEqual(
                json.loads(response.content),
                {"login_url": '/custom-login/'},
            )


class RequirePasswordChangeTests(TestCase):<commit_msg>Decode bytes to string<commit_after># Copyright (c) 2011, SD Elements. See LICENSE.txt for details.

import datetime
import json
import time  # We monkeypatch this.

from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed
from django.core.urlresolvers import reverse
from django.forms import ValidationError
from django.http import HttpResponseForbidden, HttpRequest, HttpResponse
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone

from security.auth import min_length
from security.auth_throttling import (
    attempt_count, default_delay_function, delay_message, increment_counters,
    reset_counters,
)
from security.middleware import (
    BaseMiddleware, ContentSecurityPolicyMiddleware,
    SessionExpiryPolicyMiddleware
)
from security.models import PasswordExpiry
from security.password_expiry import never_expire_password
from security.views import require_ajax, csp_report

from django.conf import settings


def login_user(func):
    """
    A decorator that will create a valid user in the database and
    then log that user in. We expect self to be a DjangoTestCase,
    or some object with a similar interface.
    """
    def wrapper(self, *args, **kwargs):
        username_local = 'a2fcf54f63993b7'
        password_local = '<PASSWORD>'
        email_local = '<EMAIL>'
        user = User.objects.create_user(
            username=username_local,
            email=email_local,
            password=<PASSWORD>,
        )
        user.is_superuser = True
        user.save()
        PasswordExpiry.objects.create(user=user).never_expire()
        self.client.login(username=username_local, password=<PASSWORD>)
        func(self, *args, **kwargs)
        self.client.logout()
        user.delete()
    return wrapper


class CustomLoginURLMiddleware(object):
    """Used to test the custom url support in the login required middleware."""
    def process_request(self, request):
        request.login_url = '/custom-login/'


class BaseMiddlewareTestMiddleware(BaseMiddleware):
    REQUIRED_SETTINGS = ('R1', 'R2')
    OPTIONAL_SETTINGS = ('O1', 'O2')

    def load_setting(self, setting, value):
        if not hasattr(self, 'loaded_settings'):
            self.loaded_settings = {}
        self.loaded_settings[setting] = value

    def process_response(self, request, response):
        response.loaded_settings = self.loaded_settings
        return response

    def process_exception(self, request, exception):
        return self.process_response(request, HttpResponse())


class BaseMiddlewareTests(TestCase):
    def __init__(self, *args, **kwargs):
        super(BaseMiddlewareTests, self).__init__(*args, **kwargs)
        self.MIDDLEWARE_NAME = \
            BaseMiddlewareTests.__module__ + '.BaseMiddlewareTestMiddleware'

    def test_settings_initially_loaded(self):
        expected_settings = {'R1': 1, 'R2': 2, 'O1': 3, 'O2': 4}
        with self.settings(
            MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,), **expected_settings
        ):
            response = self.client.get('/home/')
            self.assertEqual(expected_settings, response.loaded_settings)

    def test_required_settings(self):
        with self.settings(MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,)):
            self.assertRaises(ImproperlyConfigured, self.client.get, '/home/')

    def test_optional_settings(self):
        with self.settings(
            MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,), R1=True, R2=True
        ):
            response = self.client.get('/home/')
            self.assertEqual(None, response.loaded_settings['O1'])
            self.assertEqual(None, response.loaded_settings['O2'])

    def test_setting_change(self):
        with self.settings(
            MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,), R1=123, R2=True
        ):
            response = self.client.get('/home/')
            self.assertEqual(123, response.loaded_settings['R1'])

            with override_settings(R1=456):
                response = self.client.get('/home/')
                self.assertEqual(456, response.loaded_settings['R1'])

            response = self.client.get('/home/')
            self.assertEqual(123, response.loaded_settings['R1'])


class LoginRequiredMiddlewareTests(TestCase):
    def setUp(self):
        self.login_url = reverse("django.contrib.auth.views.login")

    def test_aborts_if_auth_middleware_missing(self):
        middleware_classes = settings.MIDDLEWARE_CLASSES
        auth_middleware = \
            'django.contrib.auth.middleware.AuthenticationMiddleware'
        middleware_classes = [
            m for m in middleware_classes if m != auth_middleware
        ]
        with self.settings(MIDDLEWARE_CLASSES=middleware_classes):
            self.assertRaises(ImproperlyConfigured, self.client.get, '/home/')

    def test_redirects_unauthenticated_request(self):
        response = self.client.get('/home/')
        self.assertRedirects(response, self.login_url + "?next=/home/")

    def test_redirects_unauthenticated_ajax_request(self):
        response = self.client.get(
            '/home/',
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response.status_code, 401)
        self.assertEqual(
            json.loads(response.content.decode('utf-8')),
            {"login_url": self.login_url},
        )

    def test_redirects_to_custom_login_url(self):
        middlware_classes = list(settings.MIDDLEWARE_CLASSES)
        custom_login_middleware = 'tests.tests.CustomLoginURLMiddleware'
        with self.settings(
            MIDDLEWARE_CLASSES=[custom_login_middleware] + middlware_classes,
        ):
            response = self.client.get('/home/')
            self.assertRedirects(response, '/custom-login/')
            response = self.client.get(
                '/home/',
                HTTP_X_REQUESTED_WITH='XMLHttpRequest',
            )
            self.assertEqual(response.status_code, 401)
            self.assertEqual(
                json.loads(response.content.decode('utf-8')),
                {"login_url": '/custom-login/'},
            )


class RequirePasswordChangeTests(TestCase):
{'fraction_non_alphanumeric': 0.0996174689193497, 'fraction_numerical': 0.009164807140580171, 'mean_word_length': 2.991412213740458, 'pattern_counts': {'":': 4, '<': 11, '<?xml version=': 0, '>': 11, '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': '4296445', 'n_tokens_mistral': 3663, 'n_tokens_neox': 3534, 'n_words': 702}