Adds the permission 'Reject Analysis Request' and update the permission
     mappings accordingly
335598
def update_rejection_permissions(portal):
    
    updated = update_rejection_permissions_for(portal, "bika_ar_workflow",
                                               "Reject Analysis Request")
    if updated:
        brains = api.search(dict(portal_type="AnalysisRequest"),
                            CATALOG_ANALYSIS_REQUEST_LISTING)
        update_rolemappings_for(brains, "bika_ar_workflow")


    updated = update_rejection_permissions_for(portal, "bika_sample_workflow",
                                               "Reject Sample")
    if updated:
        brains = api.search(dict(portal_type="Sample"), "bika_catalog")
        update_rolemappings_for(brains, "bika_sample_workflow")
378054
def reject_insert(self, s_pappid, order_id, reason, redirect_url=None):
        
        return self._post(
            'rejectinsert',
            data={
                's_pappid': s_pappid,
                'order_id': order_id,
                'reason': reason,
                'url': redirect_url,
            },
        )
826599
protected function updatePermission()
    {
        foreach ($this->permissions() as $Permission) {
            $this->authManager->add($Permission);

            echo sprintf('    > permission `%s` added.', $Permission->name) . PHP_EOL;
        }
    }
1012712
public void updatePermissions() {
    final String[] accessViewerList =
        this.accessViewer.trim().split(ACCESS_LIST_SPLIT_REGEX);
    final String[] accessExecutorList =
        this.accessExecutor.trim().split(ACCESS_LIST_SPLIT_REGEX);
    final String[] accessOwnerList =
        this.accessOwner.trim().split(ACCESS_LIST_SPLIT_REGEX);
    // Prepare permission types
    final Permission admin = new Permission();
    admin.addPermission(Type.READ);
    admin.addPermission(Type.EXECUTE);
    admin.addPermission(Type.ADMIN);
    final Permission executor = new Permission();
    executor.addPermission(Type.READ);
    executor.addPermission(Type.EXECUTE);
    final Permission viewer = new Permission();
    viewer.addPermission(Type.READ);
    // Sets the permissions
    this.project.clearUserPermission();
    for (String user : accessViewerList) {
      user = user.trim();
      if (!user.isEmpty()) {
        this.project.setUserPermission(user, viewer);
      }
    }
    for (String user : accessExecutorList) {
      user = user.trim();
      if (!user.isEmpty()) {
        this.project.setUserPermission(user, executor);
      }
    }
    for (String user : accessOwnerList) {
      user = user.trim();
      if (!user.isEmpty()) {
        this.project.setUserPermission(user, admin);
      }
    }
    this.project.setUserPermission(this.reportalUser, admin);
  }
127381
function addSubmissionFile(req, res, next) {
  req.addingNewSubmissionFile = true;

  updateSubmissionFile(req, res, next);
}
916387
def add_permission(content_type, permission):
    
    # build our permission slug
    codename = "%s_%s" % (content_type.model, permission)

    # sys.stderr.write("Checking %s permission for %s\n" % (permission, content_type.name))

    # does it already exist
    if not Permission.objects.filter(content_type=content_type, codename=codename):
        Permission.objects.create(content_type=content_type,
                                  codename=codename,
                                  name="Can %s %s" % (permission, content_type.name))
1143434
def guard_cancel(analysis_request):
    
    # Ask to partitions
    for partition in analysis_request.getDescendants(all_descendants=False):
        if not isTransitionAllowed(partition, "cancel"):
            return False

    # Look through analyses. We've checked the partitions already, so there is
    # no need to look through analyses from partitions again, but through the
    # analyses directly bound to the current Analysis Request.
    cancellable_states = ["unassigned", "registered"]
    for analysis in analysis_request.objectValues("Analysis"):
        if api.get_workflow_status_of(analysis) not in cancellable_states:
            return False

    return True
814593
private void modify(Set<Permission> permissions, IResource resource, String user, String op) throws RequestExecutionException
    {
        process(String.format("UPDATE %s.%s SET permissions = permissions %s {%s} WHERE username = '%s' AND resource = '%s'",
                              Auth.AUTH_KS,
                              PERMISSIONS_CF,
                              op,
                              "'" + StringUtils.join(permissions, "','") + "'",
                              escape(user),
                              escape(resource.getName())));
    }
231399
def guard_assign(analysis):
    
    # Only if the request was done from worksheet context.
    if not is_worksheet_context():
        return False

    # Cannot assign if the Sample has not been received
    if not analysis.isSampleReceived():
        return False

    # Cannot assign if the analysis has a worksheet assigned already
    if analysis.getWorksheet():
        return False

    # Cannot assign if user does not have permissions to manage worksheets
    return user_can_manage_worksheets()
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
785056
protected void requestPermission(String[] permissions, int code) {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> deniedPermissions = getDeniedPermissions(this, permissions);
            if (deniedPermissions.isEmpty()) {
                onPermissionGranted(code);
            } else {
                permissions = new String[deniedPermissions.size()];
                deniedPermissions.toArray(permissions);
                ActivityCompat.requestPermissions(this, permissions, code);
            }
        } else {
            onPermissionGranted(code);
        }
    }
877140
private void validateAccessPermissions(ItemState changedItem) throws RepositoryException, AccessDeniedException
   {
      if (changedItem.isAddedAutoCreatedNodes())
      {
         validateAddNodePermission(changedItem);
      }
      else if (changedItem.isDeleted())
      {
         validateRemoveAccessPermission(changedItem);
      }
      else if (changedItem.isMixinChanged())
      {
         validateMixinChangedPermission(changedItem);
      }
      else
      {
         NodeData parent = (NodeData)getItemData(changedItem.getData().getParentIdentifier());
         if (parent != null)
         {
            if (changedItem.getData().isNode())
            {
               // add node
               if (changedItem.isAdded())
               {
                  if (!accessManager.hasPermission(parent.getACL(), new String[]{PermissionType.ADD_NODE}, session
                     .getUserState().getIdentity()))
                  {
                     throw new AccessDeniedException("Access denied: ADD_NODE "
                        + changedItem.getData().getQPath().getAsString() + " for: " + session.getUserID()
                        + " item owner " + parent.getACL().getOwner());
                  }
               }
            }
            else if (changedItem.isAdded() || changedItem.isUpdated())
            {
               // add or update property
               if (!accessManager.hasPermission(parent.getACL(), new String[]{PermissionType.SET_PROPERTY}, session
                  .getUserState().getIdentity()))
               {
                  throw new AccessDeniedException("Access denied: SET_PROPERTY "
                     + changedItem.getData().getQPath().getAsString() + " for: " + session.getUserID() + " item owner "
                     + parent.getACL().getOwner());
               }
            }
         } // else - parent not found, deleted in this session or from another
      }
   }
727469
def check_permissions(self, request):
        
        permissions = [permission() for permission in self.permission_classes]
        for permission in permissions:
            if not permission.has_permission(request):
                raise PermissionDenied()
1015246
def update_allowed(self):
        
        return self.update_action.allowed(self.column.table.request,
                                          self.datum,
                                          self)
127055
def change_analysis_requests_id_formatting(portal, p_type="AnalysisRequest"):
    
    ar_id_format = dict(
        form='{sampleType}-{seq:04d}',
        portal_type='AnalysisRequest',
        prefix='analysisrequest',
        sequence_type='generated',
        counter_type='',
        split_length=1)

    bs = portal.bika_setup
    id_formatting = bs.getIDFormatting()
    ar_format = filter(lambda id: id["portal_type"] == p_type, id_formatting)
    if p_type=="AnalysisRequest":
        logger.info("Set ID Format for Analysis Request portal_type ...")
        if not ar_format or "sample" in ar_format[0]["form"]:
            # Copy the ID formatting set for Sample
            change_analysis_requests_id_formatting(portal, p_type="Sample")
            return
        else:
            logger.info("ID Format for Analysis Request already set: {} [SKIP]"
                        .format(ar_format[0]["form"]))
            return
    else:
        ar_format = ar_format and ar_format[0].copy() or ar_id_format

    # Set the Analysis Request ID Format
    ar_id_format.update(ar_format)
    ar_id_format["portal_type"] ="AnalysisRequest"
    ar_id_format["prefix"] = "analysisrequest"
    set_id_format(portal, ar_id_format)

    # Find out the last ID for Sample and reseed AR to prevent ID already taken
    # errors on AR creation
    if p_type == "Sample":
        number_generator = getUtility(INumberGenerator)
        ar_keys = dict()
        ar_keys_prev = dict()
        for key, value in number_generator.storage.items():
            if "sample-" in key:
                ar_key = key.replace("sample-", "analysisrequest-")
                ar_keys[ar_key] = api.to_int(value, 0)
            elif "analysisrequest-" in key:
                ar_keys_prev[key] = api.to_int(value, 0)

        for key, value in ar_keys.items():
            if key in ar_keys_prev:
                # Maybe this upgrade step has already been run, so we don't
                # want the ar IDs to be reseeded again!
                if value <= ar_keys_prev[key]:
                    logger.info("ID for '{}' already seeded to '{}' [SKIP]"
                                .format(key, ar_keys_prev[key]))
                    continue
            logger.info("Seeding {} to {}".format(key, value))
            number_generator.set_number(key, value)
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
97205
function assignPermissions (done) {
  async.map(defaults.permissions, function (pair, callback) {
    Role.addScopes(pair[0], pair[1], function (err, result) {
      callback(err, result)
    })
  }, function (err, results) {
    done(err, results)
  })
}