/*
PermissionController.requiresPermission('Some.permission');
or
PermissionController.requiresPermission(['Some.permission', 'Another.permission']);
340128
function(requiredPermissions) {
      if (requiredPermissions instanceof Array) {
        requiredPermissions = {
          all: requiredPermissions
        }
      } else if (typeof requiredPermissions !== 'object') {
        requiredPermissions = {
          all: [requiredPermissions]
        }
      }

      return function(req, res, next) {
        var user    = req.user
          , method  = req.method.toLowerCase()
          , id      = req.params.id
          , action  = req.params.action || id;

        if (!!id && !!action && action === 'list') {
          action = 'get'
          req.params.action = 'get';
        } else if (!action && method === 'get' && /^\/.*\/(.*\/?)$/ig.test(req.url)) {
          action = 'list';
        } else if (/^[0-9a-fA-F]{24}$/.test(action) || !isNaN(action)) {
          action = 'get';
        } else {
          if (req.params.action) {
            action = req.params.action;
          } else if (method === 'get' && !id) {
            action = 'list';
          } else {
            action = method;
          }
        }

        async.waterfall(
          [

            function determinePermissions(callback) {
              var actionName = (!!action ? action : method) + 'Action'
                , permissions = [];
              
              if (typeof requiredPermissions[actionName] !== 'undefined') {
                if (requiredPermissions[actionName] !== null) {
                  if (requiredPermissions[actionName] instanceof Array) {
                    permissions = permissions.concat(requiredPermissions[actionName]);
                  } else {
                    permissions.push(requiredPermissions[actionName]);
                  }
                }
              } else if (typeof requiredPermissions.all !== 'undefined') {
                if (requiredPermissions.all !== null) {
                  permissions = requiredPermissions.all instanceof Array ? requiredPermissions.all : [requiredPermissions.all];
                }
              }

              callback(null, permissions);
            },

            function userRoleHasPermission(permissions, callback) {
              var hasPermission = true;

              if (!!permissions.length && !req.isAuthenticated()) {
                return callback('User is not authenticated!');
              }

              permissions.every(function(requiredPermission) {
                if (/^([^\$]+)\.\$action/.test(requiredPermission)) {
                  requiredPermission = RegExp.$1 + '.';

                  switch(action) {
                  
                  case 'get':
                    requiredPermission += 'view';
                    break;
                  case 'post':
                    requiredPermission += 'create';
                    break;
                  case 'put':
                    requiredPermission += 'edit';
                    break;
                  default:
                    requiredPermission += action;
                    break;
                  }
                }

                if (requiredPermission !== 'requiresLogin' && _.findWhere([].slice.call(user.Role.Permissions), { action: requiredPermission }) === undefined) {
                  callback('Logged in user does not have ' + requiredPermission + ' permission.');
                  hasPermission = false;
                  return false;
                }
                return true;
              });

              if (!!hasPermission) {
                callback(null);
              }
            }
          ],
          function(err) {
            if (err === null) {
              next();
            } else {
              console.dir(err);
              res.send(401, { statusCode: 401, message: err });
            }
          }

       );
      }
    }
1076655
public boolean hasPermissionsById(String id, Collection<Permission> permissions) {
        AuthorizationInfo authorizationInfo = getAuthorizationInfoById(id);
        return authorizationInfo != null && isPermittedAll(permissions, authorizationInfo);
    }
348
@Override @NonNull @CheckReturnValue public Observable<Permission> requestEach(@NonNull final String... permissions) {
    return Observable.just(TRIGGER)
        .compose(ensureEach(permissions));
  }
1076978
function permissionJsApis(cb, jsApisConfig, errorCb) {
  if (!jsApisConfig) {
    ship.ready(function () {
      cb(null);
    });
    return;
  }
  ship.ready(function () {
    var permission = ship.apis.runtime.permission;
    var apisConf = jsApisConfig ? jsApisConfig : {};
    var errCb = errorCb ? errorCb : null;
    apisConf.onSuccess = function (response) {
      cb(null, response);
    };
    apisConf.onFail = function (error) {
      if (typeof errCb === 'function') {
        errCb(error);
      } else {
        cb(error, null);
      }
    };
    permission.requestJsApis(apisConf);
  });
}
457686
function(permission, negative) {
            if (!negative) {
              negative = false;
            }
            if (permission !== null && !Array.isArray(permission)) {
              var p = (negative) ? this.permissions.exclude : this.permissions.include;
              p.push(permission);
            }
          }
384687
@Override
    public void removePermissions(IPermission[] permissions) throws AuthorizationException {
        if (permissions.length > 0) {
            getPermissionStore().delete(permissions);
            if (this.cachePermissions) {
                removeFromPermissionsCache(permissions);
            }
        }
    }
131160
public static void requireAccess (ClientObject clobj, Permission perm, Object context)
        throws InvocationException
    {
        String errmsg = clobj.checkAccess(perm, context);
        if (errmsg != null) {
            throw new InvocationException(errmsg);
        }
    }
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
      }
   }
1218328
function(options) {
    var action = PermissionService.getMethod(options.method);

    //console.log('findModelPermissions options', options)
    //console.log('findModelPermissions action', action)

    return User.findOne(options.user.id)
      .populate('roles')
      .then(function(user) {
        var permissionCriteria = {
          model: options.model.id,
          action: action,
          or: [
            { role: _.pluck(user.roles, 'id') },
            { user: user.id }
          ]
        };
        
        return Permission.find(permissionCriteria).populate('criteria')
      });
  }
1157226
@Override
	public boolean addPermission(Permission permission)
	{
		if(permissions.contains(permission))
			return false;
		
		return this.permissions.add(permission);
	}
1308247
function(objects, user) {
    if (!_.isArray(objects)) {
      return PermissionService.isForeignObject(user.id)(objects);
    }
    return _.any(objects, PermissionService.isForeignObject(user.id));
  }
984114
def _check_permission(self, request):
        

        if self.access_controller:
            self.access_controller.check_perm(request, self)
1197312
private void permissionWithoutUsage() {
        if (isUsingNonJava)
            return;
        synchronized (permanentUserReadWriteLock) {
            permissionWithoutUsageLimit = LocalDateTime.now().plus(10, ChronoUnit.SECONDS);
            permissionWithoutUsageCloseThread =  getMain().getThreadPoolManager().getAddOnsThreadPool()
                    .submit((Runnable)() -> {
                try {
                    Thread.sleep(10000);
                    fireLineAccessEndedNotification();
                    endPermanent(permanentAddOn);
                } catch (InterruptedException ignored) {
                    //ignored.printStackTrace();
                }
            });
        }
    }
9866
public void addPermission(Permission permission) {
        if ((securityManager != null) && (permission != null)) {
            permissionList.add(permission);
        }
    }
820531
def required_permission(f, level):
    """"""

    @functools.wraps(f)
    def wrapper(request, pid, *args, **kwargs):
        d1_gmn.app.auth.assert_allowed(request, level, pid)
        return f(request, pid, *args, **kwargs)

    return wrapper
350888
function PermissionValidator(req, permissionSchemaKey, modelName) {
    if (arguments.length != 3) {
        throw new Error("Invalid no of arguments");
    }

    var userRoles = req.session.roles;

    var isValidModelId = function (modelId) {
        return _.isNumber(modelId);
    };

    /**
     * Returns permission error object for the action
     * @param action {String}
     * @returns {PermissionError}
     */
    var getPermissionError = this.getPermissionError = function (action) {
        return new PermissionError(null, req.session.user.userName, action)
    };

    /**
     * Returns validation result object
     * This object has following keys:
     *      isAuthorized {Boolean}: whether action is authorized
     *      roleId {Number}: Role for which action is validated
     *      action {String}: Action for which permissions are checked
     *
     * @param action {String}
     * @returns {Object}
     */
    function hasPermission1(action) {
        var cacheItem = getCacheItem(permissionSchemaKey);
        var p = checkPermissionSync(action, userRoles, cacheItem);
        /*if (p.isAuthorized === false) {
         throw new PermissionError(null, req.session.user.userName, action);
         }*/
        return  p;
    };

    /**
     * Method useful when model id is not present to assess permissions.
     * Case in which modelName is also not provided, when creating PermissionValidator instance
     *
     * @param action {String}
     * @param next {Function} - Callback will have err & permission result obj as parameters
     */
    this.hasPermissionWithoutModelId = function (action, next) {
        var that = this;
        if (!action || !_.isString(action) || !_.isFunction(next)) {
            throw new Error("Missing arguments.")
        }
        var err;
        var p = hasPermission1(action);
        if (p.isAuthorized === false) {
            err = getPermissionError(action);
        }
        next(err, p);
    };

    /**
     * Method useful to validate multiple permission actions in a single request
     * @param actions {Array} Multiple can be passed
     * @param modelId {Number}
     * @param next {Function} callback. parameter passed: err, object having each
     * permission action result
     */
    this.checkPermissionForActions = function (actions, modelId, next) {
        var that = this, perm = {};
        modelId = parseInt(modelId);
        if (!isValidModelId(modelId)) {
            throw new Error("Invalid model id: " + modelId + " :: modelName: " + modelName);
        }

        async.series([
            function (n) {
                Cache.storeByModelId(req.app.set("db"), permissionSchemaKey, modelName, modelId, n);
            } ,
            function (n) {
                var cacheItem = Cache.getCacheItem(permissionSchemaKey, modelId);

                if (cacheItem) {
                    actions.forEach(function (action) {
                        perm[action] = checkPermissionSync(action, userRoles, cacheItem);
                    });
                }
                else {
                    _l("No permissions exists in cache. Pass the callback to hasPermission");
                }
                n();
            }
        ], function (err, result) {
            next(err, !err ? perm : null);
        });
    };

    /**
     * Method check permissions in both sync and async way (if callback is provided)
     * if only action is provided than model permissions is checked (like ADD) but if modelId is also given then
     * model entry permission is checked(like VIEW, can be different for each model entry)
     *
     * @param action {String}
     * @param modelId {Number}
     * @param next {Function}
     * @returns {Object}
     */
    this.hasPermission = function (action, modelId, next) {
        var that = this;
        if (!action || !modelId || !_.isString(action) || !_.isFunction(next)) {
            throw new Error("Missing arguments.")
        }

        modelId = parseInt(modelId);
        if (!isValidModelId(modelId)) {
            throw new Error("Invalid model id: " + modelId + " :: modelName: " + modelName);
        }

        var process = function () {
            var cacheItem = Cache.getCacheItem(permissionSchemaKey, modelId);

            if (cacheItem) {
                return checkPermissionSync(action, userRoles, cacheItem);
            }
            else {
                _l("No permissions exists in cache. Pass the callback to hasPermission");
            }
            return;
        };

        Cache.storeByModelId(req.app.set("db"), permissionSchemaKey, modelName, modelId, function (err, done) {
            if (err) {
                return next(err);
            }
            var p;
            if (done) {
                p = process();
                if (p.isAuthorized === false) {
                    err = getPermissionError(action);
                }
            }
            next(err, p);
        });
    }
}
539307
private void requestPermissionsToSystem(Collection<String> permissions) {
    if (!isShowingNativeDialog.get()) {
      androidPermissionService.requestPermissions(activity,
          permissions.toArray(new String[permissions.size()]), PERMISSIONS_REQUEST_CODE);
    }
    isShowingNativeDialog.set(true);
  }