Esempio n. 1
0
def get_user_role(user, class_item):
    if 'change_class' in get_user_perms(user, class_item):
        return 'Teacher'
    elif 'view_class' in get_user_perms(user, class_item):
        return 'Student'
    else:
        return 'Pending'
 def test_direct_perms_only(self):
     admin = User.objects.create(username='******', is_superuser=True)
     self.user1.groups.add(self.group1)
     self.user2.groups.add(self.group1)
     assign_perm("change_contenttype", self.user1, self.obj1)
     assign_perm("delete_contenttype", admin, self.obj1)
     assign_perm("delete_contenttype", self.group1, self.obj1)
     expected = set([self.user1, self.user2, admin])
     result = get_users_with_perms(self.obj1, with_superusers=False, with_group_users=True)
     self.assertEqual(set(result), expected)
     self.assertEqual(set(get_user_perms(self.user1, self.obj1)), set(['change_contenttype']))
     self.assertEqual(set(get_user_perms(self.user2, self.obj1)), set([]))
     self.assertEqual(set(get_user_perms(admin, self.obj1)), set(['delete_contenttype']))
     result = get_users_with_perms(self.obj1, with_superusers=False, with_group_users=False)
     expected = set([self.user1, admin])
     self.assertEqual(set(result), expected)
     self.assertEqual(set(get_group_perms(self.user1, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_group_perms(self.user2, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_group_perms(self.group1, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_group_perms(self.group2, self.obj1)), set([]))
     self.assertEqual(set(get_group_perms(admin, self.obj1)), set([]))
     self.assertEqual(set(get_perms(admin, self.obj1)), set(['add_contenttype', 'change_contenttype', 'delete_contenttype']))
     self.assertEqual(set(get_perms(self.user1, self.obj1)), set(['change_contenttype', 'delete_contenttype']))
     self.assertEqual(set(get_perms(self.user2, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_perms(self.group1, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_perms(self.group2, self.obj1)), set([]))
 def test_direct_perms_only(self):
     admin = User.objects.create(username='******', is_superuser=True)
     self.user1.groups.add(self.group1)
     self.user2.groups.add(self.group1)
     assign_perm("change_contenttype", self.user1, self.obj1)
     assign_perm("delete_contenttype", admin, self.obj1)
     assign_perm("delete_contenttype", self.group1, self.obj1)
     expected = set([self.user1, self.user2, admin])
     result = get_users_with_perms(self.obj1, with_superusers=False, with_group_users=True)
     self.assertEqual(set(result), expected)
     self.assertEqual(set(get_user_perms(self.user1, self.obj1)), set(['change_contenttype']))
     self.assertEqual(set(get_user_perms(self.user2, self.obj1)), set([]))
     self.assertEqual(set(get_user_perms(admin, self.obj1)), set(['delete_contenttype']))
     result = get_users_with_perms(self.obj1, with_superusers=False, with_group_users=False)
     expected = set([self.user1, admin])
     self.assertEqual(set(result), expected)
     self.assertEqual(set(get_group_perms(self.user1, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_group_perms(self.user2, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_group_perms(self.group1, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_group_perms(self.group2, self.obj1)), set([]))
     self.assertEqual(set(get_group_perms(admin, self.obj1)), set([]))
     self.assertEqual(set(get_perms(admin, self.obj1)), set(['add_contenttype', 'change_contenttype', 'delete_contenttype']))
     self.assertEqual(set(get_perms(self.user1, self.obj1)), set(['change_contenttype', 'delete_contenttype']))
     self.assertEqual(set(get_perms(self.user2, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_perms(self.group1, self.obj1)), set(['delete_contenttype']))
     self.assertEqual(set(get_perms(self.group2, self.obj1)), set([]))
Esempio n. 4
0
 def dispatch(self, request, *args, **kwargs):
     allPCAs = pcaModel.objects.all()
     for pcaObject in allPCAs:
         perm = get_user_perms(request.user, pcaObject)
         if 'has_pca_control' in perm:
             pcaObject.permissionTimestamp = timezone.now()
             pcaObject.save()
     ecsObject = ecsModel.objects.filter(id="ecs").get()
     perm = get_user_perms(request.user, ecsObject)
     if 'has_ecs_control' in perm:
         ecsObject.permissionTimestamp = timezone.now()
         ecsObject.save()
     return super().dispatch(request, *args, **kwargs)
Esempio n. 5
0
def change_permission_owner(self):
    owner_permissions = ['view_expressionstudy', 'change_expressionstudy', 'delete_expressionstudy']

    if self.initial_owner:
        # If update, remove permission, else do nothing
        if self.initial_owner != self.created_by:
            initial_owner_permission = get_user_perms(self.initial_owner, self)
            for permission in owner_permissions:
                if permission in initial_owner_permission:
                    remove_perm(permission, self.initial_owner, self)

    user_permissions = get_user_perms(self.created_by, self)
    for permission in owner_permissions:
        if permission not in user_permissions:
            assign_perm(permission, self.created_by, self)
Esempio n. 6
0
def empty_user_auth(user, projects, add_perm_list):
    for perm in add_perm_list:
        remove_perm(perm, user)
    for project in projects:
        perms = get_user_perms(user, project)
        for perm in perms:
            remove_perm(perm, user, project)
Esempio n. 7
0
def create_class_view(request, username):

    if request.method == 'POST':
        form = forms.CreateClassForm(request.POST)

        if form.is_valid():
            class_item = form.save(commit=False)
            class_item.save()

            request.user.myclass.add(class_item)

            #user permissions for class creator
            teacher_perms = ['delete_class', 'change_class', 'view_class']
            update_class_perm(class_item,
                              request.user,
                              teacher_perms,
                              action="assign")

            #permissions are:
            print(get_user_perms(request.user, class_item))

            return redirect('dashboard', username)

    else:
        form = forms.CreateClassForm()

    context = {"form": form}
    return render(request, 'class_form.html', context)
Esempio n. 8
0
    def obj_perms_manage_user_view(self, request, **kwargs):
        """
        Manages selected users' permissions for current object.
        """
        current_app = self.admin_site.name

        if not self.has_change_permission():
            post_url = reverse('xadmin:index', current_app=current_app)
            return redirect(post_url)

        user = get_object_or_404(User, pk=self.user_id)
        obj = get_object_or_404(self.get_queryset(), pk=self.object_pk)
        form_class = self.get_obj_perms_manage_user_form(request)
        form = form_class(user, obj, request.POST or None)

        if request.method == 'POST' and form.is_valid():
            form.save_obj_perms()
            msg = ugettext("Permissions saved.")
            messages.success(request, msg)
            url = reverse(
                '{0.admin_site.name}:guardian_permissions_user'.format(self),
                args=[self.app_label, self.model_name, obj.pk, self.user_id]
            )
            return redirect(url)

        context = self.get_obj_perms_base_context(request, obj)

        context['user_perms'] = get_user_perms(user, obj)
        context['user_obj'] = user
        context['form'] = form

        request.current_app = current_app

        return render(request, self.get_obj_perms_manage_user_template(), context)
Esempio n. 9
0
    def get_context_data(self, **kwargs):
        context = super(GgvUserView, self).get_context_data(**kwargs)
        context['ggvuser'] = GGVUser.objects.get(user=self.get_object())
        context['ggvroles'] = get_user_perms(self.get_object(),
                                             context['course'])

        return context
Esempio n. 10
0
    def obj_perms_manage_user_view(self, request, object_pk, user_id):
        """
        Manages selected users' permissions for current object.
        """
        if not self.has_change_permission(request, None):
            post_url = reverse('admin:index', current_app=self.admin_site.name)
            return redirect(post_url)

        user = get_object_or_404(get_user_model(), pk=user_id)
        obj = get_object_or_404(self.get_queryset(request), pk=object_pk)
        form_class = self.get_obj_perms_manage_user_form(request)
        form = form_class(user, obj, request.POST or None)

        if request.method == 'POST' and form.is_valid():
            form.save_obj_perms()
            msg = gettext("Permissions saved.")
            messages.success(request, msg)
            info = (
                self.admin_site.name,
                self.model._meta.app_label,
                self.model._meta.model_name,
            )
            url = reverse('%s:%s_%s_permissions_manage_user' % info,
                          args=[obj.pk, user.pk])
            return redirect(url)

        context = self.get_obj_perms_base_context(request, obj)
        context['user_obj'] = user
        context['user_perms'] = get_user_perms(user, obj)
        context['form'] = form

        request.current_app = self.admin_site.name

        return render(request, self.get_obj_perms_manage_user_template(),
                      context)
Esempio n. 11
0
    def get(self, request):
        nodegroup_ids = JSONDeserializer().deserialize(
            request.GET.get('nodegroupIds'))
        identityId = request.GET.get('identityId')
        identityType = request.GET.get('identityType')

        ret = []
        if identityType == 'group':
            identity = Group.objects.get(pk=identityId)
            for nodegroup_id in nodegroup_ids:
                nodegroup = models.NodeGroup.objects.get(pk=nodegroup_id)
                perms = [{
                    'codename': codename,
                    'name': self.get_perm_name(codename).name
                } for codename in get_group_perms(identity, nodegroup)]
                ret.append({'perms': perms, 'nodegroup_id': nodegroup_id})
        else:
            identity = User.objects.get(pk=identityId)
            for nodegroup_id in nodegroup_ids:
                nodegroup = models.NodeGroup.objects.get(pk=nodegroup_id)
                perms = [{
                    'codename': codename,
                    'name': self.get_perm_name(codename).name
                } for codename in get_user_perms(identity, nodegroup)]

                # only get the group perms ("defaults") if no user defined object settings have been saved
                if len(perms) == 0:
                    perms = [{
                        'codename': codename,
                        'name': self.get_perm_name(codename).name
                    } for codename in set(get_group_perms(identity, nodegroup))
                             ]
                ret.append({'perms': perms, 'nodegroup_id': nodegroup_id})

        return JSONResponse(ret)
Esempio n. 12
0
 def get_list_of_users(self, element):
     users_dict = {}  # user_id: permissions
     # Transform get_users_with_perms(element, attach_perms=True) queryset to a dict user id and  perms
     userPermsQS = get_users_with_perms(element, attach_perms=True)
     for user in userPermsQS:
         listOfPerms = list(get_user_perms(user, element))
         users_dict[user.id] = listOfPerms
     return users_dict
Esempio n. 13
0
 def get_perms(self, identity, type, obj, perms):
     if type == "user":
         identity_perms = get_user_perms(identity, obj)
     else:
         identity_perms = get_group_perms(identity, obj)
     res = []
     for perm in identity_perms:
         res += list(filter(lambda x: (x["codename"] == perm), perms))
     return res
Esempio n. 14
0
    def wrap(request, *args, **kwargs):
        class_item = models.Class.objects.get(id=kwargs['pk'])
        print(class_item.user.all())

        if class_item.user.all().filter(
                username=request.user.username).exists():
            if 'view_class' in get_user_perms(request.user, class_item):
                return function(request, *args, **kwargs)
        return HttpResponse('Unauthorized', status=401)
Esempio n. 15
0
 def getHtmlDetails(self):
     user = manager.helpers.functions.get_user()
     ret = ''.join([
         '<li>Object ID: %d</li>' % self.id,
         '<li>Owner: %s</li>' % self.owner,
         '<li>Permissions: %s</li>' %
         ', '.join([x for x in get_user_perms(user, self)]),
         '<li>Date: %s</li>' % self.date.strftime("%Y-%m-%d"),
     ])
     return ret
Esempio n. 16
0
    def assign_object_permissions(cls, user_id: UUID, object_id: UUID,
                                  object_type_id, permission_ids: List[int]):
        user = get_user_model().objects.get(pk=user_id)
        content_type = ContentType.objects.get_for_id(object_type_id)
        content_type_model = content_type.model_class()
        model_instance = content_type_model.objects.get(pk=object_id)

        for permission_id in permission_ids:
            permission = Permission.objects.get(pk=permission_id)
            assign_perm(permission.codename, user, model_instance)

        return get_user_perms(user, model_instance)
Esempio n. 17
0
 def getHtmlDetails(self):
     user = manager.helpers.functions.get_user()
     ret = ''.join([
         '<li>Object ID: %d</li>' % self.id,
         '<li>Permissions: %s</li>' %
         ', '.join([x for x in get_user_perms(user, self)]),
         '<li>Owner: %s</li>' % self.owner,
         '<li>Date: %s</li>' % self.date.strftime("%Y-%m-%d %H:%M"),
         '<li>Method: %s</li>' % self.method_display_name,
         '<li>Dataset: <a href="%s">%s</a></li>' %
         (self.dataset.getUrl(), self.dataset),
     ])
     return ret
Esempio n. 18
0
    def get(self, request):
        if self.action == 'get_permission_manager_data':
            identities = []
            for group in Group.objects.all():
                identities.append({
                    'name': group.name,
                    'type': 'group',
                    'id': group.pk,
                    'default_permissions': group.permissions.all()
                })
            for user in User.objects.filter(is_superuser=False):
                groups = []
                default_perms = []
                for group in user.groups.all():
                    groups.append(group.name)
                    default_perms = default_perms + list(group.permissions.all())
                identities.append({'name': user.email or user.username, 'groups': ', '.join(groups),
                                   'type': 'user', 'id': user.pk, 'default_permissions': set(default_perms)})

            content_type = ContentType.objects.get_for_model(models.NodeGroup)
            nodegroup_permissions = Permission.objects.filter(content_type=content_type)
            ret = {'identities': identities, 'permissions': nodegroup_permissions}
            return JSONResponse(ret)

        nodegroup_ids = JSONDeserializer().deserialize(request.GET.get('nodegroupIds'))
        identityId = request.GET.get('identityId')
        identityType = request.GET.get('identityType')

        ret = []
        if identityType == 'group':
            identity = Group.objects.get(pk=identityId)
            for nodegroup_id in nodegroup_ids:
                nodegroup = models.NodeGroup.objects.get(pk=nodegroup_id)
                perms = [{'codename': codename, 'name': self.get_perm_name(
                    codename).name} for codename in get_group_perms(identity, nodegroup)]
                ret.append({'perms': perms, 'nodegroup_id': nodegroup_id})
        else:
            identity = User.objects.get(pk=identityId)
            for nodegroup_id in nodegroup_ids:
                nodegroup = models.NodeGroup.objects.get(pk=nodegroup_id)
                perms = [{'codename': codename, 'name': self.get_perm_name(
                    codename).name} for codename in get_user_perms(identity, nodegroup)]

                # only get the group perms ("defaults") if no user defined object settings have been saved
                if len(perms) == 0:
                    perms = [{'codename': codename, 'name': self.get_perm_name(
                        codename).name} for codename in set(get_group_perms(identity, nodegroup))]
                ret.append({'perms': perms, 'nodegroup_id': nodegroup_id})

        return JSONResponse(ret)
Esempio n. 19
0
 def getHtmlDetails(self):
     user = manager.helpers.functions.get_user()
     fs = self.fileset_set.all()[0]
     ret = ''.join([
         '<li>Object ID: %d</li>' % self.id,
         '<li>Permissions: %s</li>' %
         ', '.join([x for x in get_user_perms(user, self)]),
         '<li>Owner: %s</li>' % self.owner,
         '<li>Date: %s</li>' % self.date.strftime("%Y-%m-%d"),
         '<li>File date: %s</li>' % self.file_date,
         '<li>Filename: %s</li>' % self.filename,
         '<li>Fileset: <a href="%s">%s</a></li>' % (fs.getUrl(), fs.name)
     ])
     return ret
Esempio n. 20
0
    def dispatch(self, request, *args, **kwargs):
        try:
            self.course = Course.objects.get(slug=kwargs['crs_slug'])
            self.ggvuser = GGVUser.objects.get(user=self.get_object())
            self.permissions = get_perms(self.get_object(), self.course)
            if not self.permissions:
                # Needed to handle state when user has never logged in. (correct registration information)
                self.permissions = get_user_perms(self.get_object(), self.course)
            self.permissions = self.permissions[0]

        except:
            raise Http404(self.get_object().username + ' is not part of ' + self.course.title)

        return super(UpdateGgvUserAccountView, self).dispatch(request, *args, **kwargs)
Esempio n. 21
0
def join_class_view(request, username, pk=None):

    class_item = models.Class.objects.get(id=pk)

    if request.method == "GET":  #this should be a post

        qs = class_item.user.all().filter(username__iexact=username)

        if not qs.exists():
            user = User.objects.get(username=username)
            class_item.user.add(user)

            #permissions are:
            print(get_user_perms(request.user, class_item))

    return redirect('dashboard', username)
Esempio n. 22
0
def assign_tmpl_perms_user(request, perms, users, tmpl_inst):
    user = request.user
    biz = tmpl_inst.business

    if user.has_perm('manage_business', biz):
        # 删除有当前要授权权限的所有拥有用户的授权信息
        perm_users = get_users_with_perms(tmpl_inst)
        for name in perm_users:
            perm_list = get_user_perms(name, tmpl_inst)
            for perm in perm_list:
                if perm in perms:
                    remove_perm(perm, name, tmpl_inst)
        # then assign perms
        for perm, name in itertools.product(perms, users):
            assign_perm(perm, name, tmpl_inst)
    else:
        return HttpResponseForbidden()
Esempio n. 23
0
    def dispatch(self, request, *args, **kwargs):
        try:
            self.course = Course.objects.get(slug=kwargs['crs_slug'])
            self.ggvuser = GGVUser.objects.get(user=self.get_object())
            self.permissions = get_perms(self.get_object(), self.course)
            if not self.permissions:
                # Needed to handle state when user has never logged in. (correct registration information)
                self.permissions = get_user_perms(self.get_object(),
                                                  self.course)
            self.permissions = self.permissions[0]

        except:
            raise Http404(self.get_object().username + ' is not part of ' +
                          self.course.title)

        return super(UpdateGgvUserAccountView,
                     self).dispatch(request, *args, **kwargs)
Esempio n. 24
0
    def get_user_permissions(self, nodegroup=None):
        """
        get's a list of object level permissions allowed for a all users

        returns an object of the form:
        .. code-block:: python
            {
                'local':  {'codename': permssion codename, 'name': permission name} # A list of object level permissions
                'default': {'codename': permssion codename, 'name': permission name} # A list of group based object level permissions or model level permissions
            }

        Keyword Arguments:
        nodegroup -- the NodeGroup object instance to use to check for permissions on that particular object

        """

        ret = []
        for user in User.objects.all():
            perms = {
                'local': [{
                    'codename': codename,
                    'name': self.get_perm_name(codename).name
                } for codename in get_user_perms(user, nodegroup)],
                'default':
                set()
            }
            for group in user.groups.all():
                codenames = set(get_group_perms(group, nodegroup))
                if len(codenames) == 0:
                    codenames = set(
                        [item.codename for item in group.permissions.all()])
                perms['default'].update(codenames)
            perms['default'] = [{
                'codename': codename,
                'name': self.get_perm_name(codename).name
            } for codename in perms['default']]

            if len(perms['default']) > 0:
                ret.append({
                    'username': user.email or user.username,
                    'email': user.email,
                    'perms': perms,
                    'type': 'user',
                    'id': user.pk
                })
        return ret
Esempio n. 25
0
def set_member_perms(sender, instance=None, created=False, **kwargs):
    perms = get_perms_for_model(apps.get_model('app_mgr', 'Organization'))

    was_admin  = len(get_user_perms(instance.user, instance.org)) > 1

    if instance.is_admin and not was_admin:
        instance.org.admin_group.user_set.add(instance.user)
        for perm in perms:
            assign_perm(perm.codename, instance.user, instance.org)

    if not instance.is_admin and was_admin:
        instance.org.admin_group.user_set.remove(instance.user)
        for perm in perms:
            remove_perm(perm.codename, instance.user, instance.org)

    instance.org.member_group.user_set.add(instance.user)
    assign_perm('view_organization', instance.user, instance.org)
Esempio n. 26
0
def set_member_perms(sender, instance=None, created=False, **kwargs):
    perms = get_perms_for_model(apps.get_model('app_mgr', 'Organization'))

    was_admin = len(get_user_perms(instance.user, instance.org)) > 1

    if instance.is_admin and not was_admin:
        instance.org.admin_group.user_set.add(instance.user)
        for perm in perms:
            assign_perm(perm.codename, instance.user, instance.org)

    if not instance.is_admin and was_admin:
        instance.org.admin_group.user_set.remove(instance.user)
        for perm in perms:
            remove_perm(perm.codename, instance.user, instance.org)

    instance.org.member_group.user_set.add(instance.user)
    assign_perm('view_organization', instance.user, instance.org)
Esempio n. 27
0
 def delete(self, request, pk, format=None):
     """
     Delete subscription if user is owner or have permissions
     """
     try:
         sub = Subscription.objects.get(pk=pk)
         serializer = SubscriptionSerializer(sub)
         user_id = serializer.data['user']
         # If is staff and don't have delete permission, can't delete the subscription.
         if self.request.user.id == user_id or "can_delete_alarm" in get_user_perms(
                 self.request.user, sub):
             sub.delete()
             return Response(status=status.HTTP_204_NO_CONTENT)
         else:
             return Response(data={"detail": "Not Authorizated User"},
                             status=status.HTTP_403_FORBIDDEN)
     except Subscription.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
Esempio n. 28
0
def check_resource_instance_permissions(user, resourceid, permission):
    """
    Checks if a user has permission to access a resource instance

    Arguments:
    user -- the user to check
    resourceid -- the id of the resource
    permission -- the permission codename (e.g. 'view_resourceinstance') for which to check

    """
    result = {}
    try:
        resource = ResourceInstance.objects.get(resourceinstanceid=resourceid)
        result["resource"] = resource
        all_perms = get_perms(user, resource)
        if len(all_perms) == 0:  # no permissions assigned. permission implied
            result["permitted"] = "unknown"
            return result
        else:
            user_permissions = get_user_perms(user, resource)
            if "no_access_to_resourceinstance" in user_permissions:  # user is restricted
                result["permitted"] = False
                return result
            elif permission in user_permissions:  # user is permitted
                result["permitted"] = True
                return result

            group_permissions = get_group_perms(user, resource)
            if "no_access_to_resourceinstance" in group_permissions:  # group is restricted - no user override
                result["permitted"] = False
                return result
            elif permission in group_permissions:  # group is permitted - no user override
                result["permitted"] = True
                return result

            if permission not in all_perms:  # neither user nor group explicitly permits or restricts.
                result["permitted"] = False  # restriction implied
                return result

    except ObjectDoesNotExist:
        return None

    return result
Esempio n. 29
0
def no_save_subscription_if_dont_have_permissions(sender, instance, **kwargs):
    """
    Stop saving individual or group subscription if user or group don't have
    permissions to subscribe to the alarm
    :param sender: Subscription
    """
    user = instance.user if instance.user else None
    group = instance.group if instance.group else None

    if user:
        if 'can_subscribe' not in get_user_perms(user, instance.alarm):
            raise ValidationError(
                "User don't have permissions to subscribe to this alarm")
    elif group:
        if 'can_subscribe' not in get_group_perms(group, instance.alarm):
            raise ValidationError(
                "Group don't have permissions to subscribe to this alarm")
    else:
        raise ValidationError("BAD REQUEST. Check your selections.")
Esempio n. 30
0
    def obj_perms_manage_user_view(self, request, object_pk, user_id):
        """
        Manages selected users' permissions for current object.
        """
        if not self.has_change_permission(request, None):
            post_url = reverse('admin:index', current_app=self.admin_site.name)
            return redirect(post_url)

        user = get_object_or_404(get_user_model(), pk=user_id)
        obj = get_object_or_404(self.get_queryset(request), pk=object_pk)
        form_class = self.get_obj_perms_manage_user_form(request)
        form = form_class(user, obj, request.POST or None)

        if request.method == 'POST' and form.is_valid():
            form.save_obj_perms()
            msg = ugettext("Permissions saved.")
            messages.success(request, msg)
            info = (
                self.admin_site.name,
                self.model._meta.app_label,
                get_model_name(self.model)
            )
            url = reverse(
                '%s:%s_%s_permissions_manage_user' % info,
                args=[obj.pk, user.pk]
            )
            return redirect(url)

        context = self.get_obj_perms_base_context(request, obj)
        context['user_obj'] = user
        context['user_perms'] = get_user_perms(user, obj)
        context['form'] = form

        request.current_app = self.admin_site.name

        if django.VERSION >= (1, 10):
            return render(request, self.get_obj_perms_manage_user_template(), context)

        return render_to_response(self.get_obj_perms_manage_user_template(), context, RequestContext(request))
Esempio n. 31
0
        def inner_decorator(request, roles=roles, *args, **kwargs):
            p = Project.objects.get(pk=kwargs['project_id'])
            u = request.user

            has_role = check_user_role(u, p, roles)
            is_token_authenticated = getattr(request, '_is_token_authenticated', False)

            # If a request is authenticated through an API token permissions are
            # required, endpoints that require write/annotate permissions also
            # need to have the TokenAnnotate permission. This is enforced also
            # for admin accounts.
            if is_token_authenticated and not contains_read_roles(roles) and \
                    settings.REQUIRE_EXTRA_TOKEN_PERMISSIONS:
                has_role = 'can_annotate_with_token' in get_user_perms(u, p) or \
                        'can_annotate_with_token' in get_group_perms(u, p)

            if has_role:
                # The user can execute the function.
                return f(request, *args, **kwargs)
            else:
                msg = "User '{}' with ID {} does not have the required permissions in " \
                      "project {}".format(u.username, u.id, int(kwargs['project_id']))
                raise PermissionError(msg)
Esempio n. 32
0
def get_perms(request, biz_cc_id):
    template_id = request.GET.get('template_id')
    try:
        template = TaskTemplate.objects.get(pk=template_id,
                                            business__cc_id=biz_cc_id)
    except TaskTemplate.DoesNotExist:
        return HttpResponseForbidden()
    fill_params_groups = []
    execute_task_groups = []
    groups = get_groups_with_perms(template)
    # 获取有权限的分组列表
    for group in groups:
        perm_list = get_group_perms(group, template)
        for perm in perm_list:
            if perm == FILL_PARAMS_PERM_NAME:
                fill_params_groups.append(
                    {"show_name": group.name.split("\x00")[-1]})
            elif perm == EXECUTE_TASK_PERM_NAME:
                execute_task_groups.append(
                    {"show_name": group.name.split("\x00")[-1]})
    # 获取有权限的人员列表
    users = get_users_with_perms(template)
    for user in users:
        perm_list = get_user_perms(user, template)
        for perm in perm_list:
            if perm == FILL_PARAMS_PERM_NAME:
                fill_params_groups.append({"show_name": user.username})
            elif perm == EXECUTE_TASK_PERM_NAME:
                execute_task_groups.append({"show_name": user.username})
    ctx = {
        'result': True,
        'data': {
            'fill_params_groups': fill_params_groups,
            'execute_task_groups': execute_task_groups,
        }
    }
    return JsonResponse(ctx)
Esempio n. 33
0
def manage_user_permissions(request, id_chalkboard, id_user):
    chlk = get_object_or_404(Chalkboard, id=id_chalkboard)
    if check_permissions(request.user, chlk,
                         ['chalkboard_manage_permission_user']):
        user_join = get_object_or_404(JoinChalkboard,
                                      chalkboard=chlk,
                                      user_id=id_user)
        user = get_user_model().objects.get(id=id_user)
        permissions_rows = dict()
        permissions_user = dict()
        # get all permissions chalkboard
        for perm in get_perms_for_model(Chalkboard):
            permissions_rows[perm.codename] = perm.name
            permissions_user[perm.codename] = False  # default false permission
        for perm in get_user_perms(user, chlk):
            permissions_user[perm] = True
        form = PermissionForm(request.POST or None, checkboxs=permissions_user)
        if form.is_valid():
            permissions_datas = form.save()

            for codename, value in permissions_datas.items():
                has_perm = check_permissions(user, chlk, [codename])
                if value:
                    if not has_perm:
                        assign_permission(codename, user, chlk)
                else:
                    if has_perm:
                        remove_perm(codename, user, chlk)
            messages.success(request, 'Permissions saved.')
        return render(
            request, 'permissions/permissions_user_chalkboard.html', {
                'user_id': id_user,
                'chalkboard': chlk,
                'permissions_rows': permissions_rows,
                'form': form
            })
    return redirect('permission_chalkboard', id_chalkboard)
Esempio n. 34
0
    def test_set_permissions(self):
        normal_user = UserFactory(username="******")

        assign_perm("monitorings.manage_perm", self.user, self.monitoring)
        self.client.login(username="******", password="******")

        # First step - selecting user to set permissions to
        data = {
            "0-user": normal_user.pk,
            "permission_wizard-current_step": "0"
        }
        response = self.client.post(self.get_url(), data=data)
        self.assertEqual(response.status_code, 200)

        # Second step - updating user's permissions
        granted_permission = ["add_case", "add_draft", "add_letter"]
        data = {
            "1-permissions": granted_permission,
            "permission_wizard-current_step": "1",
        }
        response = self.client.post(self.get_url(), data=data)
        self.assertEqual(response.status_code, 302)
        self.assertCountEqual(get_user_perms(normal_user, self.monitoring),
                              granted_permission)
Esempio n. 35
0
 def get_context_data(self, **kwargs):
     context = super(GgvUserView, self).get_context_data(**kwargs)
     context['ggvuser'] = GGVUser.objects.get(user=self.get_object())
     context['ggvroles'] = get_user_perms(self.get_object(), context['course'])
     
     return context
Esempio n. 36
0
    def form_valid(self, form):
        self.object = form.save()

        # Need to force lower case emails.
        self.object.username = self.object.username.lower()
        self.object.save()

        username = form.cleaned_data['username']
        language = form.cleaned_data['language']
        course = form.cleaned_data['course']
        perms = form.cleaned_data['perms']
        prog_id = form.cleaned_data['program_id']
        is_active = form.cleaned_data['is_active']

        self.ggvuser.program_id = prog_id
        self.ggvuser.language_pref = language
        self.ggvuser.save()

        #get_user_perms
        curr_permissions = get_perms(self.object, self.course)
        if not curr_permissions:
            curr_permissions = get_user_perms(self.object, self.course)

        # Username changed?
        if not self.object.email == username:
            self.object.email = username
            self.object.save()
            try:
                social_auth_obj = self.object.social_auth.all()[0]
                social_auth_obj.uid = self.object.email
                social_auth_obj.save()
            except:
                pass

        if not self.object.is_active == is_active:
            self.object.is_active = is_active
            self.object.save()

        # Change the user's course?.
        if not self.course.id == course.id:

            for i in curr_permissions:
                assign_perm(i, self.object, course)
                remove_perm(i, self.object, self.course)

            # Change course_context for user's bookmarks
            bks = self.object.bookmarker.all().filter(course_context=self.course)
            for i in bks:
                try:
                    i.course_context = course
                    i.save()
                except IntegrityError as e:
                    i.delete()

            self.course = course



        # Change the user's permissions?
        if perms not in curr_permissions:
            for i in curr_permissions:
                remove_perm(i, self.object, self.course)

            assign_perm(perms, self.object, self.course)

        return super(UpdateGgvUserAccountView, self).form_valid(form)
Esempio n. 37
0
 def get_obj_perms_field_initial(self):
     perms = get_user_perms(self.user, self.obj)
     return perms
Esempio n. 38
0
    def get_user_permissions(self, nodegroup=None):
        """
        get's a list of object level permissions allowed for a all users

        returns an object of the form:
        .. code-block:: python
            {
                'local':  {'codename': permssion codename, 'name': permission name} # A list of object level permissions
                'default': {'codename': permssion codename, 'name': permission name} # A list of group based object level permissions or model level permissions
            }

        Keyword Arguments:
        nodegroup -- the NodeGroup object instance to use to check for permissions on that particular object

        """

        ret = []
        for user in User.objects.all():
            perms = {
                'local': [{'codename': codename, 'name': self.get_perm_name(codename).name} for codename in get_user_perms(user, nodegroup)],
                'default': set()
            }
            for group in user.groups.all():
                codenames = set(get_group_perms(group, nodegroup))
                if len(codenames) == 0:
                    codenames = set([item.codename for item in group.permissions.all()])
                perms['default'].update(codenames)
            perms['default'] = [{'codename': codename, 'name': self.get_perm_name(codename).name} for codename in perms['default']]

            if len(perms['default']) > 0:
                ret.append({'username': user.email or user.username, 'email': user.email, 'perms': perms, 'type': 'user', 'id': user.pk})
        return ret
Esempio n. 39
0
    def get(self, request):
        nodegroup_ids = JSONDeserializer().deserialize(request.GET.get('nodegroupIds'))
        identityId = request.GET.get('identityId')
        identityType = request.GET.get('identityType')

        ret = []
        if identityType == 'group':
            identity = Group.objects.get(pk=identityId)
            for nodegroup_id in nodegroup_ids:
                nodegroup = models.NodeGroup.objects.get(pk=nodegroup_id)
                perms = [{'codename': codename, 'name': self.get_perm_name(codename).name} for codename in get_group_perms(identity, nodegroup)]
                ret.append({'perms': perms, 'nodegroup_id': nodegroup_id})
        else:
            identity = User.objects.get(pk=identityId)
            for nodegroup_id in nodegroup_ids:
                nodegroup = models.NodeGroup.objects.get(pk=nodegroup_id)
                perms = [{'codename': codename, 'name': self.get_perm_name(codename).name} for codename in get_user_perms(identity, nodegroup)]

                # only get the group perms ("defaults") if no user defined object settings have been saved
                if len(perms) == 0:
                    perms = [{'codename': codename, 'name': self.get_perm_name(codename).name} for codename in set(get_group_perms(identity, nodegroup))]
                ret.append({'perms': perms, 'nodegroup_id': nodegroup_id})

        return JSONResponse(ret)