<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

import crypt
import sys

from django.contrib import auth
from django.core import mail
from django.test import Client, TestCase
from django.utils import translation

from xorgauth.accounts.models import User, UserAlias
import xorgauth.forms


class AuthenticationTests(TestCase):
    def setUp(self):
        # Run tests in French in order to test translations
        translation.activate('fr')
        self.vaneau = User.objects.create_user(
            hrid='louis.vaneau.1829',
            main_email='<EMAIL>',
            password='<PASSWORD>!'
        )
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        # Add classic aliases
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        UserAlias(user=self.vaneau, email='<EMAIL>').save()

    def test_auth_hrid(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau.1829', True))
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))

    def test_auth_hrid_badpass(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau.1829', True))
        c = Client()
        self.assertFalse(c.login(username='louis.vaneau.1829', password='<PASSWORD>'))

    def test_auth_hrid_disabled(self):
        self.vaneau.is_active = False
        self.vaneau.save()
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau.1829', False))
        self.assertEqual(None, User.objects.get_for_login('louis.vaneau.1829', True))
        c = Client()
        self.assertFalse(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))

    def test_auth_nonexisting_hrid(self):
        self.assertEqual(None, User.objects.get_for_login('louis.vaneau.1830', True))
        c = Client()
        self.assertFalse(c.login(username='louis.vaneau.1830', password='<PASSWORD>!'))

    def test_auth_firstname_lastname(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau', True))
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau', password='<PASSWORD>!'))

    def test_auth_main_email(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('<EMAIL>', True))
        c = Client()
        self.assertTrue(c.login(username='<EMAIL>', password='<PASSWORD>!'))

    def test_auth_email_alias(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('<EMAIL>', True))
        c = Client()
        self.assertTrue(c.login(username='<EMAIL>', password='<PASSWORD>!'))

    def test_auth_nonexisting_email(self):
        self.assertEqual(None, User.objects.get_for_login('<EMAIL>', True))
        c = Client()
        self.assertFalse(c.login(username='<EMAIL>', password='<PASSWORD>!'))

    def test_auth_firstname_lastname_2_digits(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau.29', True))
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau.29', password='<PASSWORD>!'))

    def test_auth_homonym_same_curriculum(self):
        c = Client()
        homonym = User.objects.create_user(
            hrid="louis.vaneau.1830",  # same name, same curriculum, different year
            main_email="<EMAIL>",
            password="<PASSWORD>!"
        )
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias.objects.filter(user=self.vaneau, email__startswith="louis.vaneau@").delete()
        self.assertEqual(None, User.objects.get_for_login("louis.vaneau", True))
        self.assertFalse(c.login(username='louis.vaneau', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.29', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.30', password='<PASSWORD>!'))

    def test_auth_homonym_different_curriculum(self):
        c = Client()
        homonym = User.objects.create_user(
            hrid='louis.vaneau.d1829',  # same name, same year, different curriculum
            main_email='<EMAIL>',
            password='<PASSWORD>!'
        )
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        self.assertIsNone(User.objects.get_for_login('louis.vaneau', True))
        self.assertFalse(c.login(username='louis.vaneau', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.29', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.d29', password='<PASSWORD>!'))

    def test_auth_homonym_2_digits(self):
        c = Client()
        homonym = User.objects.create_user(
            hrid='louis.vaneau.1929',  # same name, same curriculum, different year but same "2 digits"
            main_email='<EMAIL>',
            password='<PASSWORD>!'
        )
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias.objects.filter(user=self.vaneau, email__startswith="louis.vaneau@").delete()
        UserAlias.objects.filter(user=self.vaneau, email__startswith="louis.vaneau.29@").delete()
        self.assertEqual(None, User.objects.get_for_login('louis.vaneau.29', True))
        self.assertFalse(c.login(username='louis.vaneau.29', password='<PASSWORD>!'))

    def test_googleapps_password(self):
        """Test setting the Google Apps password when setting the password"""
        self.vaneau.set_password('<PASSWORD>!')
        self.vaneau.save()
        gapps_password = self.vaneau.gapps_password.password
        self.assertEqual(crypt.crypt('Depuis Vaneau!', gapps_password), gapps_password)

        password = '<PASSWORD>?'
        self.vaneau.set_password(password)
        self.vaneau.save()
        self.vaneau = User.objects.get(hrid='louis.vaneau.1829')
        gapps_password = self.vaneau.gapps_password.password
        if sys.version_info < (3,):
            password = <PASSWORD>('<PASSWORD>')
        self.assertEqual(crypt.crypt(password, gapps_password), gapps_password)

    def test_password_reset_form(self):
        """Test using the password reset form"""
        form = xorgauth.forms.PasswordResetForm({
            'email': 'louis.vaneau.1829',
        })
        self.assertTrue(form.is_valid())
        self.assertEqual('<EMAIL>', form.cleaned_data['email'])
        form.save(domain_override='test.localhost')
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual('Réinitialisation du mot de passe Polytechnique.org', mail.outbox[0].subject)
        self.assertEqual(['<EMAIL>'], mail.outbox[0].to)

    def test_password_reset_form_unknown_user(self):
        """Test using the password reset form"""
        form = xorgauth.forms.PasswordResetForm({
            'email': 'louis.vaneau.1830',
        })
        self.assertFalse(form.is_valid())
        self.assertEqual({
            'email': ['Compte utilisateur inconnu'],
        }, form.errors)
        self.assertEqual({}, form.cleaned_data)

    def test_password_reset_form_space(self):
        """Entering a space is invalid"""
        form = xorgauth.forms.PasswordResetForm({
            'email': ' ',
        })
        self.assertFalse(form.is_valid())
        self.assertEqual({
            'email': ['Ce champ est obligatoire.'],
        }, form.errors)
        self.assertEqual({}, form.cleaned_data)

    def test_auth_session_expiry(self):
        c = Client()
        c.post('/accounts/login/', {'username': 'louis.vaneau.1829', 'password': '<PASSWORD>!', 'expiry': 'now'})
        self.assertTrue(auth.get_user(c).is_authenticated)
        self.assertTrue(c.session.get_expire_at_browser_close())<commit_msg>Add tests for SetPasswordForm and PasswordChangeForm<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

import crypt
import sys

from django.contrib import auth
from django.core import mail
from django.test import Client, TestCase
from django.utils import translation

from xorgauth.accounts.models import User, UserAlias
import xorgauth.forms


class AuthenticationTests(TestCase):
    def setUp(self):
        # Run tests in French in order to test translations
        translation.activate('fr')
        self.vaneau = User.objects.create_user(
            hrid='louis.vaneau.1829',
            main_email='<EMAIL>',
            password='<PASSWORD>!'
        )
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        # Add classic aliases
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        UserAlias(user=self.vaneau, email='<EMAIL>').save()
        UserAlias(user=self.vaneau, email='<EMAIL>').save()

    def test_auth_hrid(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau.1829', True))
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))

    def test_auth_hrid_badpass(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau.1829', True))
        c = Client()
        self.assertFalse(c.login(username='louis.vaneau.1829', password='<PASSWORD>'))

    def test_auth_hrid_disabled(self):
        self.vaneau.is_active = False
        self.vaneau.save()
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau.1829', False))
        self.assertEqual(None, User.objects.get_for_login('louis.vaneau.1829', True))
        c = Client()
        self.assertFalse(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))

    def test_auth_nonexisting_hrid(self):
        self.assertEqual(None, User.objects.get_for_login('louis.vaneau.1830', True))
        c = Client()
        self.assertFalse(c.login(username='louis.vaneau.1830', password='<PASSWORD>au!'))

    def test_auth_firstname_lastname(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau', True))
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau', password='<PASSWORD>!'))

    def test_auth_main_email(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('<EMAIL>', True))
        c = Client()
        self.assertTrue(c.login(username='<EMAIL>', password='<PASSWORD>!'))

    def test_auth_email_alias(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('<EMAIL>', True))
        c = Client()
        self.assertTrue(c.login(username='<EMAIL>', password='<PASSWORD>!'))

    def test_auth_nonexisting_email(self):
        self.assertEqual(None, User.objects.get_for_login('<EMAIL>', True))
        c = Client()
        self.assertFalse(c.login(username='<EMAIL>', password='<PASSWORD>!'))

    def test_auth_firstname_lastname_2_digits(self):
        self.assertEqual(self.vaneau, User.objects.get_for_login('louis.vaneau.29', True))
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau.29', password='<PASSWORD>!'))

    def test_auth_homonym_same_curriculum(self):
        c = Client()
        homonym = User.objects.create_user(
            hrid="louis.vaneau.1830",  # same name, same curriculum, different year
            main_email="<EMAIL>",
            password="<PASSWORD>!"
        )
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias.objects.filter(user=self.vaneau, email__startswith="louis.vaneau@").delete()
        self.assertEqual(None, User.objects.get_for_login("louis.vaneau", True))
        self.assertFalse(c.login(username='louis.vaneau', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.29', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.30', password='<PASSWORD>!'))

    def test_auth_homonym_different_curriculum(self):
        c = Client()
        homonym = User.objects.create_user(
            hrid='louis.vaneau.d1829',  # same name, same year, different curriculum
            main_email='<EMAIL>',
            password='<PASSWORD>!'
        )
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias(user=homonym, email="<EMAIL>").save()
        self.assertIsNone(User.objects.get_for_login('louis.vaneau', True))
        self.assertFalse(c.login(username='louis.vaneau', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.29', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.d29', password='<PASSWORD>!'))

    def test_auth_homonym_2_digits(self):
        c = Client()
        homonym = User.objects.create_user(
            hrid='louis.vaneau.1929',  # same name, same curriculum, different year but same "2 digits"
            main_email='<EMAIL>',
            password='<PASSWORD>!'
        )
        UserAlias(user=homonym, email="<EMAIL>").save()
        UserAlias.objects.filter(user=self.vaneau, email__startswith="louis.vaneau@").delete()
        UserAlias.objects.filter(user=self.vaneau, email__startswith="louis.vaneau.29@").delete()
        self.assertEqual(None, User.objects.get_for_login('louis.vaneau.29', True))
        self.assertFalse(c.login(username='louis.vaneau.29', password='<PASSWORD>!'))

    def test_googleapps_password(self):
        """Test setting the Google Apps password when setting the password"""
        self.vaneau.set_password('<PASSWORD>!')
        self.vaneau.save()
        gapps_password = self.vaneau.gapps_password.password
        self.assertEqual(crypt.crypt('Depuis Vaneau!', gapps_password), gapps_password)

        password = '<PASSWORD>?'
        self.vaneau.set_password(password)
        self.vaneau.save()
        self.vaneau = User.objects.get(hrid='louis.vaneau.1829')
        gapps_password = <PASSWORD>au.gapps_password.password
        if sys.version_info < (3,):
            password = <PASSWORD>('utf-8')
        self.assertEqual(crypt.crypt(password, gapps_password), gapps_password)

    def test_password_reset_form(self):
        """Test using the password reset form"""
        form = xorgauth.forms.PasswordResetForm({
            'email': 'louis.vaneau.1829',
        })
        self.assertTrue(form.is_valid())
        self.assertEqual('<EMAIL>', form.cleaned_data['email'])
        form.save(domain_override='test.localhost')
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual('Réinitialisation du mot de passe Polytechnique.org', mail.outbox[0].subject)
        self.assertEqual(['<EMAIL>'], mail.outbox[0].to)

    def test_password_reset_form_unknown_user(self):
        """Test using the password reset form"""
        form = xorgauth.forms.PasswordResetForm({
            'email': 'louis.vaneau.1830',
        })
        self.assertFalse(form.is_valid())
        self.assertEqual({
            'email': ['Compte utilisateur inconnu'],
        }, form.errors)
        self.assertEqual({}, form.cleaned_data)

    def test_password_reset_form_space(self):
        """Entering a space is invalid"""
        form = xorgauth.forms.PasswordResetForm({
            'email': ' ',
        })
        self.assertFalse(form.is_valid())
        self.assertEqual({
            'email': ['Ce champ est obligatoire.'],
        }, form.errors)
        self.assertEqual({}, form.cleaned_data)

    def test_password_set_form(self):
        """Test using the password set form"""
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))
        form = xorgauth.forms.SetPasswordForm(user=self.vaneau, data={
            'new_password1': '<PASSWORD>?',
            'new_password2': '<PASSWORD>?',
        })
        self.assertTrue(form.is_valid())
        self.assertEqual('Mot de passe différent?', form.cleaned_data['new_password1'])
        form.save()
        # Athentication with the previous password fails and it works with the new password
        self.assertFalse(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.1829', password='<PASSWORD>?'))

    def test_password_change_form(self):
        """Test using the password change form"""
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))
        form = xorgauth.forms.PasswordChangeForm(user=self.vaneau, data={
            'old_password': '<PASSWORD>!',
            'new_password1': '<PASSWORD>?',
            'new_password2': '<PASSWORD>?',
        })
        self.assertTrue(form.is_valid())
        self.assertEqual('Mot de passe différent?', form.cleaned_data['new_password1'])
        form.save()
        # Athentication with the previous password fails and it works with the new password
        self.assertFalse(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))
        self.assertTrue(c.login(username='louis.vaneau.1829', password='<PASSWORD>?'))

    def test_password_change_form_incorrect_oldpass(self):
        """Test using the password change form with an incorrect old password"""
        c = Client()
        self.assertTrue(c.login(username='louis.vaneau.1829', password='<PASSWORD>!'))
        form = xorgauth.forms.PasswordChangeForm(user=self.vaneau, data={
            'old_password': '<PASSWORD>?',
            'new_password1': '<PASSWORD>?',
            'new_password2': '<PASSWORD>?',
        })
        self.assertFalse(form.is_valid())
        self.assertEqual({
            'old_password': ['V<PASSWORD> ancien mot de passe est incorrect. Veuillez le rectifier.'],
        }, form.errors)
        self.assertEqual({
            'new_password1': 'Mot de passe <PASSWORD>?',
            'new_password2': '<PASSWORD> de passe <PASSWORD>?',
        }, form.cleaned_data)

    def test_auth_session_expiry(self):
        c = Client()
        c.post('/accounts/login/', {'username': 'louis.vaneau.1829', 'password': '<PASSWORD>!', 'expiry': 'now'})
        self.assertTrue(auth.get_user(c).is_authenticated)
        self.assertTrue(c.session.get_expire_at_browser_close())
{'fraction_non_alphanumeric': 0.15080550517443722, 'fraction_numerical': 0.012109249973327643, 'mean_word_length': 3.28894989704873, 'pattern_counts': {'":': 0, '<': 128, '<?xml version=': 0, '>': 126, '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': '5130696', 'n_tokens_mistral': 6199, 'n_tokens_neox': 6091, 'n_words': 880}