dump fields permissions for a user
508096
def handle(self, *args, **options):
        

        def get_user(username):
            try:
                return User.objects.get(username=username)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't exist in the database")

        def add_permissions(user_field_permissions, content_type, name):

            p = None
            try:
                p = FieldPermission.objects.get(content_type=content_type, name=name)
            except ObjectDoesNotExist:
                p = FieldPermission(content_type=content_type, name=name)
                p.save()
            finally:
                user_field_permissions.permissions.add(p)



        if len(args) !=1:
             raise CommandError("Specifies a json file created by the fine_permissions_dump command")
        else:
            try:


                with open(args[0], 'r') as json_file:
                    myjson = json.load(json_file)

                    user = get_user(options.get('user')) if options['user'] else get_user(myjson['username'])
                    fields_permissions = myjson['fields_permissions']

                    user_field_permissions = UserFieldPermissions(user=user)
                    user_field_permissions.save()

                    for f in fields_permissions:
                        content_type = ContentType.objects.get(app_label=f["app_label"], model=f["model"])
                        add_permissions(user_field_permissions, content_type, f['name'])


            except Exception as e:
                raise CommandError(e)
375462
void displayUserPermissions(CmsUser user) {

        CmsPermissionView view = buildPermissionEntryForm(user.getId(), buildPermissionsForCurrentUser(), false, false);
        view.hideDeniedColumn();
        m_userPermissions.addComponent(view);
    }
802882
def permissions(self, course_id, permissions=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # OPTIONAL - permissions
        """List of permissions to check against authenticated user"""
        if permissions is not None:
            params["permissions"] = permissions

        self.logger.debug("GET /api/v1/courses/{course_id}/permissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/permissions".format(**path), data=data, params=params, no_data=True)
1240798
def handle(self, *args, **options):
        

        def get_user(username):
            try:
                return User.objects.get(username=username)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't exist in the database")

        def get_fields_permissions(user):
            try:
                return UserFieldPermissions.objects.get(user=user)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't have fields permissions")



        if len(args) !=1:
            raise CommandError("Specifies a user")
        else:
            try:
                self.stdout.ending = None
                user = get_user(args[0])
                fields_permissions  = get_fields_permissions(user)
                permissions = fields_permissions.permissions.all()

                jsoneatthat = {'username': user.username, 
                    'fields_permissions' : [ {'app_label': permission.content_type.app_label, 'model' : permission.content_type.model, 'name': permission.name } for permission in permissions]}

                self.stdout.write(json.dumps(jsoneatthat))

            except:
                raise
1005011
def get_permissions(self):
        '''
        
        '''
        response = self.client.getHelper(self.url, acl='true')
        if response.status_code != 200:
            raise DataApiError('Unable to get permissions:' + str(response.content))
        content = response.json()
        if 'acl' in content:
            return Acl.from_acl_response(content['acl'])
        else:
            return None
424021
void savePermissions() {

        try {
            ensureLock();
            for (CmsPermissionBean bean : m_permissionToChange) {
                if (bean.isDeleted()) {
                    m_cms.rmacc(m_cms.getSitePath(m_resource), bean.getPrincipalType(), bean.getPrincipalName());

                } else {
                    if (bean.getPermissionString() == null) {
                        m_cms.chacc(
                            m_cms.getSitePath(m_resource),
                            bean.getPrincipalType(),
                            bean.getPrincipalName(),
                            bean.getAllowed(),
                            bean.getDenied(),
                            bean.getFlags());
                    } else {
                        m_cms.chacc(
                            m_cms.getSitePath(m_resource),
                            bean.getPrincipalType(),
                            bean.getPrincipalName(),
                            bean.getPermissionString());
                    }
                }
            }
        } catch (CmsException e) {
            m_context.error(e);
        }
    }
1308247
function(objects, user) {
    if (!_.isArray(objects)) {
      return PermissionService.isForeignObject(user.id)(objects);
    }
    return _.any(objects, PermissionService.isForeignObject(user.id));
  }
830034
def _get_user_allowed_fields(self):
        
        model_name = self.Meta.model.__name__.lower()
        app_label = self.Meta.model._meta.app_label
        full_model_name = '%s.%s' % (app_label, model_name)
        permissions = self.cached_allowed_fields.get(full_model_name)

        if not permissions:
            permissions = FieldPermission.objects.filter(
                user_field_permissions__user=self.user,
                content_type__model=model_name,
                content_type__app_label=app_label
            )
            self.cached_allowed_fields[full_model_name] = permissions
        return permissions
612511
def perms_for_user(cls, instance, user, db_session=None):
        
        db_session = get_db_session(db_session, instance)
        query = db_session.query(
            cls.models_proxy.GroupResourcePermission.group_id.label("owner_id"),
            cls.models_proxy.GroupResourcePermission.perm_name,
            sa.literal("group").label("type"),
        )
        query = query.filter(
            cls.models_proxy.GroupResourcePermission.group_id.in_(
                [gr.id for gr in user.groups]
            )
        )
        query = query.filter(
            cls.models_proxy.GroupResourcePermission.resource_id == instance.resource_id
        )

        query2 = db_session.query(
            cls.models_proxy.UserResourcePermission.user_id.label("owner_id"),
            cls.models_proxy.UserResourcePermission.perm_name,
            sa.literal("user").label("type"),
        )
        query2 = query2.filter(
            cls.models_proxy.UserResourcePermission.user_id == user.id
        )
        query2 = query2.filter(
            cls.models_proxy.UserResourcePermission.resource_id == instance.resource_id
        )
        query = query.union(query2)

        groups_dict = dict([(g.id, g) for g in user.groups])
        perms = [
            PermissionTuple(
                user,
                row.perm_name,
                row.type,
                groups_dict.get(row.owner_id) if row.type == "group" else None,
                instance,
                False,
                True,
            )
            for row in query
        ]

        # include all perms if user is the owner of this resource
        if instance.owner_user_id == user.id:
            perms.append(
                PermissionTuple(
                    user, ALL_PERMISSIONS, "user", None, instance, True, True
                )
            )
        groups_dict = dict([(g.id, g) for g in user.groups])
        if instance.owner_group_id in groups_dict:
            perms.append(
                PermissionTuple(
                    user,
                    ALL_PERMISSIONS,
                    "group",
                    groups_dict.get(instance.owner_group_id),
                    instance,
                    True,
                    True,
                )
            )

        return perms
1347708
def get_user_permissions(self, username):
        

        path = Client.urls['user_permissions'] % (username,)
        conns = self._call(path, 'GET')
        return conns
893014
def cli(obj, scopes):
    """"""
    client = obj['client']
    query = [('scopes', s) for s in scopes]

    if obj['output'] == 'json':
        r = client.http.get('/perms', query)
        click.echo(json.dumps(r['permissions'], sort_keys=True, indent=4, ensure_ascii=False))
    else:
        headers = {'id': 'ID', 'scopes': 'SCOPES', 'match': 'ROLE'}
        click.echo(tabulate([p.tabular() for p in client.get_perms(query)], headers=headers, tablefmt=obj['output']))
1014908
def perform_permissions_check(self, user, obj, perms):
        
        return self.request.forum_permission_handler.can_lock_topics(obj, user)
1166463
def handle(self, **options):
        """"""
        perm_map = {}
        with open('eighth_activity_permissions.csv', 'r') as absperms:
            perms = csv.reader(absperms)
            for row in perms:
                aid, uid = row
                try:
                    usr = User.objects.get(id=uid)
                except User.DoesNotExist:
                    self.stdout.write("User {} doesn't exist, aid {}".format(uid, aid))
                else:
                    if aid in perm_map:
                        perm_map[aid].append(usr)
                    else:
                        perm_map[aid] = [usr]

        for aid in perm_map:
            try:
                act = EighthActivity.objects.get(id=aid)
            except EighthActivity.DoesNotExist:
                self.stdout.write("Activity {} doesn't exist".format(aid))
            else:
                self.stdout.write("{}: {}".format(aid, EighthActivity.objects.get(id=aid)))
                grp, _ = Group.objects.get_or_create(name="{} -- Permissions".format("{}".format(act)[:55]))
                users = perm_map[aid]
                for u in users:
                    u.groups.add(grp)
                    u.save()
                act.groups_allowed.add(grp)
                act.save()

        self.stdout.write("Done.")
443633
def delete_user_permissions(self, user, perm, obj, check_groups=False):
        
        user_perms = self.user_permissions(user, perm, obj, check_groups=False)
        if not user_perms.filter(object_id=obj.id):
            return
        perms = self.user_permissions(user, perm, obj).filter(object_id=obj.id)
        perms.delete()
1063460
def get_group_permissions(self, user_obj, obj=None):
        
        if user_obj.is_anonymous() or obj is not None:
            return set()
        if not hasattr(user_obj, '_group_perm_cache'):
            if user_obj.is_superuser:
                perms = Permission.objects.all()
            else:
                user_groups_field = get_user_class()._meta.get_field('groups')  # pylint: disable=W0212
                user_groups_query = 'group__%s' % user_groups_field.related_query_name()
                perms = Permission.objects.filter(**{user_groups_query: user_obj})
            perms = perms.values_list('content_type__app_label', 'codename').order_by()
            user_obj._group_perm_cache = set(["%s.%s" % (ct, name) for ct, name in perms])  # pylint: disable=W0212
        return user_obj._group_perm_cache
900896
def report_to_list(queryset, display_fields, user):
    
    model_class = queryset.model
    objects = queryset
    message = ""

    if not _can_change_or_view(model_class, user):
        return [], 'Permission Denied'

    # Convert list of strings to DisplayField objects.
    new_display_fields = []

    for display_field in display_fields:
        field_list = display_field.split('__')
        field = field_list[-1]
        path = '__'.join(field_list[:-1])

        if path:
            path += '__'  # Legacy format to append a __ here.

        df = DisplayField(path, field)
        new_display_fields.append(df)

    display_fields = new_display_fields

    # Display Values
    display_field_paths = []

    for i, display_field in enumerate(display_fields):
        model = get_model_from_path_string(model_class, display_field.path)

        if not model or _can_change_or_view(model, user):
            display_field_key = display_field.path + display_field.field

            display_field_paths.append(display_field_key)

        else:
            message += 'Error: Permission denied on access to {0}.'.format(
                display_field.name
            )

    values_list = objects.values_list(*display_field_paths)
    values_and_properties_list = [list(row) for row in values_list]

    return values_and_properties_list, message
1370783
def _populate_permissions(resources, content_type_id):
    
    from django.contrib.auth.models import Permission
    # read the whole auth_permission table into memory
    db_perms = [perm.codename for perm in Permission.objects.all()]

    for resource in resources:
        # get all resource's permissions that are not already in db
        perms = [perm for perm in resource.access_controller.get_perm_names(resource) if perm not in db_perms]
        for perm in perms:
            _save_new_permission(perm, content_type_id)