def search_role(role_d):
    Role = get_role_model()
    try:
        Role = get_role_model()
        return Role.objects.get_by_natural_key_json(role_d)
    except Role.DoesNotExist:
        return None
Beispiel #2
0
class RoleRemoveAdminUserView(views.TitleMixin, views.AjaxFormViewMixin,
                              SingleObjectMixin, views.PermissionMixin,
                              TemplateView):
    title = _('Remove admin user')
    model = get_role_model()
    success_url = '../..'
    template_name = 'authentic2/manager/role_remove_admin_user.html'
    permissions = ['a2_rbac.change_role']

    def dispatch(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.user = get_user_model().objects.get(pk=kwargs['user_pk'])
        return super(RoleRemoveAdminUserView,
                     self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        ctx = super(RoleRemoveAdminUserView, self).get_context_data(**kwargs)
        ctx['user'] = self.user
        return ctx

    def post(self, request, *args, **kwargs):
        self.object.get_admin_role().members.remove(self.user)
        hooks.call_hooks('event',
                         name='remove-remove-admin-role-user',
                         user=self.request.user,
                         role=self.object,
                         admin=self.user)
        return redirect(self.request, self.success_url)
Beispiel #3
0
class RoleRemoveParentView(views.AjaxFormViewMixin, SingleObjectMixin,
                           TemplateView):
    title = _('Remove parent role')
    model = get_role_model()
    success_url = '../..'
    template_name = 'authentic2/manager/role_remove_parent.html'

    def dispatch(self, request, *args, **kwargs):
        self.object = self.get_object()
        if self.object.is_internal():
            raise PermissionDenied
        self.parent = self.get_queryset().get(pk=kwargs['parent_pk'])
        return super(RoleRemoveParentView,
                     self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        ctx = super(RoleRemoveParentView, self).get_context_data(**kwargs)
        ctx['parent'] = self.parent
        return ctx

    def post(self, request, *args, **kwargs):
        if not self.request.user.has_perm('a2_rbac.change_role', self.parent):
            raise PermissionDenied
        self.object.remove_parent(self.parent)
        hooks.call_hooks('event',
                         name='manager-remove-child-role',
                         user=self.request.user,
                         parent=self.parent,
                         child=self.object)
        return redirect(self.request, self.success_url)
Beispiel #4
0
def test_all_members(db):
    User = get_user_model()
    u1 = User.objects.create(username='******')
    u2 = User.objects.create(username='******')
    u3 = User.objects.create(username='******')
    Role = utils.get_role_model()
    r1 = Role.objects.create(name='r1')
    r1.members.add(u1)
    r1.members.add(u3)
    r2 = Role.objects.create(name='r2')
    r2.members.add(u3)
    r3 = Role.objects.create(name='r3')
    r3.members.add(u2)
    r3.members.add(u3)
    r3.add_parent(r2)
    r2.add_parent(r1)
    for member in r1.all_members():
        if member == u1 or member == u3:
            assert member.direct == [r1]
        if member == u2:
            assert member.direct == []
    for member in Role.objects.filter(id=r1.id).all_members():
        if member == u1 or member == u3:
            assert member.direct == [r1]
        if member == u2:
            assert member.direct == []
Beispiel #5
0
class RoleAddParentView(views.AjaxFormViewMixin, views.TitleMixin,
                        SingleObjectMixin, FormView):
    title = _('Add parent role')
    model = get_role_model()
    form_class = forms.RolesForChangeForm
    success_url = '..'
    template_name = 'authentic2/manager/form.html'

    def dispatch(self, request, *args, **kwargs):
        self.object = self.get_object()
        if self.object.is_internal():
            raise PermissionDenied
        return super(RoleAddParentView, self).dispatch(request, *args,
                                                       **kwargs)

    def form_valid(self, form):
        child = self.get_object()
        for role in form.cleaned_data['roles']:
            child.add_parent(role)
            hooks.call_hooks('event',
                             name='manager-add-child-role',
                             user=self.request.user,
                             parent=role,
                             child=child)
        return super(RoleAddParentView, self).form_valid(form)
Beispiel #6
0
 class Meta:
     models = get_role_model()
     attrs = {'class': 'main', 'id': 'service-role-table'}
     fields = ('name', )
     empty_text = _(
         'No access restriction. All users are allowed to connect to this service.'
     )
Beispiel #7
0
def test_user_synchronization(app, simple_user):
    User = get_user_model()
    Role = get_role_model()

    headers = basic_authorization_header(simple_user)
    uuids = []
    for i in range(100):
        user = User.objects.create(first_name='ben', last_name='dauve')
        uuids.append(user.uuid)
    unknown_uuids = [uuid.uuid4().hex for i in range(100)]
    url = reverse('a2-api-users-synchronization')
    content = {
        'known_uuids': uuids + unknown_uuids,
    }
    random.shuffle(content['known_uuids'])
    response = app.post_json(url, params=content, headers=headers, status=403)

    # give custom_user.search_user permission to user
    r = Role.objects.get_admin_role(ContentType.objects.get_for_model(User),
                                    name='role',
                                    slug='role',
                                    operation=SEARCH_OP)

    r.members.add(simple_user)
    response = app.post_json(url, params=content, headers=headers)
    assert response.json['result'] == 1
    assert set(response.json['unknown_uuids']) == set(unknown_uuids)
Beispiel #8
0
def test_api_users_list_by_authorized_service(app, superuser):
    from authentic2.models import Service

    app.authorization = ('Basic', (superuser.username, superuser.username))
    User = get_user_model()
    Role = get_role_model()

    user1 = User.objects.create(username='******')
    user2 = User.objects.create(username='******')
    user3 = User.objects.create(username='******')

    role1 = Role.objects.create(name='role1')
    role2 = Role.objects.create(name='role2')
    role1.add_child(role2)
    user1.roles = [role1]
    user2.roles = [role2]

    service1 = Service.objects.create(ou=get_default_ou(), name='service1', slug='service1')
    service1.add_authorized_role(role1)

    service2 = Service.objects.create(ou=get_default_ou(), name='service2', slug='service2')

    resp = app.get('/api/users/')
    assert len(resp.json['results']) == 4

    resp = app.get('/api/users/?service-ou=default&service-slug=service1')
    assert len(resp.json['results']) == 2
    assert set(user['username'] for user in resp.json['results']) == set(['user1', 'user2'])

    resp = app.get('/api/users/?service-ou=default&service-slug=service2')
    assert len(resp.json['results']) == 4
Beispiel #9
0
class RoleRemoveChildView(views.AjaxFormViewMixin, SingleObjectMixin,
                          views.PermissionMixin, TemplateView):
    title = _('Remove child role')
    model = get_role_model()
    success_url = '../..'
    template_name = 'authentic2/manager/role_remove_child.html'
    permissions = ['a2_rbac.change_role']

    def dispatch(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.child = self.get_queryset().get(pk=kwargs['child_pk'])
        return super(RoleRemoveChildView,
                     self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        ctx = super(RoleRemoveChildView, self).get_context_data(**kwargs)
        ctx['child'] = self.child
        return ctx

    def post(self, request, *args, **kwargs):
        self.object.remove_child(self.child)
        hooks.call_hooks('event',
                         name='manager-remove-child-role',
                         user=self.request.user,
                         parent=self.object,
                         child=self.child)
        return redirect(self.request, self.success_url)
Beispiel #10
0
class ChooseRoleWidget(RoleLabelMixin, SecurityCheckMixin, ModelSelect2Widget):
    queryset = get_role_model().objects.exclude(slug__startswith='_')
    search_fields = [
        'name__icontains',
        'service__name__icontains',
        'ou__name__icontains',
    ]
Beispiel #11
0
def test_manager_site_import_error(app, db, superuser):
    site_import = login(app, superuser, '/manage/site-import/')
    form = site_import.form
    site_export = {
        'roles': [{
            "description": "",
            "service": None,
            "name": "basic",
            "attributes": [],
            "ou": {
                "slug": "unkown-ou",
                "uuid": "ba60d9e6c2874636883bdd604b23eab2",
                "name": "unkown ou"
            },
            "external_id": "",
            "slug": "basic",
            "uuid": "6eb7bbf64bf547119120f925f0e560ac"
        }]
    }
    form['site_json'] = Upload('site_export.json', json.dumps(site_export),
                               'application/octet-stream')
    res = form.submit()
    assert res.status_code == 200
    assert 'missing Organizational Unit' in res.text
    Role = get_role_model()
    with pytest.raises(Role.DoesNotExist):
        Role.objects.get(slug='basic')
Beispiel #12
0
def get_attributes(instance, ctx):
    user = ctx.get('user')
    User = get_user_model()
    if not user or not isinstance(user, User):
        return ctx
    for field in User._meta.fields:
        value = getattr(user, field.name)
        if value is None:
           continue
        ctx['django_user_' + str(field.name)] = getattr(user, field.name)
    for av in AttributeValue.objects.with_owner(user):
        ctx['django_user_' + str(av.attribute.name)] = av.to_python()
    ctx['django_user_groups'] = [group for group in user.groups.all()]
    ctx['django_user_group_names'] = [unicode(group) for group in user.groups.all()]
    if user.username:
        ctx['django_user_domain'] = user.username.rsplit('@', 1)[1] if '@' in user.username else ''
        ctx['django_user_identifier'] = user.username.rsplit('@', 1)[0] if '@' in user.username else ''
    Role = get_role_model()
    roles = Role.objects.for_user(user)
    ctx['a2_role_slugs'] = roles.values_list('slug', flat=True)
    ctx['a2_role_names'] = roles.values_list('name', flat=True)
    ctx['a2_role_uuids'] = roles.values_list('uuid', flat=True)
    if 'service' in ctx and getattr(ctx['service'], 'ou', None):
        ou = ctx['service'].ou
        ctx['a2_service_ou_role_slugs'] = roles.filter(ou=ou).values_list('slug', flat=True)
        ctx['a2_service_ou_role_names'] = roles.filter(ou=ou).values_list('name', flat=True)
        ctx['a2_service_ou_role_uuids'] = roles.filter(ou=ou).values_list('uuid', flat=True)
    return ctx
    def deserialize(self):
        ou_d = self._role_d['ou']
        has_ou = bool(ou_d)
        ou = None if not has_ou else search_ou(ou_d)
        if has_ou and not ou:
            raise DataImportError(
                "Can't import role because missing Organizational Unit : "
                "%s" % ou_d)

        kwargs = self._role_d.copy()
        del kwargs['ou']
        del kwargs['service']
        if has_ou:
            kwargs['ou'] = ou

        obj = search_role(self._role_d)
        if obj:  # Role already exist
            self._obj = obj
            status = 'updated'
            update_model(self._obj, kwargs)
        else:  # Create role
            self._obj = get_role_model().objects.create(**kwargs)
            status = 'created'

        # Ensure admin role is created.
        # Absoluteley necessary to create
        # parentings relationship later on,
        # since we don't deserialize technical role.
        self._obj.get_admin_role()
        return self._obj, status
Beispiel #14
0
 def setUp(self):
     User = get_user_model()
     Role = get_role_model()
     self.user = User.objects.create_user(self.LOGIN,
                                          password=self.PASSWORD,
                                          email=self.EMAIL,
                                          first_name=self.FIRST_NAME,
                                          last_name=self.LAST_NAME)
     self.service = Service.objects.create(
         name=self.NAME,
         slug=self.SLUG,
         urls=self.URL,
         identifier_attribute='django_user_username',
         ou=get_default_ou(),
         logout_url=self.URL + 'logout/')
     self.service_attribute1 = Attribute.objects.create(
         service=self.service,
         slug='email',
         attribute_name='django_user_email')
     self.service2 = Service.objects.create(
         name=self.NAME2,
         slug=self.SLUG2,
         urls=self.URL2,
         ou=get_default_ou(),
         identifier_attribute='django_user_email')
     self.service2_attribute1 = Attribute.objects.create(
         service=self.service2,
         slug='username',
         attribute_name='django_user_username')
     self.authorized_service = Role.objects.create(name='rogue',
                                                   ou=get_default_ou())
     self.factory = RequestFactory()
Beispiel #15
0
class ChooseRolesForChangeWidget(RoleLabelMixin, SecurityCheckMixin,
                                 ModelSelect2MultipleWidget):
    operations = ['change']
    queryset = get_role_model().objects.all()
    search_fields = [
        'name__icontains',
        'service__name__icontains',
        'ou__name__icontains',
    ]
Beispiel #16
0
class ChooseUserRoleWidget(RoleLabelMixin, SecurityCheckMixin,
                           ModelSelect2Widget):
    operations = ['change']
    model = get_role_model()
    search_fields = [
        'name__icontains',
        'service__name__icontains',
        'ou__name__icontains',
    ]
Beispiel #17
0
def test_role_members_show_all_ou(app, superuser, settings):
    Role = get_role_model()
    r = Role.objects.create(name='role', slug='role', ou=get_default_ou())
    url = reverse('a2-manager-role-members', kwargs={'pk': r.pk})
    response = login(app, superuser, url)
    assert not response.context['form'].fields['user'].queryset.query.where
    settings.A2_MANAGER_ROLE_MEMBERS_FROM_OU = True
    response = app.get(url)
    assert response.context['form'].fields['user'].queryset.query.where
Beispiel #18
0
def admin(db):
    user = create_user(username='******',
                       first_name='global',
                       last_name='admin',
                       email='*****@*****.**',
                       is_active=True,
                       ou=get_default_ou())
    Role = get_role_model()
    user.roles.add(Role.objects.get(slug='_a2-manager'))
    return user
Beispiel #19
0
def test_api_patch_role_unauthorized(app, simple_user, role_ou1):
    app.authorization = ('Basic', (simple_user.username, simple_user.username))
    Role = get_role_model()

    role_data = {
        'slug': 'updated-role',
    }
    app.patch_json('/api/roles/{}/'.format(role_ou1.uuid), params=role_data, status=404)
    role_ou1.refresh_from_db()
    assert role_ou1.slug == 'role_ou1'
    assert not len(Role.objects.filter(slug='updated-role'))
Beispiel #20
0
def test_api_post_role_unauthorized(app, simple_user, ou1):
    app.authorization = ('Basic', (simple_user.username, simple_user.username))
    Role = get_role_model()

    role_data = {
        'slug': 'mocca-manager',
        'name': 'Mocca Manager',
        'ou': 'ou1'
        }

    app.post_json('/api/roles/', params=role_data, status=403)
    assert not len(Role.objects.filter(slug='mocca-manager'))
Beispiel #21
0
def test_api_post_role_no_ou(app, superuser):
    app.authorization = ('Basic', (superuser.username, superuser.username))
    Role = get_role_model()

    role_data = {
        'slug': 'tea-manager',
        'name': 'Tea Manager',
        }
    resp = app.post_json('/api/roles/', params=role_data)
    uuid = resp.json['uuid']
    role = Role.objects.get(uuid=uuid)
    assert role.ou == get_default_ou()
Beispiel #22
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
Beispiel #23
0
def test_api_put_role_unauthorized(app, simple_user, role_ou1, ou1):
    app.authorization = ('Basic', (simple_user.username, simple_user.username))
    Role = get_role_model()

    role_data = {
        'name': 'updated-role',
        'slug': 'updated-role',
        'ou': 'ou2'
    }
    app.put_json('/api/roles/{}/'.format(role_ou1.uuid), params=role_data, status=404)
    role_ou1.refresh_from_db()
    assert role_ou1.name == 'role_ou1'
    assert role_ou1.slug == 'role_ou1'
    assert role_ou1.ou.slug == 'ou1'
Beispiel #24
0
    def handle(self, *args, **options):
        from django_rbac.utils import get_permission_model, get_role_model

        Permission = get_permission_model()
        count = Permission.objects.cleanup()
        if count:
            print 'Deleted %d permissions.' % count

        Role = get_role_model()

        count = 0
        count = Role.objects.cleanup()
        if count:
            print 'Deleted %d roles.' % count
def post_migrate_update_rbac(app_config, verbosity=2, interactive=True,
                             using=DEFAULT_DB_ALIAS, **kwargs):
    # be sure new objects names are localized using the default locale
    from .management import update_ou_admin_roles, update_ous_admin_roles, \
        update_content_types_roles


    if not router.allow_migrate(using, get_role_model()):
        return
    with override(settings.LANGUAGE_CODE):
        with transaction.atomic():
            with defer_update_transitive_closure():
                update_content_types_roles()
                update_ous_admin_roles()
Beispiel #26
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)
def test_import_site_cmd_unhandled_context_option(db, tmpdir, monkeypatch,
                                                  capsys):
    from authentic2.data_transfer import DataImportError

    export_file = tmpdir.join('roles-export.json')
    with export_file.open('w'):
        export_file.write(
            json.dumps({
                'roles': [{
                    'uuid': 'dqfewrvesvews2532',
                    'slug': 'role-slug',
                    'name': 'role-name',
                    'ou': None,
                    'service': None
                }]
            }))

    get_role_model().objects.create(uuid='dqfewrvesvews2532',
                                    slug='role-slug',
                                    name='role-name')

    with pytest.raises(DataImportError):
        management.call_command('import_site', '-o', 'role-delete-orphans',
                                export_file.strpath)
Beispiel #28
0
 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
def post_migrate_update_rbac(app_config,
                             verbosity=2,
                             interactive=True,
                             using=DEFAULT_DB_ALIAS,
                             **kwargs):
    # be sure new objects names are localized using the default locale
    from .management import update_ou_admin_roles, update_ous_admin_roles, \
        update_content_types_roles

    if not router.allow_migrate(using, get_role_model()):
        return
    with override(settings.LANGUAGE_CODE):
        with transaction.atomic():
            with defer_update_transitive_closure():
                update_content_types_roles()
                update_ous_admin_roles()
Beispiel #30
0
class RoleAddView(views.BaseAddView):
    template_name = 'authentic2/manager/role_add.html'
    model = get_role_model()
    title = _('Add role')
    success_view_name = 'a2-manager-role-members'

    def get_form_class(self):
        return forms.get_role_form_class()

    def form_valid(self, form):
        response = super(RoleAddView, self).form_valid(form)
        hooks.call_hooks('event',
                         name='manager-add-role',
                         user=self.request.user,
                         instance=form.instance,
                         form=form)
        return response
Beispiel #31
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
Beispiel #32
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)
Beispiel #33
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)
Beispiel #34
0
 def get_table_queryset(self):
     if self.is_ou_specified():
         roles = self.object.roles.all()
         User = get_user_model()
         Role = get_role_model()
         RoleParenting = get_role_parenting_model()
         rp_qs = RoleParenting.objects.filter(child=roles)
         qs = Role.objects.all()
         qs = qs.prefetch_related(models.Prefetch(
             'child_relation', queryset=rp_qs, to_attr='via'))
         qs = qs.prefetch_related(models.Prefetch(
             'members', queryset=User.objects.filter(pk=self.object.pk),
             to_attr='member'))
         qs2 = self.request.user.filter_by_perm('a2_rbac.change_role', qs)
         managable_ids = map(str, qs2.values_list('pk', flat=True))
         qs = qs.extra(select={'has_perm': 'a2_rbac_role.id in (%s)' % ', '.join(managable_ids)})
         return qs
     else:
         return self.object.roles_and_parents()
Beispiel #35
0
def update_ou_admin_roles(ou):
    Role = get_role_model()

    if app_settings.MANAGED_CONTENT_TYPES == ():
        Role.objects.filter(slug='a2-managers-of-{ou.slug}'.format(ou=ou)) \
            .delete()
    else:
        ou_admin_role = ou.get_admin_role()

    for key in MANAGED_CT:
        ct = ContentType.objects.get_by_natural_key(key[0], key[1])
        model_class = ct.model_class()
        ou_model = get_fk_model(model_class, 'ou')
        # do not create scoped admin roles if the model is not scopable
        if not ou_model:
            continue
        name = unicode(MANAGED_CT[key]['name'])
        slug = '_a2-' + slugify(name)
        scoped_name = unicode(MANAGED_CT[key]['scoped_name'])
        name = scoped_name.format(ou=ou)
        ou_slug = slug + '-' + ou.slug
        if app_settings.MANAGED_CONTENT_TYPES == ():
            Role.objects.filter(slug=ou_slug, ou=ou).delete()
            continue
        else:
            ou_ct_admin_role = Role.objects.get_admin_role(
                instance=ct,
                ou=ou,
                name=name,
                slug=ou_slug,
                update_slug=True,
                update_name=True)
        if not app_settings.MANAGED_CONTENT_TYPES or \
                key in app_settings.MANAGED_CONTENT_TYPES:
            ou_ct_admin_role.add_child(ou_admin_role)
        else:
            ou_ct_admin_role.remove_child(ou_admin_role)
        if MANAGED_CT[key].get('must_view_user'):
            ou_ct_admin_role.permissions.add(utils.get_view_user_perm(ou))
        ou_ct_admin_role.permissions.add(utils.get_view_ou_perm(ou))
Beispiel #36
0
def update_content_types_roles():
    '''Create general and scoped management roles for all managed content
       types.
    '''
    cts = ContentType.objects.all()
    Role = get_role_model()
    view_user_perm = utils.get_view_user_perm()
    view_ou_perm = utils.get_view_ou_perm()
    slug = '_a2-manager'
    if app_settings.MANAGED_CONTENT_TYPES == ():
        Role.objects.filter(slug=slug).delete()
    else:
        admin_role, created = Role.objects.get_or_create(
            slug=slug,
            defaults=dict(
                name=_('Manager')))
        admin_role.add_self_administration()
        if not created and admin_role.name != _('Manager'):
            admin_role.name = _('Manager')
            admin_role.save()

    for ct in cts:
        ct_tuple = (ct.app_label.lower(), ct.model.lower())
        if ct_tuple not in MANAGED_CT:
            continue
        # General admin role
        name = unicode(MANAGED_CT[ct_tuple]['name'])
        slug = '_a2-' + slugify(name)
        if app_settings.MANAGED_CONTENT_TYPES is not None and ct_tuple not in \
                app_settings.MANAGED_CONTENT_TYPES:
            Role.objects.filter(slug=slug).delete()
            continue
        ct_admin_role = Role.objects.get_admin_role(instance=ct, name=name,
                                                    slug=slug,
                                                    update_name=True)
        if MANAGED_CT[ct_tuple].get('must_view_user'):
            ct_admin_role.permissions.add(view_user_perm)
        ct_admin_role.permissions.add(view_ou_perm)
        ct_admin_role.add_child(admin_role)
def update_service_role_ou(sender, instance, created, raw, **kwargs):
    get_role_model().objects.filter(service=instance).update(ou=instance.ou)
Beispiel #38
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()