def create_default_ou(app_config,
                      verbosity=2,
                      interactive=True,
                      using=DEFAULT_DB_ALIAS,
                      **kwargs):
    if not router.allow_migrate(using, get_ou_model()):
        return
    # be sure new objects names are localized using the default locale
    with override(settings.LANGUAGE_CODE):
        OrganizationalUnit = get_ou_model()
        if OrganizationalUnit.objects.exists():
            return
        # Create a default OU if none exists currently
        default_ou, created = OrganizationalUnit.objects.get_or_create(
            slug='default',
            defaults={
                'default': True,
                'name': _('Default organizational unit'),
            })
        # Update all existing models having an ou field to the default ou
        for app in apps.get_app_configs():
            for model in app.get_models():
                related_model = get_fk_model(model, 'ou')
                if not related_model == OrganizationalUnit:
                    return
                model.objects.filter(ou__isnull=True).update(ou=default_ou)
示例#2
0
def update_rbac_on_ou_post_save(sender, instance, created, raw, **kwargs):
    from .management import update_ou_admin_roles, update_ous_admin_roles, \
        update_content_types_roles
    if get_ou_model().objects.count() < 3 and created:
        update_ous_admin_roles()
    else:
        update_ou_admin_roles(instance)
示例#3
0
def test_custom_ou(slapd, settings, client):
    OU = get_ou_model()
    ou = OU.objects.create(name='test', slug='test')
    settings.LDAP_AUTH_SETTINGS = [{
        'url': [slapd.ldap_url],
        'basedn': u'o=ôrga',
        'use_tls': False,
        'ou_slug': 'test',
    }]
    result = client.post('/login/', {
        'login-password-submit': '1',
        'username': USERNAME,
        'password': PASS
    },
                         follow=True)
    assert result.status_code == 200
    assert 'Étienne Michu' in str(result)
    User = get_user_model()
    assert User.objects.count() == 1
    user = User.objects.get()
    assert user.username == u'%s@ldap' % USERNAME
    assert user.first_name == u'Étienne'
    assert user.last_name == u'Michu'
    assert user.ou == ou
    assert not user.check_password(PASS)
def update_rbac_on_ou_post_save(sender, instance, created, raw, **kwargs):
    from .management import update_ou_admin_roles, update_ous_admin_roles, \
        update_content_types_roles
    if get_ou_model().objects.count() < 3 and created:
        update_ous_admin_roles()
    else:
        update_ou_admin_roles(instance)
示例#5
0
class OrganizationalUnitView(views.BaseTableView):
    template_name = 'authentic2/manager/ous.html'
    model = get_ou_model()
    table_class = tables.OUTable
    search_form_class = forms.NameSearchForm
    permissions = ['a2_rbac.search_organizationalunit']
    title = _('Organizational units')
示例#6
0
class RoleEditForm(SlugMixin, HideOUFieldMixin, LimitQuerysetFormMixin,
                   CssClass, forms.ModelForm):
    ou = forms.ModelChoiceField(queryset=get_ou_model().objects,
                                required=True,
                                label=_('Organizational unit'))

    def clean_name(self):
        qs = get_role_model().objects.all()
        if self.instance and self.instance.pk:
            qs = qs.exclude(pk=self.instance.pk)
        ou = self.cleaned_data.get('ou')
        # Test unicity of name for an OU and globally if no OU is present
        name = self.cleaned_data.get('name')
        if name and ou:
            query = Q(name=name) & (Q(ou__isnull=True) | Q(ou=ou))
            if qs.filter(query).exists():
                raise ValidationError({
                    'name':
                    _('This name is not unique over this organizational unit.')
                })
        return name

    class Meta:
        model = get_role_model()
        fields = ('name', 'ou', 'description')
示例#7
0
class OrganizationalUnitAddView(views.BaseAddView):
    model = get_ou_model()
    permissions = ['a2_rbac.add_organizationalunit']
    form_class = forms.OUEditForm
    title = _('Add organizational unit')

    def get_success_url(self):
        return '..'
示例#8
0
def test_manager_ou(app, superuser_or_admin, ou1):
    OU = get_ou_model()

    manager_home_page = login(app, superuser_or_admin,
                              reverse('a2-manager-homepage'))
    ou_homepage = manager_home_page.click(href='organizational-units')
    assert set([e.text for e in ou_homepage.pyquery('td.name')
                ]) == set(['OU1', 'Default organizational unit'])

    # add a new ou
    add_ou_page = ou_homepage.click('Add')
    add_ou_page.form.set('name', 'ou2')
    add_ou_page.form.set('default', True)
    ou_homepage = add_ou_page.form.submit().follow()
    ou2 = OU.objects.get(name='ou2')
    assert set([e.text for e in ou_homepage.pyquery('td.name')
                ]) == set(['OU1', 'Default organizational unit', 'ou2'])
    assert len(
        ou_homepage.pyquery('tr[data-pk="%s"] td.default span.true' %
                            ou2.pk)) == 1

    # FIXME: table lines are not clickable as they do not contain an anchor
    # default ou cannot be deleted
    ou2_detail_page = app.get(
        reverse('a2-manager-ou-detail', kwargs={'pk': ou2.pk}))
    assert ou2_detail_page.pyquery('a.disabled').text() == 'Delete'

    # but ou1 can be deleted
    ou1_detail_page = app.get(
        reverse('a2-manager-ou-detail', kwargs={'pk': ou1.pk}))
    ou1_delete_page = ou1_detail_page.click('Delete')
    ou_homepage = ou1_delete_page.form.submit().follow()
    assert set([e.text for e in ou_homepage.pyquery('td.name')
                ]) == set(['Default organizational unit', 'ou2'])

    # remake old default ou the default one
    old_default = OU.objects.get(name__contains='Default')
    old_default_detail_page = app.get(
        reverse('a2-manager-ou-detail', kwargs={'pk': old_default.pk}))
    assert not old_default_detail_page.pyquery(
        'input[name="default"][checked="checked"]')
    old_default_edit_page = old_default_detail_page.click('Edit')
    old_default_edit_page.form.set('default', True)
    old_default_detail_page = old_default_edit_page.form.submit().follow()
    # check detail page has changed
    assert old_default_detail_page.pyquery(
        'input[name="default"][checked="checked"]')
    # check ou homepage has changed too
    ou_homepage = old_default_detail_page.click('Organizational unit')
    assert set([e.text for e in ou_homepage.pyquery('td.name')
                ]) == set(['Default organizational unit', 'ou2'])
    assert len(ou_homepage.pyquery('span.true')) == 1
    assert len(
        ou_homepage.pyquery('tr[data-pk="%s"] td.default span.true' %
                            ou2.pk)) == 0
    assert len(
        ou_homepage.pyquery('tr[data-pk="%s"] td.default span.true' %
                            old_default.pk)) == 1
示例#9
0
 def get_table(self, **kwargs):
     OU = get_ou_model()
     exclude_ou = False
     if (hasattr(self, 'search_form') and self.search_form.is_valid()
             and self.search_form.cleaned_data.get('ou') is not None):
         exclude_ou = True
     if OU.objects.count() < 2:
         exclude_ou = True
     if exclude_ou:
         kwargs['exclude'] = ['ou']
     return super(HideOUColumnMixin, self).get_table(**kwargs)
示例#10
0
 def get_by_natural_key(self, ou_natural_key, slug):
     OU = get_ou_model()
     kwargs = {'slug': slug}
     if ou_natural_key:
         try:
             ou = OU.objects.get_by_natural_key(*ou_natural_key)
         except OU.DoesNotExist:
             raise self.model.DoesNotExist
         kwargs['ou'] = ou
     else:
         kwargs['ou__isnull'] = True
     return self.get(**kwargs)
示例#11
0
def import_ou(ou_d):
    OU = get_ou_model()
    # ou = search_ou([ou_d['slug']])
    ou = search_ou(ou_d)
    if ou is None:
        ou = OU.objects.create(**ou_d)
        status = 'created'
    else:
        update_model(ou, ou_d)
        status = 'updated'
    # Ensure admin role is created
    ou.get_admin_role()
    return ou, status
示例#12
0
def test_role_parenting(db):
    OrganizationalUnit = utils.get_ou_model()
    Role = utils.get_role_model()
    RoleParenting = utils.get_role_parenting_model()

    ou = OrganizationalUnit.objects.create(name='ou')
    roles = []
    for i in range(10):
        roles.append(Role.objects.create(name='r%d' % i, ou=ou))

    assert Role.objects.count() == 10
    assert RoleParenting.objects.count() == 0
    for i in range(1, 3):
        RoleParenting.objects.create(parent=roles[i - 1], child=roles[i])
    assert RoleParenting.objects.filter(direct=True).count() == 2
    assert RoleParenting.objects.filter(direct=False).count() == 1
    for i, role in enumerate(roles[:3]):
        assert role.children().count() == 3 - i
        assert role.parents().count() == i + 1
        assert role.children(False).count() == 3 - i - 1
        assert role.parents(False).count() == i

    for i in range(4, 6):
        RoleParenting.objects.create(parent=roles[i - 1], child=roles[i])
    assert RoleParenting.objects.filter(direct=True).count() == 4
    assert RoleParenting.objects.filter(direct=False).count() == 2
    for i, role in enumerate(roles[3:6]):
        assert role.children().count() == 3 - i
        assert role.parents().count() == i + 1
        assert role.children(False).count() == 3 - i - 1
        assert role.parents(False).count() == i
    RoleParenting.objects.create(parent=roles[2], child=roles[3])
    assert RoleParenting.objects.filter(direct=True).count() == 5
    assert RoleParenting.objects.filter(direct=False).count() == 10
    for i in range(6):
        assert roles[i].parents().distinct().count() == i + 1
    for i, role in enumerate(roles[:6]):
        assert role.children().count() == 6 - i
        assert role.parents().count() == i + 1
        assert role.children(False).count() == 6 - i - 1
        assert role.parents(False).count() == i
    RoleParenting.objects.filter(parent=roles[2], child=roles[3],
                                 direct=True).delete()
    assert RoleParenting.objects.filter(direct=True).count() == 4
    assert RoleParenting.objects.filter(direct=False).count() == 2
    # test that it works with cycles
    RoleParenting.objects.create(parent=roles[2], child=roles[3])
    RoleParenting.objects.create(parent=roles[5], child=roles[0])
    for role in roles[:6]:
        assert role.children().count() == 6
        assert role.parents().count() == 6
示例#13
0
def create_default_ou(app_config, verbosity=2, interactive=True,
                      using=DEFAULT_DB_ALIAS, **kwargs):
    if not router.allow_migrate(using, get_ou_model()):
        return
    # be sure new objects names are localized using the default locale
    with override(settings.LANGUAGE_CODE):
        OrganizationalUnit = get_ou_model()
        if OrganizationalUnit.objects.exists():
            return
        # Create a default OU if none exists currently
        default_ou, created = OrganizationalUnit.objects.get_or_create(
            slug='default',
            defaults={
                'default': True,
                'name': _('Default organizational unit'),
            })
        # Update all existing models having an ou field to the default ou
        for app in apps.get_app_configs():
            for model in app.get_models():
                related_model = get_fk_model(model, 'ou')
                if not related_model == OrganizationalUnit:
                    return
                model.objects.filter(ou__isnull=True).update(ou=default_ou)
示例#14
0
class OrganizationalUnitDetailView(views.BaseDetailView):
    model = get_ou_model()
    permissions = ['a2_rbac.view_organizationalunit']
    form_class = forms.OUEditForm
    template_name = 'authentic2/manager/ou_detail.html'

    @property
    def title(self):
        return unicode(self.object)

    def authorize(self, request, *args, **kwargs):
        super(OrganizationalUnitDetailView,
              self).authorize(request, *args, **kwargs)
        self.can_delete = self.can_delete and not self.object.default
示例#15
0
    def populate_user_ou(self, user, dn, conn, block, attributes):
        '''Assign LDAP user to an ou, the default one if ou_slug setting is
           None'''

        ou_slug = block['ou_slug']
        OU = get_ou_model()
        if ou_slug:
            ou_slug = unicode(ou_slug)
            try:
                user.ou = OU.objects.get(slug=ou_slug)
            except OU.DoesNotExist:
                raise ImproperlyConfigured('ou_slug value is wrong for ldap %r',
                                          block['url'])
        else:
            user.ou = get_default_ou()
示例#16
0
def update_ous_admin_roles():
    '''Create general admin roles linked to all organizational units,
       they give general administrative rights to all mamanged content types
       scoped to the given organizational unit.
    '''
    Role = get_role_model()
    Permission = get_permission_model()
    OU = get_ou_model()
    ou_all = OU.objects.all()
    if len(ou_all) < 2:
        # If there is no ou or less than two, only generate global management
        # roles
        return
    for ou in ou_all:
        update_ou_admin_roles(ou)
示例#17
0
def create_default_permissions(app_config,
                               verbosity=2,
                               interactive=True,
                               using=DEFAULT_DB_ALIAS,
                               **kwargs):
    from .models import CHANGE_PASSWORD_OP, RESET_PASSWORD_OP, ACTIVATE_OP, CHANGE_EMAIL_OP

    if not router.allow_migrate(using, get_ou_model()):
        return

    with override(settings.LANGUAGE_CODE):
        get_operation(CHANGE_PASSWORD_OP)
        get_operation(RESET_PASSWORD_OP)
        get_operation(ACTIVATE_OP)
        get_operation(CHANGE_EMAIL_OP)
示例#18
0
class ChoosePermissionForm(CssClass, forms.Form):
    operation = forms.ModelChoiceField(required=False,
                                       label=_('Operation'),
                                       queryset=Operation.objects)
    ou = forms.ModelChoiceField(label=_('Organizational unit'),
                                queryset=get_ou_model().objects,
                                required=False)
    target = forms.ModelChoiceField(label=_('Target object'),
                                    required=False,
                                    queryset=ContentType.objects)
    action = forms.CharField(initial='add',
                             required=False,
                             widget=forms.HiddenInput)
    permission = forms.ModelChoiceField(
        queryset=get_permission_model().objects,
        required=False,
        widget=forms.HiddenInput)
示例#19
0
 def get_queryset(self):
     qs = super(RolesMixin, self).get_queryset()
     qs = qs.select_related("ou")
     Permission = get_permission_model()
     permission_ct = ContentType.objects.get_for_model(Permission)
     ct_ct = ContentType.objects.get_for_model(ContentType)
     ou_ct = ContentType.objects.get_for_model(get_ou_model())
     permission_qs = Permission.objects.filter(target_ct_id__in=[ct_ct.id, ou_ct.id]).values_list("id", flat=True)
     # only non role-admin roles, they are accessed through the
     # RoleManager views
     if not self.admin_roles:
         qs = qs.filter(
             Q(admin_scope_ct__isnull=True) | Q(admin_scope_ct=permission_ct, admin_scope_id__in=permission_qs)
         )
     if not self.service_roles:
         qs = qs.filter(service__isnull=True)
     return qs
示例#20
0
def get_search_ou_perm(ou=None):
    if ou:
        Permission = rbac_utils.get_permission_model()
        view_ou_perm, created = Permission.objects.get_or_create(
            operation=rbac_utils.get_operation(SEARCH_OP),
            target_ct=ContentType.objects.get_for_model(ou),
            target_id=ou.pk,
            ou__isnull=True)
    else:
        OU = rbac_utils.get_ou_model()
        Permission = rbac_utils.get_permission_model()
        view_ou_perm, created = Permission.objects.get_or_create(
            operation=rbac_utils.get_operation(SEARCH_OP),
            target_ct=ContentType.objects.get_for_model(ContentType),
            target_id=ContentType.objects.get_for_model(OU).pk,
            ou__isnull=True)
    return view_ou_perm
示例#21
0
def test_manager_create_role(superuser_or_admin, app):
    # clear cache from previous runs
    from authentic2.manager.utils import get_ou_count
    get_ou_count.cache.cache = {}

    Role = get_role_model()
    OU = get_ou_model()

    non_admin_roles = Role.objects.exclude(slug__startswith='_')

    ou_add = login(app, superuser_or_admin, reverse('a2-manager-role-add'))
    form = ou_add.form
    assert 'name' in form.fields
    assert 'description' in form.fields
    assert 'ou' not in form.fields
    form.set('name', 'New role')
    response = form.submit().follow()
    assert non_admin_roles.count() == 1
    role = non_admin_roles.get()
    assert response.request.path == reverse('a2-manager-role-members',
                                            kwargs={'pk': role.pk})
    role_list = app.get(reverse('a2-manager-roles'))
    assert 'New role' in role_list

    # Test slug collision
    non_admin_roles.update(name='Old role')
    response = form.submit().follow()
    role_list = app.get(reverse('a2-manager-roles'))
    assert 'New role' in role_list
    assert 'Old role' in role_list
    assert non_admin_roles.count() == 2
    assert non_admin_roles.get(name='New role').slug == 'new-role1'
    assert non_admin_roles.get(name='Old role').slug == 'new-role'

    # Test multi-ou form
    OU.objects.create(name='New OU', slug='new-ou')
    ou_add = app.get(reverse('a2-manager-role-add'))
    form = ou_add.form
    assert 'name' in form.fields
    assert 'description' in form.fields
    assert 'ou' in form.fields
    options = [o[2] for o in form.fields['ou'][0].options]
    assert len(options) == 3
    assert '---------' in options
    assert 'New OU' in options
示例#22
0
class OrganizationalUnitDeleteView(views.BaseDeleteView):
    model = get_ou_model()
    template_name = 'authentic2/manager/ou_delete.html'
    permissions = ['a2_rbac.delete_organizationalunit']
    title = _('Delete organizational unit')

    def dispatch(self, request, *args, **kwargs):
        if self.get_object().default:
            messages.warning(
                request,
                _('You cannot delete the default '
                  'organizational unit, you must first '
                  'set another default organiational '
                  'unit.'))
            return self.return_ajax_response(
                request, HttpResponseRedirect(self.get_success_url()))
        return super(OrganizationalUnitDeleteView,
                     self).dispatch(request, *args, **kwargs)
示例#23
0
def update_ous_admin_roles():
    '''Create general admin roles linked to all organizational units,
       they give general administrative rights to all mamanged content types
       scoped to the given organizational unit.
    '''
    Role = get_role_model()
    Permission = get_permission_model()
    OU = get_ou_model()
    ou_all = OU.objects.all()
    if len(ou_all) < 2:
        # If there is no ou or less than two, only generate global management
        # roles
        Role.objects.filter(slug__startswith='_a2', ou__isnull=False).delete()
        Role.objects.filter(slug__startswith='_a2-managers-of-').delete()
        Permission.objects.filter(roles__isnull=True).delete()
        return
    for ou in ou_all:
        update_ou_admin_roles(ou)
示例#24
0
def patch_authentic_user():
    User = get_user_model()
    OU = get_ou_model()
    Role = get_role_model()
    organisation_unit = OU.objects.get(default=True)
    user_admin_commune = User.objects.get_or_create(
        username='******')[0]
    with provisionning:

        role_agent_fabriques = Role(name='Agent ayant acces aux fabriques',
                                    ou=organisation_unit)
        role_agent_fabriques.save()

        with open("/tmp/tmp_uuid_agent_fabriques.txt", 'w') as f:
            f.write(role_agent_fabriques.uuid)

        # Set role to user
        role_agent_fabriques.members.add(user_admin_commune)
示例#25
0
 def register_issuer(name,
                     issuer=None,
                     openid_configuration=None,
                     verify=True,
                     timeout=None,
                     ou=None):
     OU = get_ou_model()
     ou = OU.objects.get(default=True)
     return OIDCProvider.objects.create(
         name=name,
         ou=ou,
         issuer=issuer,
         strategy='create',
         authorization_endpoint=openid_configuration[
             'authorization_endpoint'],
         token_endpoint=openid_configuration['token_endpoint'],
         userinfo_endpoint=openid_configuration['userinfo_endpoint'],
         end_session_endpoint=openid_configuration['end_session_endpoint'])
示例#26
0
def test_manager_create_ou(superuser_or_admin, app):
    OU = get_ou_model()

    ou_add = login(app, superuser_or_admin, path=reverse('a2-manager-ou-add'))
    form = ou_add.form
    form.set('name', 'New OU')
    response = form.submit().follow()
    assert 'New OU' in response
    assert OU.objects.count() == 2
    assert OU.objects.get(name='New OU').slug == 'new-ou'

    # Test slug collision
    OU.objects.filter(name='New OU').update(name='Old OU')
    response = form.submit().follow()
    assert 'Old OU' in response
    assert 'New OU' in response
    assert OU.objects.get(name='Old OU').slug == 'new-ou'
    assert OU.objects.get(name='New OU').slug == 'new-ou1'
    assert OU.objects.count() == 3
示例#27
0
 def get_queryset(self):
     qs = super(RolesMixin, self).get_queryset()
     qs = qs.select_related('ou')
     Permission = get_permission_model()
     permission_ct = ContentType.objects.get_for_model(Permission)
     ct_ct = ContentType.objects.get_for_model(ContentType)
     ou_ct = ContentType.objects.get_for_model(get_ou_model())
     permission_qs = Permission.objects.filter(target_ct_id__in=[ct_ct.id, ou_ct.id]) \
         .values_list('id', flat=True)
     # only non role-admin roles, they are accessed through the
     # RoleManager views
     if not self.admin_roles:
         qs = qs.filter(
             Q(admin_scope_ct__isnull=True)
             | Q(admin_scope_ct=permission_ct,
                 admin_scope_id__in=permission_qs))
     if not self.service_roles:
         qs = qs.filter(service__isnull=True)
     return qs
示例#28
0
class AddLibertyProviderFromUrlForm(forms.Form):
    name = forms.CharField(max_length=140, label=_('Name'))
    slug = forms.SlugField(max_length=140, label=_('Shortcut'),
                           help_text=_("Internal nickname for the service provider"))
    url = forms.URLField(label=_("Metadata's URL"))
    ou = forms.ModelChoiceField(queryset=get_ou_model().objects, initial=get_default_ou,
                                label=_('Organizational unit'))

    def clean(self):
        cleaned_data = super(AddLibertyProviderFromUrlForm, self).clean()
        name = cleaned_data.get('name')
        slug = cleaned_data.get('slug')
        url = cleaned_data.get('url')
        ou = cleaned_data.get('ou')
        self.instance = None
        self.childs = []
        if name and slug and url:
            try:
                response = requests.get(url)
                response.raise_for_status()
                content = response.content
            except requests.RequestException, e:
                raise ValidationError(_('Retrieval of %(url)s failed: %(exception)s') % {
                    'url': url,
                    'exception': e
                })
            root = ET.fromstring(content)
            if root.tag != '{%s}EntityDescriptor' % lasso.SAML2_METADATA_HREF:
                raise ValidationError(_('Invalid SAML metadata: %s')
                                      % _('missing EntityDescriptor tag'))
            is_sp = not root.find('{%s}SPSSODescriptor' % lasso.SAML2_METADATA_HREF) is None
            if not is_sp:
                raise ValidationError(_('Invalid SAML metadata: %s')
                                      % _('missing SPSSODescriptor tags'))
            liberty_provider = LibertyProvider(name=name, slug=slug, metadata=content,
                                               metadata_url=url, ou=ou)
            liberty_provider.full_clean(exclude=('entity_id', 'protocol_conformance'))
            self.childs.append(LibertyServiceProvider(
                liberty_provider=liberty_provider,
                enabled=True))
            self.instance = liberty_provider
        return cleaned_data
示例#29
0
    def get_form_kwargs(self, **kwargs):
        '''Initialize mail from token'''
        kwargs = super(RegistrationCompletionView,
                       self).get_form_kwargs(**kwargs)
        if 'ou' in self.token:
            OU = get_ou_model()
            ou = get_object_or_404(OU, id=self.token['ou'])
        else:
            ou = get_default_ou()

        attributes = {'email': self.email, 'ou': ou}
        for key in self.token:
            if key in app_settings.A2_PRE_REGISTRATION_FIELDS:
                attributes[key] = self.token[key]
        logger.debug(u'attributes %s', attributes)

        prefilling_list = utils.accumulate_from_backends(
            self.request, 'registration_form_prefill')
        logger.debug(u'prefilling_list %s', prefilling_list)
        # Build a single meaningful prefilling with sets of values
        prefilling = {}
        for p in prefilling_list:
            for name, values in p.items():
                if name in self.fields:
                    prefilling.setdefault(name, set()).update(values)
        logger.debug(u'prefilling %s', prefilling)

        for name, values in prefilling.items():
            attributes[name] = ' '.join(values)
        logger.debug(u'attributes with prefilling %s', attributes)

        if self.token.get('user_id'):
            kwargs['instance'] = User.objects.get(id=self.token.get('user_id'))
        else:
            init_kwargs = {}
            for key in ('email', 'first_name', 'last_name', 'ou'):
                if key in attributes:
                    init_kwargs[key] = attributes[key]
            kwargs['instance'] = get_user_model()(**init_kwargs)

        return kwargs
示例#30
0
def test_manager_stress_create_user(superuser_or_admin, app, mailoutbox):
    User = get_user_model()
    OU = get_ou_model()

    new_ou = OU.objects.create(name='new ou', slug='new-ou')
    url = reverse('a2-manager-user-add', kwargs={'ou_pk': new_ou.pk})
    # create first user with [email protected] ou OU1 : OK

    assert len(mailoutbox) == 0
    assert User.objects.filter(ou_id=new_ou.id).count() == 0
    for i in range(100):
        ou_add = login(app, superuser_or_admin, url)
        form = ou_add.form
        form.set('first_name', 'John')
        form.set('last_name', 'Doe')
        form.set('email', '*****@*****.**')
        form.set('password1', 'ABcd1234')
        form.set('password2', 'ABcd1234')
        form.submit().follow()
        app.get('/logout/').form.submit()
    assert User.objects.filter(ou_id=new_ou.id).count() == 100
    assert len(mailoutbox) == 100
示例#31
0
def test_custom_ou(settings, client):
    OU = get_ou_model()
    ou = OU.objects.create(name='test', slug='test')
    settings.LDAP_AUTH_SETTINGS = [{
        'url': [slapd.ldapi_url],
        'basedn': 'o=orga',
        'use_tls': False,
        'ou_slug': 'test',
    }]
    result = client.post('/login/', {'login-password-submit': '1',
                                     'username': '******',
                                     'password': '******'}, follow=True)
    assert result.status_code == 200
    assert 'id="user"' in str(result)
    assert 'Étienne Michu' in str(result)
    User = get_user_model()
    assert User.objects.count() == 1
    user = User.objects.get()
    assert user.username == u'etienne.michu@ldap'
    assert user.first_name == u'Étienne'
    assert user.last_name == u'Michu'
    assert user.ou == ou
    assert not user.check_password('pass')
示例#32
0
    def get_by_natural_key(self, slug, ou_natural_key, service_natural_key):
        kwargs = {'slug': slug}
        if ou_natural_key is None:
            kwargs['ou__isnull'] = True
        else:
            OU = rbac_utils.get_ou_model()
            try:
                ou = OU.objects.get_by_natural_key(*ou_natural_key)
            except OU.DoesNotExist:
                raise self.model.DoesNotExist
            kwargs['ou'] = ou
        if service_natural_key is None:
            kwargs['service__isnull'] = True
        else:
            # XXX: prevent an import loop
            from authentic2.models import Service

            try:
                service = Service.objects.get_by_natural_key(*service_natural_key)
            except Service.DoesNotExist:
                raise self.model.DoesNotExist
            kwargs['service'] = service
        return self.get(**kwargs)
示例#33
0
    def permissions(self):
        """ Update permissions (delete everything then create)
        """
        created, deleted = [], []
        for perm in self._obj.permissions.all():
            perm.delete()
            deleted.append(perm)
        self._obj.permissions.clear()
        if self._permissions:
            for perm in self._permissions:
                op = Operation.objects.get_by_natural_key_json(
                    perm['operation'])
                ou = get_ou_model().objects.get_by_natural_key_json(
                    perm['ou']) if perm['ou'] else None
                ct = ContentType.objects.get_by_natural_key_json(
                    perm['target_ct'])
                target = ct.model_class().objects.get_by_natural_key_json(
                    perm['target'])
                perm = get_permission_model().objects.create(
                    operation=op, ou=ou, target_ct=ct, target_id=target.pk)
                self._obj.permissions.add(perm)
                created.append(perm)

        return created, deleted
示例#34
0
    def setUp(self):
        User = get_user_model()
        Role = get_role_model()
        OU = get_ou_model()

        ct_user = ContentType.objects.get_for_model(User)

        self.ou = OU.objects.create(slug='ou', name='OU', email_is_unique=True,
                                    username_is_unique=True)
        self.reguser1 = User.objects.create(username='******')
        self.reguser1.set_password('password')
        self.reguser1.save()
        cred = '%s:%s' % (self.reguser1.username.encode('utf-8'), 'password')
        self.reguser1_cred = base64.b64encode(cred)
        self.user_admin_role = Role.objects.get_admin_role(
            instance=ct_user, name='user admin', slug='user-admin')
        self.reguser1.roles.add(self.user_admin_role)

        self.reguser2 = User.objects.create(username='******',
                                            password='******')
        self.reguser2.set_password('password')
        self.reguser2.save()
        cred = '%s:%s' % (self.reguser2.username.encode('utf-8'), 'password')
        self.reguser2_cred = base64.b64encode(cred)
        self.ou_user_admin_role = Role.objects.get_admin_role(
            instance=ct_user, name='user admin', slug='user-admin',
            ou=self.ou)
        self.ou_user_admin_role.members.add(self.reguser2)

        self.reguser3 = User.objects.create(username='******',
                                            password='******',
                                            is_superuser=True)
        self.reguser3.set_password('password')
        self.reguser3.save()
        cred = '%s:%s' % (self.reguser3.username.encode('utf-8'), 'password')
        self.reguser3_cred = base64.b64encode(cred)
示例#35
0
def create_authentic_user():
    User = get_user_model()
    OU = get_ou_model()
    Role = get_role_model()
    organisation_unit = OU.objects.get(default=True)
    with provisionning:
        # create default role in ts2.
        try:
            role_agent_fabriques = Role.objects.get(
                name='Agent ayant acces aux fabriques')
        except ObjectDoesNotExist:
            role_agent_fabriques = Role(name='Agent ayant acces aux fabriques',
                                        ou=organisation_unit)
            role_agent_fabriques.save()

        try:
            role_agent_traitant_pop = Role.objects.get(
                name='Agents traitants - Population, etat civil')
        except ObjectDoesNotExist:
            role_agent_traitant_pop = Role(
                name='Agents traitants - Population, etat civil',
                ou=organisation_unit)
            role_agent_traitant_pop.save()

        try:
            role_agent_traitant_trav = Role.objects.get(
                name='Agents traitants - Travaux')
        except ObjectDoesNotExist:
            role_agent_traitant_trav = Role(name='Agents traitants - Travaux',
                                            ou=organisation_unit)
            role_agent_traitant_trav.save()

        try:
            role_citoyen_test = Role.objects.get(name='Citoyen (test)')
        except ObjectDoesNotExist:
            role_citoyen_test = Role(name='Citoyen (test)',
                                     ou=organisation_unit)
            role_citoyen_test.save()

        try:
            role_debug = Role.objects.get(name='Debug')
        except ObjectDoesNotExist:
            role_debug = Role(name='Debug', ou=organisation_unit)
            role_debug.save()

        with open("/tmp/tmp_uuid_agent_fabriques.txt", 'w') as f:
            f.write(role_agent_fabriques.uuid)
            f.close()

        with open("/tmp/tmp_uuid_agent_traitant_pop.txt", 'w') as f:
            f.write(role_agent_traitant_pop.uuid)
            f.close()

        with open("/tmp/tmp_uuid_agent_traitant_trav.txt", 'w') as f:
            f.write(role_agent_traitant_trav.uuid)
            f.close()

        with open("/tmp/tmp_uuid_citoyen_test.txt", 'w') as f:
            f.write(role_citoyen_test.uuid)
            f.close()

        with open("/tmp/tmp_uuid_debug.txt", 'w') as f:
            f.write(role_debug.uuid)
            f.close()

        user_admin = User.objects.get(username='******')
        role_debug.members.add(user_admin)
示例#36
0
 def __init__(self, *args, **kwargs):
     super(HideOUFieldMixin, self).__init__(*args, **kwargs)
     OU = get_ou_model()
     if OU.objects.count() < 2:
         del self.fields['ou']
示例#37
0
def update_rbac_on_ou_post_delete(sender, instance, **kwargs):
    from .management import update_ou_admin_roles, update_ous_admin_roles, \
        update_content_types_roles
    if get_ou_model().objects.count() < 2:
        update_ous_admin_roles()
示例#38
0
 def get_table(self, **kwargs):
     OU = get_ou_model()
     if OU.objects.count() < 2:
         kwargs['exclude'] = ['ou']
     return super(HideOUColumnMixin, self).get_table(**kwargs)
示例#39
0
def test_api_users_create_email_is_unique(settings, app, superuser):
    from django.contrib.auth import get_user_model

    User = get_user_model()
    OU = get_ou_model()
    ou1 = OU.objects.create(name='OU1', slug='ou1')
    ou2 = OU.objects.create(name='OU2', slug='ou2', email_is_unique=True)

    app.authorization = ('Basic', (superuser.username, superuser.username))
    # test missing first_name
    payload = {
        'ou': 'ou1',
        'first_name': 'John',
        'last_name': 'Doe',
        'email': '*****@*****.**',
    }

    assert User.objects.filter(ou=ou1).count() == 0
    assert User.objects.filter(ou=ou2).count() == 0

    app.post_json('/api/users/', params=payload)
    assert User.objects.filter(ou=ou1).count() == 1

    app.post_json('/api/users/', params=payload)
    assert User.objects.filter(ou=ou1).count() == 2

    payload['ou'] = 'ou2'
    app.post_json('/api/users/', params=payload)
    assert User.objects.filter(ou=ou2).count() == 1

    resp = app.post_json('/api/users/', params=payload, status=400)
    assert User.objects.filter(ou=ou2).count() == 1
    assert resp.json['result'] == 0
    assert resp.json['errors']['email']

    settings.A2_EMAIL_IS_UNIQUE = True
    User.objects.filter(ou=ou1).delete()
    assert User.objects.filter(ou=ou1).count() == 0
    payload['ou'] = 'ou1'
    app.post_json('/api/users/', params=payload, status=400)
    assert User.objects.filter(ou=ou1).count() == 0
    assert resp.json['result'] == 0
    assert resp.json['errors']['email']

    payload['email'] = '*****@*****.**'
    resp = app.post_json('/api/users/', params=payload)
    uuid = resp.json['uuid']

    app.patch_json('/api/users/%s/' % uuid, params={'email': '*****@*****.**'})
    resp = app.patch_json('/api/users/%s/' % uuid, params={'email': '*****@*****.**'},
                          status=400)
    assert resp.json['result'] == 0
    assert resp.json['errors']['email']
    settings.A2_EMAIL_IS_UNIQUE = False

    payload['ou'] = 'ou2'
    payload['email'] = '*****@*****.**'
    resp = app.post_json('/api/users/', params=payload)
    assert User.objects.filter(ou=ou2).count() == 2
    uuid = resp.json['uuid']
    resp = app.patch_json('/api/users/%s/' % uuid, params={'email': '*****@*****.**'},
                          status=400)
    assert resp.json['result'] == 0
    assert resp.json['errors']['email']
示例#40
0
# -*- coding: utf-8 -*-
import re

from django.contrib.auth import get_user_model
from django_rbac.utils import get_role_model, get_ou_model
from django_rbac.models import VIEW_OP
from django.test import Client
from django.core import mail

from lxml import html

from authentic2.tests import Authentic2TestCase as TestCase, get_response_form

User = get_user_model()
Role = get_role_model()
OU = get_ou_model()


class ManagerRBACTestCase(TestCase):
    def setUp(self):
        self.ou1 = OU.objects.create(name="ou1")
        self.ou2 = OU.objects.create(name="ou2")
        self.ou1_u1 = User.objects.create(username="******", ou=self.ou1)
        self.ou1_u1.set_password("u1")
        self.ou1_u1.save()
        self.ou1_u2 = User.objects.create(username="******", ou=self.ou1)
        self.ou1_u2.set_password("u2")
        self.ou1_u2.save()
        self.ou2_u1 = User.objects.create(username="******", ou=self.ou2)
        self.ou2_u1.set_password("u1")
        self.ou2_u1.save()