Sets up an access controller that will be provided to any distributed objects created on the
server. The controllers can subsequently be overridden if desired, but a default controller
is useful for implementing basic access control policies.
161285
public void setDefaultAccessController (AccessController controller)
    {
        AccessController oldDefault = _defaultController;
        _defaultController = controller;

        // switch all objects from the old default (null, usually) to the new default.
        for (DObject obj : _objects.values()) {
            if (oldDefault == obj.getAccessController()) {
                obj.setAccessController(controller);
            }
        }
    }
927349
def controller(self):
        """"""
        if hasattr(self, 'controllers'):
            if len(self.controllers) > 1:
                # in the future, we should support more controllers
                raise TypeError("Only one controller per account.")
            return self.controllers[0]
        raise AttributeError("There is no controller assigned.")
338771
function Routing(app) {
	var config, defaultController;

	/**
	 * Find the action function based on controller name and action name.
	 * If no controller but a model is found, the default controller is taken.
	 * @param  {String} controllerName controller name
	 * @param  {String} actionName     action name
	 * @return {Function}              action function
	 */
	function getAction(controllerName, actionName) {
		controllerName = controllerName.camelize();
		var controller = app.controllers[controllerName];
		if (controller === undefined && app.models[controllerName])
			controller = defaultController;

		if (controller)
			return controller[actionName || 'index'];
		else
			return null;
	}

	/**
	 * adds a single route
	 * @param {String} verb           HTTP verb
	 * @param {String} routePath      routing path
	 * @param {String} controllerName controller name
	 * @param {String} actionName     action name
	 */
	function addSingleRoute(verb, routePath, controllerName, actionName) {
		// add controller and action fields to the request
		var reqExtender = function(req, res, next) {
			req.controller = controllerName;
			req.action = actionName || 'index';
			next();
		};

		var params = [routePath, reqExtender];
		params = params.concat(getPolicies(controllerName, actionName));
		params.push(getAction(controllerName, actionName));

		app[verb].apply(app, params);
	}

	/**
	 * gets the policies in effect for a given controller and action
	 * @param  {String} controller
	 * @param  {String} action
	 * @return {Array}            policies
	 */
	function getPolicies(controller, action) {
		var policies = config.policies;
		var currentPolicies = [];
		if (policies[controller] && policies[controller][action]) {
			currentPolicies = policies[controller][action];
		} else if (Object.isString(policies[controller])) {
			currentPolicies = policies[controller];
		} else if (policies[controller] && policies[controller]['*']) {
			currentPolicies = policies[controller]['*'];
		} else if (policies['*']) {
			currentPolicies = policies['*'];
		}

		if (currentPolicies === true) {
			currentPolicies = [];
		}

		if (!Object.isArray(currentPolicies)) {
			currentPolicies = [currentPolicies];
		}

		currentPolicies = currentPolicies.map(function(policy) {
			var policyPath = path.join(config.rootDir, config.paths.policies, policy);
			return require(policyPath);
		});
		return currentPolicies;
	}

	/**
	 * parse the resource route definitions
	 */
	var resourceRouting;
	function parseResourceRoutes() {
		var routes = config.resourceRouting;
		resourceRouting = [];
		for (var route in routes) {
			var parsedRoute = parseRoute(route, routes[route]);
			// if it's a string it defines the action
			if (Object.isString(parsedRoute.target)) {
				parsedRoute.target = {action: parsedRoute.target};
			}
			resourceRouting.push(parsedRoute);
		}
	}

	/**
	 * add a resource route
	 * @param {String} routePath      route path
	 * @param {String} controllerName controller name
	 */
	function addResourceRoute(routePath, controllerName) {
		resourceRouting.forEach(function(route) {
			var actionPath = route.path.replace(':controller', controllerName);
			route.verbs.forEach(function (verb) {
				addSingleRoute(verb, actionPath, controllerName, route.target.action);
			});
		});
	}

	/**
	 * add a static route
	 * @param {String} routePath route path
	 * @param {String} target    target path (relative to the scarab root)
	 */
	function addStaticRoute(routePath, targets) {
		if (!Object.isArray(targets)) {
			targets = [targets];
		}
		targets.forEach(function(target) {
			if (target)
				app.use(routePath, app.middleware.static(path.resolve(config.rootDir, target)));
		});
	}

	function addRedirectRoute(verb, routePath, target) {
		app[verb](routePath, function(req, res) {
			res.redirect(target);
		});
	}

	/**
	 * apply the path policies (for static routes)
	 */
	function applyPathPolicies() {
		var allPolicies = [];
		for (var routePath in config.policies) {
			if (routePath.charAt(0) === '/') {
				var currentPolicies = config.policies[routePath];
				if (currentPolicies === true) {
					currentPolicies = [];
				}
				if (!Object.isArray(currentPolicies)) {
					currentPolicies = [currentPolicies];
				}
				allPolicies.push({route: routePath, policies: currentPolicies});
			}
		}
		allPolicies.forEach(function(pathPolicy) {
			pathPolicy.policies.forEach(function(policy) {
				var policyPath = path.join(config.rootDir, config.paths.policies, policy);
				app.all(pathPolicy.route, require(policyPath));
			});
		});
	}

	/**
	 * parse a route
	 * @param  {String} route  a route definition
	 * @param  {Object} target target definition
	 * @return {Object}        route parsed into verbs, path and target
	 */
	function parseRoute(route, target) {
		var verbs, routePath, routeParts;

		routeParts = route.split(' ');
		if (routeParts.length === 1) {
			verbs = ['all'];
			routePath = routeParts[0];
		} else {
			verbs = routeParts[0].split(',');
			verbs.map(function (verb) {
				return verb.trim().toLowerCase();
			});
			routePath = routeParts[1];
		}
		return {verbs: verbs, path: routePath, target: target};
	}

	/**
	 * initializes all routes
	 */
	function init() {
		config = app.config;

		defaultController = config.defaultControllerFactory(app.models);

		// load controllers
		var controllerDir = path.join(config.rootDir, config.paths.controllers);
		var controllerFiles = fs.readdirSync(controllerDir);
		controllerFiles.forEach(function(controllerFile) {
			var controllerName = controllerFile.substring(0, controllerFile.indexOf('Controller'));
			var controllerDef = require(path.join(controllerDir, controllerFile));
			var controller;
			if (controllerDef.noDefaultActions) {
				controller = controllerDef;
			} else {
				controller = Object.create(defaultController);
				controller = Object.merge(controller, controllerDef);
			}
			app.controllers[controllerName] = controller;
		});

		applyPathPolicies();

		var routes = config.routes,
			parsed = [];

		parseResourceRoutes();

		for (var route in routes) {
			parsed.push(parseRoute(route, routes[route]));
		}

		parsed.forEach(function(route) {
			if(!route.target)
				return;

			if (Object.isString(route.target)) {
				if (route.verbs[0] !== 'static' && route.target.charAt(0) === '/') {
					route.target = {redirect: route.target};
				} else {
					var parts = route.target.split('.');
					if (parts.length === 2) {
						route.target = {controller: parts[0], action: parts[1]};
					}
				}
			}
			if (!Object.isObject(route.target)) {
				route.target = {controller: route.target};
			}

			route.verbs.forEach(function (verb) {
				if (verb === 'resource') {
					addResourceRoute(route.path, route.target.controller);
				} else if (verb === 'static') {
					addStaticRoute(route.path, route.target.controller);
				} else if (route.target.redirect) {
					addRedirectRoute(verb, route.path, route.target.redirect);
				} else {
					addSingleRoute(verb, route.path, route.target.controller, route.target.action);
				}
			});
		});

		if(config.autoRoute) {
			resourceRouting.forEach(function(route) {
				var actionPath = path.join('/', config.autoRoutePath, route.path);
				route.verbs.forEach(function (verb) {
					app[verb](actionPath, function(req, res, next) {
						var controllerName = req.params.controller.singularize();
						var actionName = route.target.action;
						req.controller = controllerName;
						req.action = actionName;

						var action = getAction(controllerName, actionName);
						if (action) {
							var policies = getPolicies(controllerName, actionName);
							if (policies.length > 0) {
								var policyIdx = 0;
								var nextPolicy = function() {
									policyIdx++;
									if (policyIdx < policies.length) {
										policies[policyIdx](req, res, nextPolicy);
									} else {
										action(req, res, next);
									}
								};
								policies[0](req, res, nextPolicy);
							} else {
								action(req, res, next);
							}
						} else {
							next();
						}
					});
				});
			});
		}
	}

	return {
		init: init
	};
}
372751
public function setup()
    {
        if (!$this->_checkRequestType('jsonapi')) {
            return;
        }

        $appClass = Configure::read('App.namespace') . '\Application';

        // If `App\Application` class exists it means Cake 3.3's PSR7 middleware
        // implementation is used and it's too late to register new error handler.
        if (!class_exists($appClass, false)) {
            $this->registerExceptionHandler();
        }
    }
831810
def make_server(
        server_class, handler_class, authorizer_class, filesystem_class,
        host_port, file_access_user=None, **handler_options):
    
    from . import compat
    if isinstance(handler_class, compat.string_type):
        handler_class = import_class(handler_class)

    if isinstance(authorizer_class, compat.string_type):
        authorizer_class = import_class(authorizer_class)

    if isinstance(filesystem_class, compat.string_type):
        filesystem_class = import_class(filesystem_class)

    authorizer = authorizer_class(file_access_user)
    handler = handler_class
    for key, value in handler_options.items():
        setattr(handler, key, value)
    handler.authorizer = authorizer
    if filesystem_class is not None:
        handler.abstracted_fs = filesystem_class
    return server_class(host_port, handler)
294536
protected function createServer(): ResourceServer
    {
        // Init our repositories
        $accessTokenRepository = new AccessTokenRepository(); // instance of AccessTokenRepositoryInterface

        // Path to authorization server's public key
        $publicKeyPath = Environment::getEnv('OAUTH_PUBLIC_KEY_PATH');

        // Relative paths to the web root
        $publicKeyPath = str_replace('{BASE_DIR}', Director::baseFolder(), $publicKeyPath);

        // Setup the authorization server
        return new ResourceServer(
            $accessTokenRepository,
            $publicKeyPath
        );
    }
798935
function(controller, callback) {

            // Add the given name to the controller
            controller.name = name;
            controller.module = module;

            // Set default value on the controller instance
            controller.basePath = self.getBasePath(
                controller, path, module
            );

            // Add the canonical path
            controller.canonicalPath = self.getCanonicalPath(
                path, name, module
            );

            callback(null, controller);
        }
699954
def setup_default_permissions(session, instance):
    
    if instance not in session.new or not isinstance(instance, Entity):
        return

    if not current_app:
        # working outside app_context. Raw object manipulation
        return

    _setup_default_permissions(instance)
249011
function generateGenericControllers(controllers, models) {
        var genericControllers = {},
            genericRoute = [];

        models.forEach(function(model) {
            var persistence = $database.getPersistenceOfModel(model);
            if (null == persistence) {
                throw new Error('');
            }
            var defaultController = {};
            var modelRest = model + "Rest";

            if (controllers.hasOwnProperty(modelRest)) {
                defaultController = controllers[modelRest];
            } else if (controllers.hasOwnProperty(utils.camelizePath(modelRest))) {
                defaultController = controllers[utils.camelizePath(modelRest)];
            }

            var generatorController = persistence.generatorController;

            genericControllers[modelRest] = _.defaults({}, defaultController, generatorController.generate(persistence.repositories[model], true));
            //create
            genericRoute.push({
                method: 'post',
                controller: modelRest,
                action: 'create',
                path: '/' + model
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'createQuery',
                path: '/' + model + '/create'
            });

            //Read
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'index',
                path: '/' + model
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'findById',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'find',
                path: '/' + model + '/find'
            });

            //update
            genericRoute.push({
                method: 'put',
                controller: modelRest,
                action: 'update',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'updateQuery',
                path: '/' + model + '/update/:id'
            });

            //update
            genericRoute.push({
                method: 'delete',
                controller: modelRest,
                action: 'delete',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'delete',
                path: '/' + model + '/delete/:id'
            });

        });

        return [genericControllers, genericRoute]
    }
1028511
def setup(self):
        self.client = self._get_client()
        sg = self._create_isolation_security_group()
        if self.exists is not True:
            acl = self._create_network_acl()
            self._add_network_acl_entries(acl)
            self._add_security_group_rule(sg)
        self._add_security_group_to_instance(sg)

        """"""
        if self.dry_run is not False:
            self._add_security_group_rule(sg)
            self._add_security_group_to_instance(sg)
1002554
public function setupPermissions()
    {
        $app = Application::getFacadeApplication();
        $u = $app->make(\Concrete\Core\User\User::class);
        if ($u->isSuperUser() || ($this->ignorePermissions)) {
            return; // super user always sees everything. no need to limit
        }

        $accessEntities = $u->getUserAccessEntityObjects();
        $peIDs = ['-1'];
        foreach ($accessEntities as $pae) {
            $peIDs[] = $pae->getAccessEntityID();
        }

        $owpae = PageOwnerPermissionAccessEntity::getOrCreate();
        // now we retrieve a list of permission duration object IDs that are attached view_page or view_page_version
        // against any of these access entity objects. We just get'em all.
        $db = $app->make(Connection::class);
        $activePDIDs = [];
        $vpPKID = $db->GetOne('select pkID from PermissionKeys where pkHandle = ?', [$this->viewPagePermissionKeyHandle]);
        /*
        $vpvPKID = $db->GetOne('select pkID from PermissionKeys where pkHandle = \'view_page_versions\'');
        $pdIDs = $db->GetCol("select distinct pdID from PagePermissionAssignments ppa inner join PermissionAccessList pa on ppa.paID = pa.paID where pkID in (?, ?) and pdID > 0", array($vpPKID, $vpvPKID));
        */
        $pdIDs = $db->GetCol("select distinct pdID from PagePermissionAssignments ppa inner join PermissionAccessList pa on ppa.paID = pa.paID where pkID =? and pdID > 0", [$vpPKID]);
        if (count($pdIDs) > 0) {
            // then we iterate through all of them and find any that are active RIGHT NOW
            foreach ($pdIDs as $pdID) {
                $pd = PermissionDuration::getByID($pdID);
                if ($pd->isActive()) {
                    $activePDIDs[] = $pd->getPermissionDurationID();
                }
            }
        }
        $activePDIDs[] = 0;

        if ($this->includeAliases) {
            $cInheritPermissionsFromCID = 'if(p2.cID is null, p1.cInheritPermissionsFromCID, p2.cInheritPermissionsFromCID)';
        } else {
            $cInheritPermissionsFromCID = 'p1.cInheritPermissionsFromCID';
        }

        if ($this->displayOnlyApprovedPages) {
            $now = $app->make('date')->getOverridableNow();
            $nowSql = $db->quote($now);
            $cvIsApproved = " and cv.cvIsApproved = 1 and (cv.cvPublishDate is null or cv.cvPublishDate <= {$nowSql}) and (cv.cvPublishEndDate is null or cv.cvPublishEndDate >= {$nowSql})";
        } else {
            $cvIsApproved = '';
        }

        $uID = 0;
        if ($u->isRegistered()) {
            $uID = $u->getUserID();
        }

        /*
        $this->filter(false, "((select count(cID) from PagePermissionAssignments ppa1 inner join PermissionAccessList pa1 on ppa1.paID = pa1.paID where ppa1.cID = {$cInheritPermissionsFromCID} and pa1.accessType = " . PermissionKey::ACCESS_TYPE_INCLUDE . " and pa1.pdID in (" . implode(',', $activePDIDs) . ")
            and pa1.peID in (" . implode(',', $peIDs) . ") and (if(pa1.peID = " . $owpae->getAccessEntityID() . " and p1.uID <>" . $uID . ", false, true)) and (ppa1.pkID = " . $vpPKID . $cvIsApproved . " or ppa1.pkID = " . $vpvPKID . ")) > 0
            or (p1.cPointerExternalLink !='' AND p1.cPointerExternalLink IS NOT NULL))");
        $this->filter(false, "((select count(cID) from PagePermissionAssignments ppaExclude inner join PermissionAccessList paExclude on ppaExclude.paID = paExclude.paID where ppaExclude.cID = {$cInheritPermissionsFromCID} and accessType = " . PermissionKey::ACCESS_TYPE_EXCLUDE . " and pdID in (" . implode(',', $activePDIDs) . ")
            and paExclude.peID in (" . implode(',', $peIDs) . ") and (if(paExclude.peID = " . $owpae->getAccessEntityID() . " and p1.uID <>" . $uID . ", false, true)) and (ppaExclude.pkID = " . $vpPKID . $cvIsApproved . " or ppaExclude.pkID = " . $vpvPKID . ")) = 0)");
            */

        $this->filter(false, "((select count(cID) from PagePermissionAssignments ppa1 inner join PermissionAccessList pa1 on ppa1.paID = pa1.paID where ppa1.cID = {$cInheritPermissionsFromCID} and pa1.accessType = " . PermissionKey::ACCESS_TYPE_INCLUDE . " and pa1.pdID in (" . implode(',', $activePDIDs) . ")
			and pa1.peID in (" . implode(',', $peIDs) . ") and (if(pa1.peID = " . $owpae->getAccessEntityID() . " and p1.uID <>" . $uID . ", false, true)) and (ppa1.pkID = " . $vpPKID . $cvIsApproved . ")) > 0
			or (p1.cPointerExternalLink !='' AND p1.cPointerExternalLink IS NOT NULL))");
        $this->filter(false, "((select count(cID) from PagePermissionAssignments ppaExclude inner join PermissionAccessList paExclude on ppaExclude.paID = paExclude.paID where ppaExclude.cID = {$cInheritPermissionsFromCID} and accessType = " . PermissionKey::ACCESS_TYPE_EXCLUDE . " and pdID in (" . implode(',', $activePDIDs) . ")
			and paExclude.peID in (" . implode(',', $peIDs) . ") and (if(paExclude.peID = " . $owpae->getAccessEntityID() . " and p1.uID <>" . $uID . ", false, true)) and (ppaExclude.pkID = " . $vpPKID . $cvIsApproved . ")) = 0)");
    }
940529
function accessControl () {
    // if the query is for specific record(s) by id then the action type
    // is read. for all other queries the action type is list.
    this.action = defined(this.args.where.id) ? 'read' : 'list'
    // if allow override is set then skip access control
    if (this.args.allow) {
        return
    }
    // get global access control instance
    var accessControl = ImmutableAccessControl.getGlobal()
    // add scope of access allowed to args
    this.args.scope = accessControl.allowModelScope({
        action: this.action,
        model: this.model.name,
        session: this.session,
        states: this.accessControlStates(),
    })
    // if scope is undefined then throw access denied error
    if (!defined(this.args.scope)) {
        httpError(403, null, accessControl.audit)
    }
    // if scope is own add access control args
    if (this.args.scope === 'own') {
        this.accessControlOwn(accessControl)
    }
}
1143591
private function initServer()
    {
        $this
            ->setSessionStorage($this->sessionStorage)
            ->setAccessTokenStorage($this->accessTokenStorage)
            ->setClientStorage($this->clientStorage)
            ->setScopeStorage($this->scopeStorage)
        ;
    }
245467
def controller(self):
        

        if hasattr(self, 'controller_id'):
            if len(self.controller_info['controllers']) > 1:
                raise TypeError(
                    'Only one controller per account is supported.'
                )
            return self.controller_id
        raise AttributeError('No controllers assigned to this account.')
1261189
def do_access_control(self):
        """"""
        from abilian.services import get_service

        if current_app.testing and current_app.config.get("NO_LOGIN"):
            # Special case for tests
            user = User.query.get(0)
            login_user(user, force=True)
            return

        state = self.app_state
        user = unwrap(current_user)

        # Another special case for tests
        if current_app.testing and getattr(user, "is_admin", False):
            return

        security = get_service("security")
        user_roles = frozenset(security.get_roles(user))
        endpoint = request.endpoint
        blueprint = request.blueprint

        access_controllers = []
        access_controllers.extend(state.bp_access_controllers.get(None, []))

        if blueprint and blueprint in state.bp_access_controllers:
            access_controllers.extend(state.bp_access_controllers[blueprint])

        if endpoint and endpoint in state.endpoint_access_controllers:
            access_controllers.extend(state.endpoint_access_controllers[endpoint])

        for access_controller in reversed(access_controllers):
            verdict = access_controller(user=user, roles=user_roles)
            if verdict is None:
                continue
            elif verdict is True:
                return
            else:
                if user.is_anonymous:
                    return self.redirect_to_login()
                raise Forbidden()

        # default policy
        if current_app.config.get("PRIVATE_SITE") and user.is_anonymous:
            return self.redirect_to_login()
93934
function initAccessControl (args) {
    // get global access control instance
    var accessControl = ImmutableAccessControl.getGlobal()
    // check for deprecated access control
    if (defined(args.accessControl)) {
        throw new Error('model local accessControl is deprecated')
    }
    // check for deprecated access model if passed
    if (defined(args.accessModel)) {
        throw new Error('accessModel is deprecated')
    }
    // set access id column if passed
    if (args.accessIdName) {
        // set access id name
        this.accessIdName = args.accessIdName
        // get column spec
        var spec = this.columns[this.accessIdName]
        // column for access id name must exist
        this.assert(defined(spec), `column not defined for accessIdName ${args.accessIdName}`)
        // column must be id
        this.assert(spec.type === 'id', `accessIdName column ${args.accessIdName} must have type id`)
        // set access id name with access control provider
        accessControl.setAccessIdName(this.name, this.accessIdName)
    }
    // set default access id name o model
    else {
        // default is accountId if model has an account id
        this.accessIdName = this.defaultColumnsInverse.accountId ? 'accountId' : undefined
    }
    // if rules not passed skip adding
    if (!defined(args.accessControlRules)) {
        return
    }
    // require access control rules to be array
    this.assert(Array.isArray(args.accessControlRules), 'accessControlRules must be array')
    // add each access control rule
    _.each(args.accessControlRules, accessControlRule => {
        // if rule is a string then it is for `all` role
        if (typeof accessControlRule === 'string') {
            // prepend model:<modelName>: to rule
            accessControlRule = `model:${this.name}:${accessControlRule}`
            // add rule with all role
            accessControl.setRule(['all', accessControlRule], true)
        }
        // otherwise must be array with role(s) and rule as last element
        else if (Array.isArray(accessControlRule)) {
            // get index of last element
            var lastIdx = accessControlRule.length - 1
            // prepend model:<modelName>: to rule
            accessControlRule[lastIdx] = `model:${this.name}:${accessControlRule[lastIdx]}`
            // add rule
            accessControl.setRule(accessControlRule, true)
        }
        // error
        else {
            throw this.error('string or array required for accessControlRules element')
        }
    })
}
1277883
private function createControllerDefinition()
    {
        $id = $this->getServiceId('controller');
        if (!$this->container->has($id)) {
            $definition = new Definition($this->getServiceClass('controller'));
            $definition
                ->addMethodCall('setConfiguration', [new Reference($this->getServiceId('configuration'))])
                ->addMethodCall('setContainer', [new Reference('service_container')])
            ;
            $this->container->setDefinition($id, $definition);
        }
    }