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

from datetime import datetime, timedelta
import time # We monkeypatch this.

from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.forms import ValidationError
from django.http import HttpResponseForbidden, HttpRequest
from django.conf.urls.defaults import *
from django.test import TestCase
from django.utils import simplejson as json

from security.auth import min_length
from security.auth_throttling import delay_message, increment_counters, attempt_count, reset_counters
from security.middleware import MandatoryPasswordChangeMiddleware
from security.middleware import SessionExpiryPolicyMiddleware
from security.models import PasswordExpiry
from security.password_expiry import never_expire_password
from security.views import require_ajax

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 = '<PASSWORD>'
        password_local = '<PASSWORD>'
        email_local = '<EMAIL>'
        user = User.objects.create_user(username=username_local,
                email=email_local, password=password_local)
        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 LoginRequiredMiddlewareTests(TestCase):
    def setUp(self):
        self.login_url = reverse("django.contrib.auth.views.login")

    def test_aborts_if_auth_middlware_missing(self):
        middlware_classes = settings.MIDDLEWARE_CLASSES
        auth_middleware = 'django.contrib.auth.middleware.AuthenticationMiddleware'
        middlware_classes = [m for m in middlware_classes if m != auth_middleware]
        with self.settings(MIDDLEWARE_CLASSES=middlware_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, 403)
        self.assertEqual(json.loads(response.content),
                         {"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, 403)
            self.assertEqual(json.loads(response.content),
                             {"login_url": '/custom-login/'})


class RequirePasswordChangeTests(TestCase):
    def test_require_password_change(self):
        """
        A brand-new user should have an already-expired password, and therefore
        be redirected to the password change form on any request.
        """
        user = User.objects.create_user(username="foo",
                                        password="<PASSWORD>",
                                        email="<EMAIL>")
        self.client.login(username="foo", password="<PASSWORD>")
        try:
            self.assertRedirects(self.client.get("/home/"),
                                 MandatoryPasswordChangeMiddleware().password_change_url)
            never_expire_password(user)
            self.assertEqual(self.client.get("/home/").status_code, 200)
        finally:
            self.client.logout()
            user.delete()<commit_msg>Update tests to match behaviour of login required middleware.<commit_after># Copyright (c) 2011, SD Elements. See LICENSE.txt for details.

from datetime import datetime, timedelta
import time # We monkeypatch this.

from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.forms import ValidationError
from django.http import HttpResponseForbidden, HttpRequest
from django.conf.urls.defaults import *
from django.test import TestCase
from django.utils import simplejson as json

from security.auth import min_length
from security.auth_throttling import delay_message, increment_counters, attempt_count, reset_counters
from security.middleware import MandatoryPasswordChangeMiddleware
from security.middleware import SessionExpiryPolicyMiddleware
from security.models import PasswordExpiry
from security.password_expiry import never_expire_password
from security.views import require_ajax

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 = 'a<PASSWORD>'
        password_local = '<PASSWORD>'
        email_local = '<EMAIL>'
        user = User.objects.create_user(username=username_local,
                email=email_local, password=password_local)
        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 LoginRequiredMiddlewareTests(TestCase):
    def setUp(self):
        self.login_url = reverse("django.contrib.auth.views.login")

    def test_aborts_if_auth_middlware_missing(self):
        middlware_classes = settings.MIDDLEWARE_CLASSES
        auth_middleware = 'django.contrib.auth.middleware.AuthenticationMiddleware'
        middlware_classes = [m for m in middlware_classes if m != auth_middleware]
        with self.settings(MIDDLEWARE_CLASSES=middlware_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),
                         {"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):
    def test_require_password_change(self):
        """
        A brand-new user should have an already-expired password, and therefore
        be redirected to the password change form on any request.
        """
        user = User.objects.create_user(username="foo",
                                        password="<PASSWORD>",
                                        email="<EMAIL>")
        self.client.login(username="foo", password="<PASSWORD>")
        try:
            self.assertRedirects(self.client.get("/home/"),
                                 MandatoryPasswordChangeMiddleware().password_change_url)
            never_expire_password(user)
            self.assertEqual(self.client.get("/home/").status_code, 200)
        finally:
            self.client.logout()
            user.delete()
{'fraction_non_alphanumeric': 0.0879974462651628, 'fraction_numerical': 0.002766546073632688, 'mean_word_length': 2.893537696768848, 'pattern_counts': {'":': 4, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7113187', 'n_tokens_mistral': 2536, 'n_tokens_neox': 2471, 'n_words': 557}