This post_syncdb/post_migrate hooks takes care of adding a view permission too all our
    content types.
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)
753951
final protected function initPostStatusesTrait(): void {
		$postStatuses = $this->getPostStatuses();
		
		// first, we register our statuses.  notice that we directly call the
		// WordPress add_action() function because we want to use anonymous
		// functions here, and there's no good way to add these actions to a
		// LoaderInterface object as a result.  plus, we want these actions to
		// "just happen" without a programmer having to think about them.
		
		$options = [];
		foreach ($postStatuses as $postStatus) {
			$args = $this->getPostStatusArguments($postStatus);
			add_action("init", function () use ($postStatus, $args) {
				register_post_status($postStatus, $args);
			});
			
			$options[$postStatus] = $args["label"];
		}
		
		add_action("post_submitbox_misc_actions",
			function (\WP_Post $post) use ($options) {
				// registering our post status tells WordPress all about it,
				// but WordPress doesn't automatically add them to the <select>
				// elements in the DOM.  so, we do that here.  for more info
				// see https://core.trac.wordpress.org/ticket/12706.
				
				$jsonOptions = "{";
				$optionFormat = '"%s": { "display": "%s", "selected": %d },';
				foreach ($options as $status => $display) {
					$selected = (int)$post->post_status === $status;
					
					// for each of our options, we use the above format to
					// create a series of JSON strings which we can inject
					// into our JavaScript below.
					
					$jsonOptions .= sprintf($optionFormat, $status, $display, $selected);
				}
				
				// the loop above adds an extra comma to our JSON string.
				// we'll replace that comma with a the closing curly brace
				// to end said string.
				
				$jsonOptions = preg_replace("/,$/", "}", $jsonOptions);
				ob_start(); ?>

                <script id="php7BoilerplateAddPostStatuses">
					(function ($) {

						// we'll add our statuses into the scope of this
						// anonymous functions.  that way, it's accessible
						// to the other functions, anonymous or otherwise,
						// herein.  but, it won't conflict with any other
						// variable named statuses outside this scope.

						var statuses = <?= $jsonOptions ?>;

						$(document).ready(function () {
							var statusSelect = $("#post_status");
							if (statusSelect.length > 0) {

								// as long as we have a status <select> in
								// the DOM, we'll want to do some work to make
                                // our custom statuses work.

								setDisplayedStatus(statusSelect);
								$(".save-post-status").click(setHiddenStatus);
								addCustomStatuses(statusSelect);
							}
						});
						
						function setDisplayedStatus(statusSelect) {
							var status = statusSelect.val();
							
							// as long as our status is in our list of custom
                            // statuses, we want to make sure that the on-
                            // screen display of the posts's status matches
                            // the display of the selected option.
                            
                            if ($.inArray(status, statuses)) {
                                var display = statusSelect.find("option[value=" + status + "]").text();
                                $("#post-status-display").text(display);
                            }
						}
						
						function setHiddenStatus() {
							var status = $("#post_status").val();

							// as long as the status that's selected is a part
							// of our list of statuses, we'll want to set the
							// the value of the #hidden_post_status field to
							// the selected status.

							if ($.inArray(status, statuses)) {
								$("#hidden_post_status").val(status);
							}
						}

						function addCustomStatuses(statusSelect) {
							for(status in statuses) {
								if (statuses.hasOwnProperty(status)) {

									// for each of our custom statuses, we
									// create an <option>.  if our status is
									// selected, then we set that property.
									// otherwise, we set various attributes
									// and then append it to our <select>
									// element.

									var option = $("<option>")
										.prop("selected", statuses[status].selected)
										.text(statuses[status].display)
										.attr("value", status)
										.data("custom", true);

									statusSelect.append(option);
								}
							}

							// in case we need to do anything else after we've
							// changed the DOM, we fire this event, too.  then,
							// other JS can watch for it and handle any clean
							// up or whatever when it's caught.

							var event = new jQuery.Event("postStatusesAdded");
							statusSelect.trigger(event);
						}
					})(jQuery);
                </script>
				
				<?php echo ob_get_clean();
				
			}
		);
	}
563577
private CompletableFuture<Revision> addPermissionAtPointer(Author author,
                                                               String projectName, JsonPointer path,
                                                               Collection<Permission> permission,
                                                               String commitSummary) {
        final Change<JsonNode> change =
                Change.ofJsonPatch(METADATA_JSON,
                                   asJsonArray(new TestAbsenceOperation(path),
                                               new AddOperation(path, Jackson.valueToTree(permission))));
        return metadataRepo.push(projectName, Project.REPO_DOGMA, author, commitSummary, change);
    }
998420
def _process_permission(perm):
    """"""
    # XXX: Optimize: rebuild only permissions, not whole document
    codename = perm.permission.codename
    if not codename.startswith('view') and not codename.startswith('owner'):
        return

    index_builder.build(perm.content_object)
165221
def has_permission(self, *args, **kwargs):
        """"""
        def wrapper(view):
            if getattr(view, '_has_permissions_decorator', False) is True:
                return view

            @wraps(view)
            @jsonapi_exception_formatter
            def decorated(*view_args, **view_kwargs):
                self.check_permissions(view, view_args, view_kwargs, *args, **kwargs)
                return view(*view_args, **view_kwargs)
            decorated._has_permissions_decorator = True
            return decorated
        return wrapper
845897
def blog__sync_config_post_fields_with_db_post_fields_for_post(post)
      # save or update post fields from config
      post_fields = CONFIGS[:lato_blog][:post_fields]
      post_fields.map { |key, content| blog__sync_config_post_field(post, key, content) }
      # remove old post fields
      db_post_fields = post.post_fields.visibles.roots
      db_post_fields.map { |dbpf| blog__sync_db_post_field(post, dbpf) }
    end
315476
public function view($_type = null, $id = null)
    {
        // setting up an event for the view
        $_event = new Event('Controller.PostTypes.beforeView.' . $this->_type, $this, [
            'id' => $id,
        ]);
        $this->eventManager()->dispatch($_event);

        $type = $this->Model->get($id, [
            'contain' => $this->Settings['contain']
        ]);
        $this->set('type', $type);

        // setting up an event for the view
        $_event = new Event('Controller.PostTypes.afterView.' . $this->_type, $this, [
            'id' => $id,
        ]);
        $this->eventManager()->dispatch($_event);

        if (!$this->Settings['views']['view']) {
            $this->render(Configure::read('PostTypes.AdminPostTypeViews.view'));
            return;
        }

        $this->render($this->Settings['views']['view']);
    }
1035514
def add_permission_role(self, role, perm_view):
        
        if perm_view not in role.permissions:
            try:
                role.permissions.append(perm_view)
                self.get_session.merge(role)
                self.get_session.commit()
                log.info(
                    c.LOGMSG_INF_SEC_ADD_PERMROLE.format(str(perm_view), role.name)
                )
            except Exception as e:
                log.error(c.LOGMSG_ERR_SEC_ADD_PERMROLE.format(str(e)))
                self.get_session.rollback()
1219992
function permissible(postModel, action, context, unsafeAttrs, loadedPermissions, hasUserPermission, hasAppPermission, hasApiKeyPermission) {
        let isContributor, isEdit, isAdd, isDestroy;

        function isChanging(attr) {
            return unsafeAttrs[attr] && unsafeAttrs[attr] !== postModel.get(attr);
        }

        function isPublished() {
            return unsafeAttrs.status && unsafeAttrs.status !== 'draft';
        }

        function isDraft() {
            return postModel.get('status') === 'draft';
        }

        isContributor = loadedPermissions.user && _.some(loadedPermissions.user.roles, {name: 'Contributor'});
        isEdit = (action === 'edit');
        isAdd = (action === 'add');
        isDestroy = (action === 'destroy');

        if (isContributor && isEdit) {
            // Only allow contributor edit if status is changing, and the post is a draft post
            hasUserPermission = !isChanging('status') && isDraft();
        } else if (isContributor && isAdd) {
            // If adding, make sure it's a draft post and has the correct ownership
            hasUserPermission = !isPublished();
        } else if (isContributor && isDestroy) {
            // If destroying, only allow contributor to destroy their own draft posts
            hasUserPermission = isDraft();
        }

        const excludedAttrs = [];
        if (isContributor) {
            // Note: at the moment primary_tag is a computed field,
            // meaning we don't add it to this list. However, if the primary_tag/primary_author
            // ever becomes a db field rather than a computed field, add it to this list
            // TODO: once contributors are able to edit existing tags, this can be removed
            // @TODO: we need a concept for making a diff between incoming tags and existing tags
            excludedAttrs.push('tags');
        }

        if (hasUserPermission && hasApiKeyPermission && hasAppPermission) {
            return Promise.resolve({excludedAttrs});
        }

        return Promise.reject(new common.errors.NoPermissionError({
            message: common.i18n.t('errors.models.post.notEnoughPermission')
        }));
    }
1231585
def create_permissions():
    
    current_app.appbuilder.add_permissions(update_perms=True)
    click.echo(click.style("Created all permissions", fg="green"))
56754
function handlePermissionUpdate() {
            permissionArea.find("form").submit(function (e) {
                e.preventDefault();
                //console.log(e);
                var form = e.currentTarget;
                appendFormFields(form);
                Rocket.Util.submitFormAsync(form, function (responseData) {
                    //console.log(responseData);
                    if (responseData && responseData.status && responseData.status == "success") {
                        location.reload();
                    }
                });
            });
        }
356267
public function actionAdd() 
	{
		$setting = BannerSetting::model()->findByPk(1, array(
			'select' => 'banner_file_type',
		));
		$banner_file_type = unserialize($setting->banner_file_type);
		if(empty($banner_file_type))
			$banner_file_type = array();
		
		$model=new Banners;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Banners'])) {
			$model->attributes=$_POST['Banners'];

			if($model->save()) {
				Yii::app()->user->setFlash('success', Yii::t('phrase', 'Banner success created.'));
				$this->redirect(array('manage'));
			}
		}

		$this->pageTitle = Yii::t('phrase', 'Create Banner');
		$this->pageDescription = '';
		$this->pageMeta = '';
		$this->render('admin_add', array(
			'model'=>$model,
			'banner_file_type'=>$banner_file_type,
		));
	}
776864
def add_event_view(request):
    
    is_events_admin = request.user.has_admin_permission('events')
    if not is_events_admin:
        return redirect("request_event")

    if request.method == "POST":
        form = EventForm(data=request.POST, all_groups=request.user.has_admin_permission('groups'))
        logger.debug(form)
        if form.is_valid():
            obj = form.save()
            obj.user = request.user
            # SAFE HTML
            obj.description = safe_html(obj.description)

            # auto-approve if admin
            obj.approved = True
            obj.approved_by = request.user
            messages.success(request, "Because you are an administrator, this event was auto-approved.")
            obj.created_hook(request)

            obj.save()
            return redirect("events")
        else:
            messages.error(request, "Error adding event.")
    else:
        form = EventForm(all_groups=request.user.has_admin_permission('groups'))
    context = {"form": form, "action": "add", "action_title": "Add" if is_events_admin else "Submit", "is_events_admin": is_events_admin}
    return render(request, "events/add_modify.html", context)
357646
def manage_request_types_view(request):
    ''' 
    '''
    request_types = RequestType.objects.all()
    return render_to_response('manage_request_types.html', {
        'page_name': "Admin - Manage Request Types",
        'request_types': request_types
        }, context_instance=RequestContext(request))
333674
public function postsIndex($lang, $postTypeSlug, $view)
    {
        $postType = PostType::findBySlug($postTypeSlug);
        if(!$postType) {
            return response()->view('errors.404', ['message' => "This post type does not exist!"], 404);
        }

        // check if user has permissions to access this link
        $key = ($view == 'list') ? 'read' : $view;
        if(!User::hasAccess($postTypeSlug, $key)) {
            return view('errors.permissions');
        }

        return view('content');
    }
13819
def check_all_permissions(sender, **kwargs):
    
    if not is_permissions_app(sender):
        return

    config = getattr(settings, 'PERMISSIONS', dict())

    # for each of our items
    for natural_key, permissions in config.items():
        # if the natural key '*' then that means add to all objects
        if natural_key == '*':
            # for each of our content types
            for content_type in ContentType.objects.all():
                for permission in permissions:
                    add_permission(content_type, permission)

        # otherwise, this is on a specific content type, add for each of those
        else:
            app, model = natural_key.split('.')
            try:
                content_type = ContentType.objects.get_by_natural_key(app, model)
            except ContentType.DoesNotExist:
                continue

            # add each permission
            for permission in permissions:
                add_permission(content_type, permission)
539184
def add_view(self, request, form_url='', extra_context=None):
        """"""
        extra_context = {
            'language': get_language_from_request(request),
            'page_languages': settings.PAGE_LANGUAGES,
        }
        return super(PageAdmin, self).add_view(request, form_url,
                                               extra_context)