Exemple #1
0
    def setUp(cls):
        cls.client_simple = AuthGroupeXClient.objects.create(
            privkey='356a192b7913b04c54574d18c28d46e6395428ab',  # SHA1("1")
            name='Test AuthGroupeX Client',
            data_fields='matricule_ax,nom,prenom,full_promo,forlife,sex',
            return_urls=r'#https://example\.com/#',
            allow_xnet=False,
        )

        vaneau = User.objects.create_user(
            hrid='louis.vaneau.1829',
            fullname='Louis Vaneau',
            firstname='Louis',
            lastname='Vaneau',
            sex='male',
            main_email='*****@*****.**',
            password='******',
            axid='18290001',
            schoolid='18290042',
            xorgdb_uid=1,
            study_year='X1829',
            grad_year=1832,
        )
        cls.role_x = Role.objects.create(hrid='x', display='X')
        cls.role_xnet = Role.objects.create(hrid='xnet', display='External')
        vaneau.roles.add(cls.role_x)
        vaneau.save()
        UserAlias(user=vaneau, email='*****@*****.**').save()
    def setUp(self):
        call_command('creatersakey')

        client_public_noconsent = oidc_provider.models.Client(
            name='Test Client',
            client_id='123456789',
            client_type='public',
            client_secret='',
            redirect_uris=['http://example.com/'],
            require_consent=False)
        client_public_noconsent.save()

        response_type = oidc_provider.models.ResponseType.objects.get(value='id_token token')
        client_public_noconsent.response_types.add(response_type)

        self.vaneau = User.objects.create_user(
            hrid='louis.vaneau.1829',
            fullname='Louis Vaneau',
            main_email='*****@*****.**',
            password='******',
            axid='18290001',
            study_year='X1829',
            grad_year=1829,
        )
        UserAlias(user=self.vaneau, email='*****@*****.**').save()
Exemple #3
0
 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='*****@*****.**',
         password='******')
     UserAlias(user=homonym,
               email="*****@*****.**").save()
     UserAlias(user=homonym,
               email="*****@*****.**").save()
     UserAlias(user=homonym, email="*****@*****.**").save()
     UserAlias(user=homonym, email="*****@*****.**").save()
     UserAlias(user=homonym, email="*****@*****.**").save()
     self.assertIsNone(User.objects.get_for_login('louis.vaneau', True))
     self.assertFalse(
         c.login(username='******', password='******'))
     self.assertTrue(
         c.login(username='******', password='******'))
     self.assertTrue(
         c.login(username='******',
                 password='******'))
Exemple #4
0
 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="*****@*****.**",
         password="******")
     UserAlias(user=homonym,
               email="*****@*****.**").save()
     UserAlias(user=homonym, email="*****@*****.**").save()
     UserAlias(user=homonym, 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='******', password='******'))
     self.assertTrue(
         c.login(username='******', password='******'))
     self.assertTrue(
         c.login(username='******',
                 password='******'))
Exemple #5
0
 def test_non_lowercase_alias_email(self):
     """Test using non-lowercase alias email addresses"""
     user = User.objects.create_user(
         hrid='louis.vaneau.1829',
         fullname='Louis Vaneau',
         preferred_name='Louis Vaneau',
         main_email='*****@*****.**',
         password='******')
     alias = UserAlias(user=user, email='*****@*****.**')
     alias.full_clean()
     alias.email = '*****@*****.**'
     with self.assertRaises(ValidationError):
         alias.full_clean()
Exemple #6
0
 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='*****@*****.**',
         password='******')
     UserAlias(user=homonym, 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='******', password='******'))
Exemple #7
0
 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='*****@*****.**',
         password='******')
     UserAlias(user=self.vaneau, email='*****@*****.**').save()
     # Add classic aliases
     UserAlias(user=self.vaneau,
               email='*****@*****.**').save()
     UserAlias(user=self.vaneau,
               email='*****@*****.**').save()
     UserAlias(user=self.vaneau, email='*****@*****.**').save()
     UserAlias(user=self.vaneau, email='*****@*****.**').save()
     UserAlias(user=self.vaneau, email='*****@*****.**').save()
    def handle(self, *args, **options):
        is_verbose = int(options['verbosity']) >= 2
        with open(options['jsonfile'][0], 'r') as jsonfd:
            jsondata = json.load(jsonfd)
        if 'accounts' not in jsondata:
            raise CommandError("Unable to find account entries")
        hasher = PBKDF2WrappedSHA1PasswordHasher()
        admin_role = Role.get_admin()
        role_displays = {
            # Alumni
            'x': 'X',
            'master': 'Master',
            'phd': 'PhD',
            # Staff
            'ax': 'AX',
            'fx': 'FX',
            'school': 'School',
            # Other
            'xnet': 'External',
        }
        type_roles = {}
        for rolename, roledisplay in role_displays.items():
            type_roles[rolename], created = Role.objects.get_or_create(hrid=rolename)
            if created:
                if is_verbose:
                    print("Creating role %r (%r)" % (rolename, roledisplay))
                type_roles[rolename].display = roledisplay
                type_roles[rolename].full_clean()
                type_roles[rolename].save()

        accounts_num = len(jsondata['accounts'])
        for idx_account, account_data in enumerate(jsondata['accounts']):
            # Do not import virtual accounts
            if account_data['type'] == 'virtual':
                continue

            hrid = account_data['hruid']
            try:
                user = User.objects.get(hrid=hrid)
                if is_verbose:
                    print("Updating user %s (%d/%d)" % (hrid, idx_account + 1, accounts_num))
            except ObjectDoesNotExist:
                user = User(hrid=hrid)
                if is_verbose:
                    print("Creating user %s (%d/%d)" % (hrid, idx_account + 1, accounts_num))

            user.fullname = account_data['full_name']
            user.preferred_name = account_data['display_name']
            user.main_email = account_data['email']
            user.password = hasher.encode_sha1_hash(account_data['password'])
            user.axid = account_data['ax_id']
            user.schoolid = account_data['xorg_id']
            user.xorgdb_uid = account_data['uid']
            user.firstname = account_data['firstname']
            user.lastname = account_data['lastname']
            user.sex = account_data['sex']
            user.study_year = account_data['promo']
            user.grad_year = account_data['grad_year']
            user.full_clean()
            user.save()
            if account_data['is_admin']:
                user.roles.add(admin_role)
                user.save()

            # Import groups
            for groupname, perms in account_data['groups'].items():
                group = Group.objects.get_or_create(shortname=groupname)[0]
                GroupMembership.objects.get_or_create(
                    group=group,
                    user=user,
                    perms=perms)

            # Import email aliases
            for email in account_data['email_source'].keys():
                try:
                    alias = UserAlias.objects.get(email=email)
                except ObjectDoesNotExist:
                    alias = UserAlias(user=user, email=email)
                    alias.full_clean()
                    alias.save()
                else:
                    if alias.user != user:
                        raise CommandError("Duplicate email %r" % email)

            # Import account type into role
            user.roles.add(type_roles[account_data['type']])
            user.full_clean()
            user.save()
Exemple #9
0
    def handle(self, *args, **options):
        is_verbose = int(options['verbosity']) >= 2
        with open(options['jsonfile'][0], 'r') as jsonfd:
            jsondata = json.load(jsonfd)
        if 'accounts' not in jsondata:
            raise CommandError("Unable to find account entries")
        hasher = PBKDF2WrappedSHA1PasswordHasher()
        admin_role = Role.get_admin()
        role_displays = {
            # Alumni
            'x': 'X',
            'master': 'Master',
            'phd': 'PhD',
            # Staff
            'ax': 'AX',
            'fx': 'FX',
            'school': 'School',
            # Other
            'xnet': 'External',
        }
        type_roles = {}
        for rolename, roledisplay in role_displays.items():
            type_roles[rolename], created = Role.objects.get_or_create(hrid=rolename)
            if created:
                if is_verbose:
                    print("Creating role %r (%r)" % (rolename, roledisplay))
                type_roles[rolename].display = roledisplay
                type_roles[rolename].full_clean()
                type_roles[rolename].save()

        accounts_num = len(jsondata['accounts'])
        for idx_account, account_data in enumerate(jsondata['accounts']):
            # Do not import virtual accounts
            if account_data['type'] == 'virtual':
                continue

            hrid = account_data['hruid']
            try:
                user = User.objects.get(hrid=hrid)
                is_creating_user = False
                if is_verbose:
                    print("Updating user %s (%d/%d)" % (hrid, idx_account + 1, accounts_num))
            except ObjectDoesNotExist:
                user = User(hrid=hrid)
                is_creating_user = True
                if is_verbose:
                    print("Creating user %s (%d/%d)" % (hrid, idx_account + 1, accounts_num))

            # Sometimes, display_name is empty. Use the first name or a name
            # from the email address
            if not account_data['display_name']:
                if account_data['firstname']:
                    if is_verbose:
                        print("... using first name (%r) as display name" % account_data['firstname'])
                    account_data['display_name'] = account_data['firstname']
                else:
                    # This should only happen for external accounts
                    if account_data['type'] != 'xnet':
                        raise CommandError(
                            "No display_name nor firstname for a non-external account: %r" % account_data)

                    display_name = account_data['email'].split('@')[0]
                    if not display_name:
                        raise CommandError(
                            "No display_name nor firstname nor email in account data: %r" % account_data)
                    if is_verbose:
                        print("... using email user (%r) as display name" % display_name)
                    account_data['display_name'] = display_name

                    # If full name is empty too, use the same display name
                    if not account_data['full_name']:
                        account_data['full_name'] = display_name

            # Update the fields of user, if needed
            user_fields = {
                'fullname': account_data['full_name'],
                'preferred_name': account_data['display_name'],
                'main_email': account_data['email'],
                'axid': account_data['ax_id'],
                'schoolid': str(account_data['xorg_id']) if account_data['xorg_id'] else None,
                'xorgdb_uid': account_data['uid'],
                'firstname': account_data['firstname'],
                'lastname': account_data['lastname'],
                'sex': account_data['sex'],
                'study_year': account_data['promo'],
                'grad_year': account_data['grad_year'],
            }
            is_user_modified = is_creating_user
            for field_name, new_value in user_fields.items():
                if getattr(user, field_name) != new_value:
                    if not is_creating_user and is_verbose:
                        print("... updating %r because %r is %r, not %r" % (
                            user,
                            field_name,
                            getattr(user, field_name),
                            new_value))
                    is_user_modified = True
                    setattr(user, field_name, new_value)

            if is_creating_user:
                # Do not override the password when updating an existing account
                if account_data['password']:
                    user.password = hasher.encode_sha1_hash(account_data['password'])
                else:
                    user.set_unusable_password()

            # Validate and save the user only if it has been modified
            if is_user_modified:
                user.full_clean()
                user.save()

            # Add new administrators
            if account_data['is_admin'] and not user.roles.filter(pk=admin_role.pk).exists():
                user.roles.add(admin_role)
                user.save()

            # Import groups
            for groupname, perms in account_data['groups'].items():
                group = Group.objects.get_or_create(shortname=groupname)[0]
                # Perform an "update_or_create" on the membership, calling full_clean() also
                membership, created = GroupMembership.objects.get_or_create(
                    group=group,
                    user=user,
                    defaults={'perms': perms})
                if not created and membership.perms != perms:
                    membership.perms = perms
                    membership.full_clean()
                    membership.save()
                else:
                    # check values, to ensure a sane database
                    membership.full_clean()

            # Import email aliases
            current_user_aliases = set(a.email for a in user.aliases.all())
            for email in account_data['email_source'].keys():
                if email in current_user_aliases:
                    continue
                try:
                    alias = UserAlias.objects.get(email=email)
                except ObjectDoesNotExist:
                    alias = UserAlias(user=user, email=email)
                    alias.full_clean()
                    alias.save()
                else:
                    if alias.user != user:
                        raise CommandError("Duplicate email %r" % email)

            # Import account type into role
            user_type_role = type_roles[account_data['type']]
            if not user.roles.filter(pk=user_type_role.pk).exists():
                user.roles.add(user_type_role)
                user.full_clean()
                user.save()
Exemple #10
0
 def setUp(cls):
     vaneau = User.objects.create_user(
         hrid='louis.vaneau.1829',
         main_email='*****@*****.**',
         password='******')
     UserAlias(user=vaneau, email='*****@*****.**').save()