/** * Determines if redirect may be performed. * * @param Request $request * The current request object. * @param string $route_name * The current route name. * * @return bool * TRUE if redirect may be performed. */ public function canRedirect(Request $request, $route_name = NULL) { $can_redirect = TRUE; if (isset($route_name)) { $route = $this->routeProvider->getRouteByName($route_name); if ($this->config->get('access_check')) { // Do not redirect if is a protected page. $can_redirect &= $this->accessManager->check($route, $request, $this->account); } } else { $route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT); } if (strpos($request->getScriptName(), 'index.php') === FALSE) { // Do not redirect if the root script is not /index.php. $can_redirect = FALSE; } elseif (!($request->isMethod('GET') || $request->isMethod('HEAD'))) { // Do not redirect if this is other than GET request. $can_redirect = FALSE; } elseif ($this->state->get('system.maintenance_mode') || defined('MAINTENANCE_MODE')) { // Do not redirect in offline or maintenance mode. $can_redirect = FALSE; } elseif ($this->config->get('ignore_admin_path') && isset($route)) { // Do not redirect on admin paths. $can_redirect &= !(bool) $route->getOption('_admin_route'); } return $can_redirect; }
/** * {@inheritdoc} */ public function render($empty = FALSE) { $account = \Drupal::currentUser(); if (!$empty || !empty($this->options['empty'])) { $element = array('#theme' => 'links', '#links' => array(array('href' => 'node/add', 'title' => $this->t('Add content'))), '#access' => $this->accessManager->checkNamedRoute('node.add_page', array(), $account)); return $element; } return array(); }
/** * Checks access to the route. * * @param string $route_name * The current route name. * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return bool * TRUE if access is granted. */ public function canRedirect($route_name, Request $request) { $do_redirect = TRUE; /** @var \Symfony\Component\Routing\Route $route */ $route = $this->routeProvider->getRouteByName($route_name); if ($this->config->get('access_check')) { $do_redirect &= $this->accessManager->check($route, $request, $this->account); } if ($this->config->get('ignore_admin_path')) { $do_redirect &= !(bool) $route->getOption('_admin_route'); } return $do_redirect; }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) { switch ($operation) { case 'view': // There is no direct view. return FALSE; case 'update': // If there is a URL, this is an external link so always accessible. return $account->hasPermission('administer menu') && ($entity->getUrl() || $this->accessManager->checkNamedRoute($entity->getRouteName(), $entity->getRouteParameters(), $account)); case 'delete': return !$entity->isNew() && $account->hasPermission('administer menu'); } }
/** * {@inheritdoc} */ public function isValid($path) { // External URLs and the front page are always valid. if ($path == '<front>' || UrlHelper::isExternal($path)) { return TRUE; } // Check the routing system. $collection = $this->routeProvider->getRoutesByPattern('/' . $path); if ($collection->count() == 0) { return FALSE; } $request = RequestHelper::duplicate($this->requestStack->getCurrentRequest(), '/' . $path); $request->attributes->set('_system_path', $path); // We indicate that a menu administrator is running the menu access check. $request->attributes->set('_menu_admin', TRUE); // Attempt to match this path to provide a fully built request to the // access checker. try { $request->attributes->add($this->requestMatcher->matchRequest($request)); } catch (ParamNotConvertedException $e) { return FALSE; } // Consult the access manager. $routes = $collection->all(); $route = reset($routes); return $this->accessManager->check($route, $request, $this->account); }
/** * Tests the checkAccess() tree manipulator. * * @covers ::checkAccess */ public function testCheckAccess() { // Those menu links that are non-external will have their access checks // performed. 8 routes, but 1 is external, 2 already have their 'access' // property set, and 1 is a child if an inaccessible menu link, so only 4 // calls will be made. $this->accessManager->expects($this->exactly(4))->method('checkNamedRoute')->will($this->returnValueMap(array(array('example1', array(), $this->currentUser, NULL, FALSE), array('example2', array('foo' => 'bar'), $this->currentUser, NULL, TRUE), array('example3', array('baz' => 'qux'), $this->currentUser, NULL, FALSE), array('example5', array(), $this->currentUser, NULL, TRUE)))); $this->mockTree(); $this->originalTree[5]->subtree[7]->access = TRUE; $this->originalTree[8]->access = FALSE; $tree = $this->defaultMenuTreeManipulators->checkAccess($this->originalTree); // Menu link 1: route without parameters, access forbidden, hence removed. $this->assertFalse(array_key_exists(1, $tree)); // Menu link 2: route with parameters, access granted. $element = $tree[2]; $this->assertTrue($element->access); // Menu link 3: route with parameters, access forbidden, hence removed, // including its children. $this->assertFalse(array_key_exists(3, $tree[2]->subtree)); // Menu link 4: child of menu link 3, which already is removed. $this->assertSame(array(), $tree[2]->subtree); // Menu link 5: no route name, treated as external, hence access granted. $element = $tree[5]; $this->assertTrue($element->access); // Menu link 6: external URL, hence access granted. $element = $tree[6]; $this->assertTrue($element->access); // Menu link 7: 'access' already set. $element = $tree[5]->subtree[7]; $this->assertTrue($element->access); // Menu link 8: 'access' already set, to FALSE, hence removed. $this->assertFalse(array_key_exists(8, $tree)); }
/** * Gets the render array for all local tasks. * * @param string $current_route_name * The route for which to make renderable local tasks. * * @return array * A render array as expected by theme_menu_local_tasks. */ public function getTasksBuild($current_route_name) { $tree = $this->getLocalTasksForRoute($current_route_name); $build = array(); // Collect all route names. $route_names = array(); foreach ($tree as $instances) { foreach ($instances as $child) { $route_names[] = $child->getRouteName(); } } // Pre-fetch all routes involved in the tree. This reduces the number // of SQL queries that would otherwise be triggered by the access manager. $routes = $route_names ? $this->routeProvider->getRoutesByNames($route_names) : array(); $request = $this->requestStack->getCurrentRequest(); foreach ($tree as $level => $instances) { foreach ($instances as $plugin_id => $child) { $route_name = $child->getRouteName(); $route_parameters = $child->getRouteParameters($request); // Find out whether the user has access to the task. $access = $this->accessManager->checkNamedRoute($route_name, $route_parameters, $this->account); if ($access) { $active = $this->isRouteActive($current_route_name, $route_name, $route_parameters); // The plugin may have been set active in getLocalTasksForRoute() if // one of its child tabs is the active tab. $active = $active || $child->getActive(); // @todo It might make sense to use link render elements instead. $link = array('title' => $this->getTitle($child), 'route_name' => $route_name, 'route_parameters' => $route_parameters, 'localized_options' => $child->getOptions($request)); $build[$level][$plugin_id] = array('#theme' => 'menu_local_task', '#link' => $link, '#active' => $active, '#weight' => $child->getWeight(), '#access' => $access); } } } return $build; }
/** * Finds all local actions that appear on a named route. * * @param string $route_appears * The route name for which to find local actions. * * @return array * An array of link render arrays. */ public function getActionsForRoute($route_appears) { if (!isset($this->instances[$route_appears])) { $route_names = array(); $this->instances[$route_appears] = array(); // @todo - optimize this lookup by compiling or caching. foreach ($this->getDefinitions() as $plugin_id => $action_info) { if (in_array($route_appears, $action_info['appears_on'])) { $plugin = $this->createInstance($plugin_id); $route_names[] = $plugin->getRouteName(); $this->instances[$route_appears][$plugin_id] = $plugin; } } // Pre-fetch all the action route objects. This reduces the number of SQL // queries that would otherwise be triggered by the access manager. if (!empty($route_names)) { $this->routeProvider->getRoutesByNames($route_names); } } $links = array(); $request = $this->requestStack->getCurrentRequest(); foreach ($this->instances[$route_appears] as $plugin_id => $plugin) { $route_name = $plugin->getRouteName(); $route_parameters = $plugin->getRouteParameters($request); $links[$plugin_id] = array('#theme' => 'menu_local_action', '#link' => array('title' => $this->getTitle($plugin), 'route_name' => $route_name, 'route_parameters' => $route_parameters, 'localized_options' => $plugin->getOptions($request)), '#access' => $this->accessManager->checkNamedRoute($route_name, $route_parameters, $this->account), '#weight' => $plugin->getWeight()); } return $links; }
/** * Adds a default access check service to the container and the access manager. */ protected function setupAccessChecker() { $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver, $this->requestStack); $this->accessManager->setContainer($this->container); $access_check = new DefaultAccessCheck(); $this->container->register('test_access_default', $access_check); $this->accessManager->addCheckService('test_access_default', 'access', array('_access')); }
/** * Tests that if access is granted, AccessSubscriber will not throw an exception. */ public function testAccessSubscriberDoesNotAlterRequestIfAccessManagerGrantsAccess() { $this->parameterBag->expects($this->once())->method('has')->with(RouteObjectInterface::ROUTE_OBJECT)->will($this->returnValue(TRUE)); $this->parameterBag->expects($this->once())->method('get')->with(RouteObjectInterface::ROUTE_OBJECT)->will($this->returnValue($this->route)); $this->accessManager->expects($this->once())->method('check')->with($this->equalTo($this->route))->will($this->returnValue(TRUE)); $subscriber = new AccessSubscriber($this->accessManager, $this->currentUser); // We're testing that no exception is thrown in this case. There is no // return. $subscriber->onKernelRequestAccessCheck($this->event); }
/** * Checks access for one menu link instance. * * @param \Drupal\Core\Menu\MenuLinkInterface $instance * The menu link instance. * * @return bool * TRUE if the current user can access the link, FALSE otherwise. */ protected function menuLinkCheckAccess(MenuLinkInterface $instance) { // Use the definition here since that's a lot faster than creating a Url // object that we don't need. $definition = $instance->getPluginDefinition(); // 'url' should only be populated for external links. if (!empty($definition['url']) && empty($definition['route_name'])) { $access = TRUE; } else { $access = $this->accessManager->checkNamedRoute($definition['route_name'], $definition['route_parameters'], $this->account); } return $access; }
/** * Verifies that the current user can access the requested path. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The Event to process. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * Thrown when the access got denied. */ public function onKernelRequestAccessCheck(GetResponseEvent $event) { $request = $event->getRequest(); // The controller is being handled by the HTTP kernel, so add an attribute // to tell us this is the controller request. $request->attributes->set('_controller_request', TRUE); if (!$request->attributes->has(RouteObjectInterface::ROUTE_OBJECT)) { // If no Route is available it is likely a static resource and access is // handled elsewhere. return; } // Wrap this in a try/catch to ensure the '_controller_request' attribute // can always be removed. try { $access = $this->accessManager->check($request->attributes->get(RouteObjectInterface::ROUTE_OBJECT), $request, $this->currentUser); } catch (\Exception $e) { $request->attributes->remove('_controller_request'); throw $e; } $request->attributes->remove('_controller_request'); if (!$access) { throw new AccessDeniedHttpException(); } }
/** * {@inheritdoc} */ public function getContextualLinksArrayByGroup($group_name, array $route_parameters, array $metadata = array()) { $links = array(); $request = $this->requestStack->getCurrentRequest(); foreach ($this->getContextualLinkPluginsByGroup($group_name) as $plugin_id => $plugin_definition) { /** @var $plugin \Drupal\Core\Menu\ContextualLinkInterface */ $plugin = $this->createInstance($plugin_id); $route_name = $plugin->getRouteName(); // Check access. if (!$this->accessManager->checkNamedRoute($route_name, $route_parameters, $this->account)) { continue; } $links[$plugin_id] = array('route_name' => $route_name, 'route_parameters' => $route_parameters, 'title' => $plugin->getTitle($request), 'weight' => $plugin->getWeight(), 'localized_options' => $plugin->getOptions(), 'metadata' => $metadata); } $this->moduleHandler->alter('contextual_links', $links, $group_name, $route_parameters); return $links; }
/** * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { $links = array(); // General path-based breadcrumbs. Use the actual request path, prior to // resolving path aliases, so the breadcrumb can be defined by simply // creating a hierarchy of path aliases. $path = trim($this->context->getPathInfo(), '/'); $path_elements = explode('/', $path); $exclude = array(); // Don't show a link to the front-page path. $front = $this->config->get('page.front'); $exclude[$front] = TRUE; // /user is just a redirect, so skip it. // @todo Find a better way to deal with /user. $exclude['user'] = TRUE; while (count($path_elements) > 1) { array_pop($path_elements); // Copy the path elements for up-casting. $route_request = $this->getRequestForPath(implode('/', $path_elements), $exclude); if ($route_request) { $route_name = $route_request->attributes->get(RouteObjectInterface::ROUTE_NAME); // Note that the parameters don't really matter here since we're // passing in the request which already has the upcast attributes. $parameters = array(); $access = $this->accessManager->checkNamedRoute($route_name, $parameters, $this->currentUser, $route_request); if ($access) { $title = $this->titleResolver->getTitle($route_request, $route_request->attributes->get(RouteObjectInterface::ROUTE_OBJECT)); } if ($access) { if (!isset($title)) { // Fallback to using the raw path component as the title if the // route is missing a _title or _title_callback attribute. $title = str_replace(array('-', '_'), ' ', Unicode::ucfirst(end($path_elements))); } // @todo Replace with a #type => link render element so that the alter // hook can work with the actual data. $links[] = $this->l($title, $route_request->attributes->get(RouteObjectInterface::ROUTE_NAME), $route_request->attributes->get('_raw_variables')->all(), array('html' => TRUE)); } } } if ($path && $path != $front) { // Add the Home link, except for the front page. $links[] = $this->l($this->t('Home'), '<front>'); } return array_reverse($links); }
/** * {@inheritdoc} */ protected function renderLink(EntityInterface $entity, ResultRow $values) { if (empty($entity)) { return; } // Check access when we pull up the user account so we know // if the user has made the contact page available. if (!$this->accessManager->checkNamedRoute('contact.personal_page', array('user' => $entity->id()), $this->currentUser())) { return; } $this->options['alter']['make_link'] = TRUE; $this->options['alter']['path'] = "user/{$entity->id()}/contact"; $title = t('Contact %user', array('%user' => $entity->name->value)); $this->options['alter']['attributes'] = array('title' => $title); if (!empty($this->options['text'])) { return $this->options['text']; } else { return $title; } }
/** * Tests the access checking of the getContextualLinksArrayByGroup method. * * @see \Drupal\Core\Menu\ContextualLinkManager::getContextualLinksArrayByGroup() */ public function testGetContextualLinksArrayByGroupAccessCheck() { $definitions = array('test_plugin1' => array('id' => 'test_plugin1', 'class' => '\\Drupal\\Core\\Menu\\ContextualLinkDefault', 'title' => 'Plugin 1', 'weight' => 0, 'group' => 'group1', 'route_name' => 'test_route', 'options' => array()), 'test_plugin2' => array('id' => 'test_plugin2', 'class' => '\\Drupal\\Core\\Menu\\ContextualLinkDefault', 'title' => 'Plugin 2', 'weight' => 2, 'group' => 'group1', 'route_name' => 'test_route2', 'options' => array('key' => 'value'))); $this->pluginDiscovery->expects($this->once())->method('getDefinitions')->will($this->returnValue($definitions)); $this->accessManager->expects($this->any())->method('checkNamedRoute')->will($this->returnValueMap(array(array('test_route', array('key' => 'value'), $this->account, NULL, TRUE), array('test_route2', array('key' => 'value'), $this->account, NULL, FALSE)))); // Set up mocking of the plugin factory. $map = array(); foreach ($definitions as $plugin_id => $definition) { $plugin = $this->getMock('Drupal\\Core\\Menu\\ContextualLinkInterface'); $plugin->expects($this->any())->method('getRouteName')->will($this->returnValue($definition['route_name'])); $plugin->expects($this->any())->method('getTitle')->will($this->returnValue($definition['title'])); $plugin->expects($this->any())->method('getWeight')->will($this->returnValue($definition['weight'])); $plugin->expects($this->any())->method('getOptions')->will($this->returnValue($definition['options'])); $map[] = array($plugin_id, array(), $plugin); } $this->factory->expects($this->any())->method('createInstance')->will($this->returnValueMap($map)); $result = $this->contextualLinkManager->getContextualLinksArrayByGroup('group1', array('key' => 'value')); // Ensure that access checking was respected. $this->assertTrue(isset($result['test_plugin1'])); $this->assertFalse(isset($result['test_plugin2'])); }
/** * Validates the form, both on the menu link edit and content menu link form. * * $form is not currently used, but passed here to match the normal form * validation method signature. * * @param array $form * A nested array form elements comprising the form. * @param array $form_state * An associative array containing the current state of the form. */ protected function doValidate(array $form, array &$form_state) { $extracted = $this->extractUrl($form_state['values']['url']); // If both URL and route_name are empty, the entered value is not valid. $valid = FALSE; if ($extracted['url']) { // This is an external link. $valid = TRUE; } elseif ($extracted['route_name']) { // Users are not allowed to add a link to a page they cannot access. $valid = $this->accessManager->checkNamedRoute($extracted['route_name'], $extracted['route_parameters'], $this->account); } if (!$valid) { $this->setFormError('url', $form_state, $this->t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $form_state['values']['url']))); } elseif ($extracted['route_name']) { // The user entered a Drupal path. $normal_path = $this->pathAliasManager->getPathByAlias($extracted['path']); if ($extracted['path'] != $normal_path) { drupal_set_message($this->t('The menu system stores system paths only, but will use the URL alias for display. %link_path has been stored as %normal_path', array('%link_path' => $extracted['path'], '%normal_path' => $normal_path))); } } }
/** * Tests that an access checker throws an exception for not allowed values. * * @dataProvider providerCheckException * * @expectedException \Drupal\Core\Access\AccessException */ public function testCheckException($return_value) { $route_provider = $this->getMock('Drupal\\Core\\Routing\\RouteProviderInterface'); // Setup a test route for each access configuration. $requirements = array('_test_incorrect_value' => 'TRUE'); $options = array('_access_checks' => array('test_incorrect_value')); $route = new Route('', array(), $requirements, $options); $route_provider->expects($this->any())->method('getRouteByName')->will($this->returnValue($route)); $this->paramConverter = $this->getMock('Drupal\\Core\\ParamConverter\\ParamConverterManagerInterface'); $this->paramConverter->expects($this->any())->method('convert')->will($this->returnValue(array())); $this->setupAccessArgumentsResolverFactory(); $container = new ContainerBuilder(); // Register a service that will return an incorrect value. $access_check = $this->getMock('Drupal\\Tests\\Core\\Access\\TestAccessCheckInterface'); $access_check->expects($this->any())->method('access')->will($this->returnValue($return_value)); $container->set('test_incorrect_value', $access_check); $access_manager = new AccessManager($route_provider, $this->paramConverter, $this->argumentsResolverFactory, $this->currentUser, $this->checkProvider); $this->checkProvider->setContainer($container); $this->checkProvider->addCheckService('test_incorrect_value', 'access'); $access_manager->checkNamedRoute('test_incorrect_value', array(), $this->account); }
/** * Language translations overview page for a configuration name. * * @param \Symfony\Component\HttpFoundation\Request $request * Page request object. * @param string $plugin_id * The plugin ID of the mapper. * * @return array * Page render array. */ public function itemPage(Request $request, $plugin_id) { /** @var \Drupal\config_translation\ConfigMapperInterface $mapper */ $mapper = $this->configMapperManager->createInstance($plugin_id); $mapper->populateFromRequest($request); $page = array(); $page['#title'] = $this->t('Translations for %label', array('%label' => $mapper->getTitle())); // It is possible the original language this configuration was saved with is // not on the system. For example, the configuration shipped in English but // the site has no English configured. Represent the original language in // the table even if it is not currently configured. $languages = $this->languageManager->getLanguages(); $original_langcode = $mapper->getLangcode(); if (!isset($languages[$original_langcode])) { $language_name = $this->languageManager->getLanguageName($original_langcode); if ($original_langcode == 'en') { $language_name = $this->t('Built-in English'); } // Create a dummy language object for this listing only. $languages[$original_langcode] = new Language(array('id' => $original_langcode, 'name' => $language_name)); } // We create a fake request object to pass into // ConfigMapperInterface::populateFromRequest() for the different languages. // Creating a separate request for each language and route is neither easily // possible nor performant. $fake_request = $request->duplicate(); $page['languages'] = array('#type' => 'table', '#header' => array($this->t('Language'), $this->t('Operations'))); foreach ($languages as $language) { $langcode = $language->id; // This is needed because // ConfigMapperInterface::getAddRouteParameters(), for example, // needs to return the correct language code for each table row. $fake_request->attributes->set('langcode', $langcode); $mapper->populateFromRequest($fake_request); // Prepare the language name and the operations depending on whether this // is the original language or not. if ($langcode == $original_langcode) { $language_name = '<strong>' . $this->t('@language (original)', array('@language' => $language->name)) . '</strong>'; // Check access for the path/route for editing, so we can decide to // include a link to edit or not. $route_request = $this->getRequestForPath($request, $mapper->getBasePath()); $edit_access = FALSE; if (!empty($route_request)) { $route_name = $route_request->attributes->get(RouteObjectInterface::ROUTE_NAME); // Note that the parameters don't really matter here since we're // passing in the request which already has the upcast attributes. $parameters = array(); $edit_access = $this->accessManager->checkNamedRoute($route_name, $parameters, $this->account, $route_request); } // Build list of operations. $operations = array(); if ($edit_access) { $operations['edit'] = array('title' => $this->t('Edit'), 'route_name' => $mapper->getBaseRouteName(), 'route_parameters' => $mapper->getBaseRouteParameters(), 'query' => array('destination' => $mapper->getOverviewPath())); } } else { $language_name = $language->name; $operations = array(); // If no translation exists for this language, link to add one. if (!$mapper->hasTranslation($language)) { $operations['add'] = array('title' => $this->t('Add'), 'route_name' => $mapper->getAddRouteName(), 'route_parameters' => $mapper->getAddRouteParameters()); } else { // Otherwise, link to edit the existing translation. $operations['edit'] = array('title' => $this->t('Edit'), 'route_name' => $mapper->getEditRouteName(), 'route_parameters' => $mapper->getEditRouteParameters()); $operations['delete'] = array('title' => $this->t('Delete'), 'route_name' => $mapper->getDeleteRouteName(), 'route_parameters' => $mapper->getDeleteRouteParameters()); } } $page['languages'][$langcode]['language'] = array('#markup' => $language_name); $page['languages'][$langcode]['operations'] = array('#type' => 'operations', '#links' => $operations); } return $page; }
/** * Apply access checks to routes. * * @param \Drupal\Core\Routing\RouteBuildEvent $event * The event to process. */ public function onRoutingRouteAlterSetAccessCheck(RouteBuildEvent $event) { $this->accessManager->setChecks($event->getRouteCollection()); }
/** * Setup the access manager to always return TRUE. */ public function setupAccessManagerWithTrue() { $this->accessManager->expects($this->any())->method('checkNamedRoute')->will($this->returnValue(TRUE)); }