Update permissions for some users.

    Give bulk-delete permissions to moderators.
    Give edit permission to moderators and editors in order
    to display 'Main' page in the explorer.
498962
def update_permissions_for_group(apps, schema_editor):
    '''
    
    '''
    db_alias = schema_editor.connection.alias
    try:
        # Django 1.9
        emit_post_migrate_signal(2, False, db_alias)
    except TypeError:
        # Django < 1.9
        try:
            # Django 1.8
            emit_post_migrate_signal(2, False, 'default', db_alias)
        except TypeError:  # Django < 1.8
            emit_post_migrate_signal([], 2, False, 'default', db_alias)

    Group = apps.get_model('auth.Group')
    Permission = apps.get_model('auth.Permission')
    GroupPagePermission = apps.get_model('wagtailcore.GroupPagePermission')
    SectionIndexPage = apps.get_model('core.SectionIndexPage')
    MainPage = apps.get_model('core.Main')

    moderator_group = Group.objects.filter(name='Moderators').first()
    editor_group = Group.objects.filter(name='Editors').first()

    if moderator_group:
        sections = SectionIndexPage.objects.first()
        GroupPagePermission.objects.get_or_create(
            group_id=moderator_group.id,
            page_id=sections.id,
            permission_type='bulk_delete'
        )

        main = MainPage.objects.first()
        GroupPagePermission.objects.get_or_create(
            group_id=moderator_group.id,
            page_id=main.id,
            permission_type='edit'
        )

    if editor_group:
        main = MainPage.objects.first()
        GroupPagePermission.objects.get_or_create(
            group_id=editor_group.id,
            page_id=main.id,
            permission_type='edit'
        )
270742
def fix_client_permissions(portal):
    
    wfs = get_workflows()

    start = time.time()
    clients = portal.clients.objectValues()
    total = len(clients)
    for num, client in enumerate(clients):
        logger.info("Fixing permission for client {}/{} ({})"
                    .format(num, total, client.getName()))
        update_role_mappings(client, wfs=wfs)
    end = time.time()
    logger.info("Fixing client permissions took %.2fs" % float(end-start))
    transaction.commit()
841637
public function updateModeratorForMany($newForums = [], $oldForums = [])
    {
        $transaction = static::getDb()->beginTransaction();
        try {
            $add = [];
            foreach ($newForums as $forum) {
                if (!in_array($forum, $oldForums, true) && (new Query)->from(Forum::tableName())->where(['id' => $forum])->exists()
                        && (new Query)->from(Mod::tableName())->where(['forum_id' => $forum, 'user_id' => $this->id])->exists() === false) {
                    $add[] = [$forum, $this->id];
                }
            }
            $remove = [];
            foreach ($oldForums as $forum) {
                if (!in_array($forum, $newForums, true) && (new Query)->from(Mod::tableName())->where(['forum_id' => $forum, 'user_id' => $this->id])->exists()) {
                    $remove[] = $forum;
                }
            }
            if (!empty($add) && !Podium::getInstance()->db->createCommand()->batchInsert(Mod::tableName(), ['forum_id', 'user_id'], $add)->execute()) {
                throw new Exception('Moderators adding error!');
            }
            if (!empty($remove) && !Podium::getInstance()->db->createCommand()->delete(Mod::tableName(), ['forum_id' => $remove, 'user_id' => $this->id])->execute()) {
                throw new Exception('Moderators deleting error!');
            }
            Podium::getInstance()->podiumCache->delete('forum.moderators');
            Log::info('Moderators updated', null, __METHOD__);
            $transaction->commit();
            return true;
        } catch (Exception $e) {
            $transaction->rollBack();
            Log::error($e->getMessage(), null, __METHOD__);
        }
        return false;
    }
888946
public function edit(User $user)
    {
        $roles = Role::all();
        $permissions = Permission::all();
        return view('chuckcms::backend.users.edit', compact('user', 'roles', 'permissions'));
    }
1057427
protected function updateUserRole()
    {
        $this->controlAccess('user_role_edit');

        if ($this->role->update($this->data_role['role_id'], $this->getSubmitted())) {
            $this->redirect('admin/user/role', $this->text('Role has been updated'), 'success');
        }

        $this->redirect('', $this->text('Role has not been updated'), 'warning');
    }
871762
def assign_contributor_permissions(obj, contributor=None):
    """"""
    for permission in get_all_perms(obj):
        assign_perm(permission, contributor if contributor else obj.contributor, obj)
449741
def security_cleanup(self, baseviews, menus):
        
        viewsmenus = self.get_all_view_menu()
        roles = self.get_all_roles()
        for viewmenu in viewsmenus:
            found = False
            for baseview in baseviews:
                if viewmenu.name == baseview.__class__.__name__:
                    found = True
                    break
            if menus.find(viewmenu.name):
                found = True
            if not found:
                permissions = self.find_permissions_view_menu(viewmenu)
                for permission in permissions:
                    for role in roles:
                        self.del_permission_role(role, permission)
                    self.del_permission_view_menu(
                        permission.permission.name, viewmenu.name
                    )
                self.del_view_menu(viewmenu.name)
357739
def add_view_permissions(sender, verbosity, **kwargs):
    
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.models import Permission

    for content_type in ContentType.objects.all():
        codename = "view_%s" % content_type.model

        _, created = Permission.objects \
            .get_or_create(content_type=content_type,
                           codename=codename,
                           defaults={'name': 'Can view %s' % content_type.name})
        if created and verbosity >= 1:
            print('Added view permission for %s' % content_type.name)
1313246
def add_permission(self, perm):
        
        self.Permissions(permission=perm)
        PermissionCache.flush()
        self.save()
262410
def can_edit(self, user=None, request=None):
        
        can = False
        if request and not self.owner:
            if (getattr(settings, "UMAP_ALLOW_ANONYMOUS", False)
                    and self.is_anonymous_owner(request)):
                can = True
        if self.edit_status == self.ANONYMOUS:
            can = True
        elif not user.is_authenticated:
            pass
        elif user == self.owner:
            can = True
        elif self.edit_status == self.EDITORS and user in self.editors.all():
            can = True
        return can
401817
def perform_permissions_check(self, user, obj, perms):
        
        return self.request.forum_permission_handler.can_delete_post(obj, user)
737731
def main():
    """"""
    mod_choices = ('banned', 'contributor', 'moderator')
    mod_choices_dsp = ', '.join(['`{}`'.format(x) for x in mod_choices])
    msg = {
        'add': ('Add users to one of the following categories: {}'
                .format(mod_choices_dsp)),
        'clear': 'Remove users who have no flair set.',
        'css': 'Ignore the CSS field when synchronizing flair.',
        'edit': 'When adding flair templates, mark them as editable.',
        'file': 'The file containing contents for --message',
        'flair': 'List flair for the subreddit.',
        'flair_stats': 'Display the number of users with each flair.',
        'json': 'Output the results as json. Applies to --flair',
        'limit': ('The minimum number of users that must have the specified '
                  'flair in order to add as a template. default: %default'),
        'list': ('List the users in one of the following categories: '
                 '{}. May be specified more than once.'
                 .format(mod_choices_dsp)),
        'msg': ('Send message to users of one of the following categories: '
                '{}. Message subject provided via --subject, content provided '
                'via --file or STDIN.').format(mod_choices_dsp),
        'sort': ('The order to add flair templates. Available options are '
                 '`alpha` to add alphabetically, and `size` to first add '
                 'flair that is shared by the most number of users. '
                 'default: %default'),
        'static': ('Add this template when syncing flair templates. When '
                   'syncing text and css use a comma to separate the two.'),
        'subject': 'The subject of the message to send for --message.',
        'sync': 'Synchronize flair templates with current user flair.',
        'text': 'Ignore the text field when synchronizing flair.'}

    usage = 'Usage: %prog [options] SUBREDDIT'
    parser = arg_parser(usage=usage)
    parser.add_option('-a', '--add', help=msg['add'])
    parser.add_option('-l', '--list', action='append', help=msg['list'],
                      choices=mod_choices, metavar='CATEGORY', default=[])
    parser.add_option('-c', '--clear-empty', action='store_true',
                      help=msg['clear'])
    parser.add_option('-F', '--file', help=msg['file'])
    parser.add_option('-f', '--flair', action='store_true', help=msg['flair'])
    parser.add_option('', '--flair-stats', action='store_true',
                      help=msg['flair_stats'])
    parser.add_option('-m', '--message', choices=mod_choices, help=msg['msg'])
    parser.add_option('', '--subject', help=msg['subject'])

    group = OptionGroup(parser, 'Format options')
    group.add_option('-j', '--json', action='store_true', help=msg['json'])
    parser.add_option_group(group)

    group = OptionGroup(parser, 'Sync options')
    group.add_option('', '--sync', action='store_true', help=msg['sync'])
    group.add_option('-s', '--static', action='append', help=msg['static'])
    group.add_option('', '--editable', action='store_true', help=msg['edit'])
    group.add_option('', '--ignore-css', action='store_true',
                     default=False, help=msg['css'])
    group.add_option('', '--ignore-text', action='store_true',
                     default=False, help=msg['text'])
    group.add_option('', '--limit', type='int', help=msg['limit'], default=2)
    group.add_option('', '--sort', action='store', choices=('alpha', 'size'),
                     default='alpha', help=msg['sort'])
    parser.add_option_group(group)

    options, args = parser.parse_args()
    if len(args) == 0:
        parser.error('Must provide subreddit name.')
    if options.message and not options.subject:
        parser.error('Must provide --subject when providing --message.')
    subreddit = args[0]

    check_for_updates(options)

    modutils = ModUtils(subreddit, options.site, options.verbose)

    if options.add:
        modutils.add_users(options.add)
    if options.clear_empty:
        modutils.clear_empty()
    for category in options.list:
        modutils.output_list(category)
    if options.flair:
        modutils.output_current_flair(as_json=options.json)
    if options.flair_stats:
        modutils.output_flair_stats()
    if options.sync:
        modutils.flair_template_sync(editable=options.editable,
                                     limit=options.limit,
                                     static=options.static, sort=options.sort,
                                     use_css=not options.ignore_css,
                                     use_text=not options.ignore_text)
    if options.message:
        modutils.message(options.message, options.subject, options.file)
588243
def set_content_permissions(self, user, obj, payload):
        """"""
        for entity in obj.entity_set.all():
            if user.has_perm('share_entity', entity):
                update_permission(entity, payload)

        # Data doesn't have "ADD" permission, so it has to be removed
        payload = remove_permission(payload, 'add')

        for data in obj.data.all():
            if user.has_perm('share_data', data):
                update_permission(data, payload)
1273597
def editpermissions_anonymous_user_view(self, request, forum_id=None):
        
        forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None

        # Set up the context
        context = self.get_forum_perms_base_context(request, forum)
        context['forum'] = forum
        context['title'] = '{} - {}'.format(_('Forum permissions'), _('Anonymous user'))
        context['form'] = self._get_permissions_form(
            request, UserForumPermission, {'forum': forum, 'anonymous_user': True},
        )

        return render(request, self.editpermissions_anonymous_user_view_template_name, context)
646561
private void visit_OP_SET_PERMISSIONS() throws IOException {
    visitTxId();
    v.visitStringUTF8( EditsElement.PATH);
    v.visitShort(      EditsElement.FS_PERMISSIONS);
  }
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()
347728
def edit(self, name, permission=''):
        
        if name:
            data = {'name': name, 'permission': permission}
            json = self._json(self._patch(self._api, data=dumps(data)), 200)
            if json:
                self._update_(json)
                return True
        return False