Create Permission (and any missing Permission between this and Parent) if
we have permission

Pass in the desired Management Permission for this Permission

If Force is set, then Roles listed will be created, if allowed,
pre-granted.
484426
public Result<Void> createPerm(AuthzTrans trans, PermDAO.Data perm, boolean fromApproval) {
		String user = trans.user();
		// Next, see if User is allowed to Manage Parent Permission

		Result<NsDAO.Data> rnsd;
		if (!fromApproval) {
			rnsd = q.mayUser(trans, user, perm, Access.write);
			if (rnsd.notOK()) {
				return Result.err(rnsd);
			}
		} else {
			rnsd = q.deriveNs(trans, perm.ns);
		}

		// Does Child exist?
		if (!trans.forceRequested()) {
			if (q.permDAO.read(trans, perm).isOKhasData()) {
				return Result.err(Status.ERR_ConflictAlreadyExists,
						"Permission [%s.%s|%s|%s] already exists.", perm.ns,
						perm.type, perm.instance, perm.action);
			}
		}

		// Attempt to add perms to roles, creating as possible
		Set<String> roles;
		String pstring = perm.encode();

		// For each Role
		for (String role : roles = perm.roles(true)) {
			Result<RoleDAO.Data> rdd = RoleDAO.Data.decode(trans,q,role);
			if(rdd.isOKhasData()) {
				RoleDAO.Data rd = rdd.value;
				if (!fromApproval) {
					// May User write to the Role in question.
					Result<NsDAO.Data> rns = q.mayUser(trans, user, rd,
							Access.write);
					if (rns.notOK()) {
						// Remove the role from Add, because
						roles.remove(role); // Don't allow adding
						trans.warn()
								.log("User [%s] does not have permission to relate Permissions to Role [%s]",
										user, role);
					}
				}

				Result<List<RoleDAO.Data>> rlrd;
				if ((rlrd = q.roleDAO.read(trans, rd)).notOKorIsEmpty()) {
					rd.perms(true).add(pstring);
					if (q.roleDAO.create(trans, rd).notOK()) {
						roles.remove(role); // Role doesn't exist, and can't be
											// created
					}
				} else {
					rd = rlrd.value.get(0);
					if (!rd.perms.contains(pstring)) {
						q.roleDAO.addPerm(trans, rd, perm);
					}
				}
			}
		}

		Result<PermDAO.Data> pdr = q.permDAO.create(trans, perm);
		if (pdr.isOK()) {
			return Result.ok();
		} else { 
			return Result.err(pdr);
		}
	}
731532
def add_role(self, role):
        
        schema = RoleSchema()
        ok = schema.process(role)
        if not ok or not role.id:
            err = 'Role must be valid and saved before adding to user'
            raise x.UserException(err)

        self.__roles.append(role)
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)
762184
def authorize(self, role):
        """"""
        resource, action = parse_request()
        roles = self.meta.get("$roles", {})
        message = "%s can't access %s.%s" % (role, resource, action)
        try:
            if action not in roles[role][resource]:
                abort(403, "PermissionDeny", message)
        except KeyError:
            abort(403, "PermissionDeny", message)
744205
private static PermissionDefinition createPermission(String permission, String description) {

        PermissionDefinitionDataImpl pd = new PermissionDefinitionDataImpl();
        pd.setId(permission);
        pd.setDescription(description);

        return pd;
    }
77811
def _load_permissions(self):
        """"""
        result = _P(needs=set(), excludes=set())
        if not self.allow_by_default:
            result.needs.update(self.explicit_needs)

        for explicit_need in self.explicit_needs:
            if explicit_need.method == 'action':
                action = current_access.get_action_cache(
                    self._cache_key(explicit_need)
                )
                if action is None:
                    action = _P(needs=set(), excludes=set())

                    actionsusers = ActionUsers.query_by_action(
                        explicit_need
                    ).all()

                    actionsroles = ActionRoles.query_by_action(
                        explicit_need
                    ).join(
                        ActionRoles.role
                    ).all()

                    actionssystem = ActionSystemRoles.query_by_action(
                        explicit_need
                    ).all()

                    for db_action in chain(
                            actionsusers, actionsroles, actionssystem):
                        if db_action.exclude:
                            action.excludes.add(db_action.need)
                        else:
                            action.needs.add(db_action.need)

                    current_access.set_action_cache(
                        self._cache_key(explicit_need),
                        action
                    )
                # in-place update of results
                result.update(action)
            elif self.allow_by_default:
                result.needs.add(explicit_need)
        self._permissions = result
968361
def set(self, permissions):
        
        parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id})
        target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'PUT', 'multi')
        r = self.client.request('PUT', target_url, json=permissions)
        if r.status_code != 201:
            raise exceptions.ServerError("Expected 201 response, got %s: %s" % (r.status_code, target_url))
        return self.list()
875041
public static boolean hasPermission(Permission permission) {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            try {
                security.checkPermission(permission);
            } catch (java.security.AccessControlException e) {
                return false;
            }
        }
        return true;
    }
741981
public function add()
    {
        $this->loadModel('User.Roles');
        $role = $this->Roles->newEntity();

        if ($this->request->data()) {
            $role = $this->Roles->patchEntity($role, $this->request->data(), ['fieldList' => 'name']);
            if ($this->Roles->save($role)) {
                $this->Flash->success(__d('user', 'Role successfully created.'));
            } else {
                $this->Flash->danger(__d('user', 'Role could not be created.'));
            }
        }

        $this->title(__d('user', 'Define New Role'));
        $this->set(compact('role'));
        $this->Breadcrumb
            ->push('/admin/user/manage')
            ->push(__d('user', 'Roles'), ['plugin' => 'User', 'controller' => 'roles', 'action' => 'index'])
            ->push(__d('user', 'Add new role'), '');
    }
1241752
def add_permission(self, role, name):
        
        if self.has_permission(role, name):
            return True
        targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
        if not targetGroup:
            return False
        # Create or update
        permission = AuthPermission.objects(name=name).update(
                add_to_set__groups=[targetGroup], creator=self.client, upsert=True
        )
        return True
273589
def create_permission(self):
        """"""
        return Permission(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
739482
def role_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/roles"
        return self.call(api_path, method="POST", data=data, **kwargs)
531207
def add_permission(target, *args)
      raise '#can and #can_not have to be used inside a role block' unless @role
      options = args.last.is_a?(Hash) ? args.pop : {}
      tasks = []
      models = []

      models << args.pop if args.last == :any
      args.each {|arg| arg.is_a?(Symbol) ? tasks << arg : models << arg}

      tasks.each do |task|
        models.each do |model|
          if permission = target[task][model][@role]
            permission.load_options(options)
          else
            target[task][model][@role] = Permission.new(@role, task, model, options)
          end
        end
      end
    end
651962
public function addMissingRoles()
    {
        if (!get_role('author')) {
            add_role(
                'author',
                'Author',
                array(
                    'upload_files'           => true,
                    'edit_posts'             => true,
                    'edit_published_posts'   => true,
                    'publish_posts'          => true,
                    'read'                   => true,
                    'level_2'                => true,
                    'level_1'                => true,
                    'level_0'                => true,
                    'delete_posts'           => true,
                    'delete_published_posts' => true
                )
            );

            delete_option('_author_role_bkp');
        }
    }
250985
public void addPermission(String roleName, String capability) {
    Permission permission = new Permission();
    permission.setRoleName(roleName);
    permission.setCapability(capability);
    this.permissions.add(permission);
  }
423475
def create_role(resource_root,
                service_name,
                role_type,
                role_name,
                host_id,
                cluster_name="default"):
  
  apirole = ApiRole(resource_root, role_name, role_type,
                    ApiHostRef(resource_root, host_id))
  return call(resource_root.post,
      _get_roles_path(cluster_name, service_name),
      ApiRole, True, data=[apirole])[0]
673119
def grant_admin_role(self):
    
    apiuser = ApiUser(self._get_resource_root(), self.name, roles=['ROLE_ADMIN'])
    return self._put('', ApiUser, data=apiuser)