/** * Redirects login attempts on already-logged-in session to the destination. */ public function onRespond(FilterResponseEvent $event) { // Return early in most cases. if ($event->getRequest()->getMethod() !== 'POST') { return; } if (!$this->currentUser->isAuthenticated()) { return; } if (!$event->isMasterRequest()) { return; } if (!$event->getRequest()->query->has('destination')) { return; } if ($event->getResponse() instanceof RedirectResponse) { return; } // There has to be a better way to figure out if we landed on the 403/404 page. $page_403 = $this->configFactory->get('system.site')->get('page.403'); $page_404 = $this->configFactory->get('system.site')->get('page.404'); $path = $this->currentPath->getPath(); $route = $this->currentRouteMatch->getRouteName(); if ($route == 'system.403' || $page_403 && $path == $page_403 || $route == 'system.404' || $page_404 && $path == $page_404) { // RedirectResponseSubscriber will convert to absolute URL for us. $event->setResponse(new RedirectResponse($this->redirectDestination->get(), RedirectResponse::HTTP_SEE_OTHER)); } }
/** * Determine whether the page is configured to be offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); $path = $request->attributes->get('_system_path'); if ($this->maintenanceMode->applies($route_match)) { // If the site is offline, log out unprivileged users. if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) { user_logout(); // Redirect to homepage. $event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE]))); return; } } if ($this->account->isAuthenticated()) { if ($path == 'user/login') { // If the user is already logged in, redirect to their profile page. $event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()])); return; } if ($path == 'user/register') { // If the user is already registered, redirect to their edit page. $event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE]))); return; } } }
/** * {@inheritdoc} */ protected function blockAccess(AccountInterface $account) { if ($account->hasPermission('search content')) { return AccessResult::allowed(); } return AccessResult::forbidden(); }
public function access(AccountInterface $account) { if (!$account->id() == 1) { return AccessResult::forbidden(); } return AccessResult::allowed(); }
/** * Tests adding and editing values using metatag. */ public function testMetatag() { // Create a test entity. $edit = ['name[0][value]' => 'Barfoo', 'user_id[0][target_id]' => 'foo (' . $this->adminUser->id() . ')']; $this->drupalPostForm('entity_test/add', $edit, t('Save')); $entities = entity_load_multiple_by_properties('entity_test', ['name' => 'Barfoo']); $this->assertEqual(1, count($entities), 'Entity was saved'); $entity = reset($entities); // Update the Global defaults and test them. $values = array('keywords' => 'Purple monkey dishwasher'); $this->drupalPostForm('admin/structure/metatag_defaults/global', $values, 'Save'); $this->assertText('Saved the Global Metatag defaults.'); $this->drupalGet('entity_test/' . $entity->id()); $elements = $this->cssSelect('meta[name=keywords]'); $this->assertTrue(count($elements) === 1, 'Found keywords metatag from defaults'); $this->assertEqual((string) $elements[0]['content'], $values['keywords'], 'Default keywords applied'); // Tests metatags with urls work. $edit = ['name[0][value]' => 'UrlTags', 'user_id[0][target_id]' => 'foo (' . $this->adminUser->id() . ')', 'field_metatag[0][open_graph][og_url]' => 'http://example.com/foo.html']; $this->drupalPostForm('entity_test/add', $edit, t('Save')); $entities = entity_load_multiple_by_properties('entity_test', ['name' => 'UrlTags']); $this->assertEqual(1, count($entities), 'Entity was saved'); $entity = reset($entities); $this->drupalGet('entity_test/' . $entity->id()); $elements = $this->cssSelect("meta[property='og:url']"); $this->assertTrue(count($elements) === 1, 'Found keywords metatag from defaults'); $this->assertEqual((string) $elements[0]['content'], $edit['field_metatag[0][open_graph][og_url]']); }
/** * {@inheritdoc} */ public function defaultAccess($operation = 'view', AccountInterface $account = NULL) { if ($operation == 'view') { return TRUE; } return $account->hasPermission('create url aliases') || $account->hasPermission('administer url aliases'); }
/** * Checks access to the translation overview for the entity and bundle. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * @param string $entity_type_id * The entity type ID. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(RouteMatchInterface $route_match, AccountInterface $account, $entity_type_id) { /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ $entity = $route_match->getParameter($entity_type_id); if ($entity && $entity->isTranslatable()) { // Get entity base info. $bundle = $entity->bundle(); // Get entity access callback. $definition = $this->entityManager->getDefinition($entity_type_id); $translation = $definition->get('translation'); $access_callback = $translation['content_translation']['access_callback']; $access = call_user_func($access_callback, $entity); if ($access->isAllowed()) { return $access; } // Check "translate any entity" permission. if ($account->hasPermission('translate any entity')) { return AccessResult::allowed()->cachePerPermissions()->inheritCacheability($access); } // Check per entity permission. $permission = "translate {$entity_type_id}"; if ($definition->getPermissionGranularity() == 'bundle') { $permission = "translate {$bundle} {$entity_type_id}"; } return AccessResult::allowedIfHasPermission($account, $permission)->inheritCacheability($access); } // No opinion. return AccessResult::neutral(); }
/** * {@inheritdoc} */ public function log($level, $message, array $context = array()) { // Merge in defaults. $context += array('channel' => $this->channel, 'link' => '', 'user' => NULL, 'uid' => 0, 'request_uri' => '', 'referer' => '', 'ip' => '', 'timestamp' => time()); // Some context values are only available when in a request context. if ($this->requestStack && ($request = $this->requestStack->getCurrentRequest())) { $context['request_uri'] = $request->getUri(); $context['referer'] = $request->headers->get('Referer', ''); $context['ip'] = $request->getClientIP(); try { if ($this->currentUser) { $context['user'] = $this->currentUser; $context['uid'] = $this->currentUser->id(); } } catch (\Exception $e) { // An exception might be thrown if the database connection is not // available or due to another unexpected reason. It is more important // to log the error that we already have so any additional exceptions // are ignored. } } if (is_string($level)) { // Convert to integer equivalent for consistency with RFC 5424. $level = $this->levelTranslation[$level]; } // Call all available loggers. foreach ($this->sortLoggers() as $logger) { $logger->log($level, $message, $context); } }
/** * Adds a cache tag if the 'user.permissions' cache context is present. * * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event * The event to process. */ public function onRespond(FilterResponseEvent $event) { if (!$event->isMasterRequest()) { return; } if (!$this->currentUser->isAnonymous()) { return; } $response = $event->getResponse(); if (!$response instanceof CacheableResponseInterface) { return; } // The 'user.permissions' cache context ensures that if the permissions for // a role are modified, users are not served stale render cache content. // But, when entire responses are cached in reverse proxies, the value for // the cache context is never calculated, causing the stale response to not // be invalidated. Therefore, when varying by permissions and the current // user is the anonymous user, also add the cache tag for the 'anonymous' // role. if (in_array('user.permissions', $response->getCacheableMetadata()->getCacheContexts())) { $per_permissions_response_for_anon = new CacheableMetadata(); $per_permissions_response_for_anon->setCacheTags(['config:user.role.anonymous']); $response->addCacheableDependency($per_permissions_response_for_anon); } }
/** * User object. * * @return \Drupal\moodle\Sql\User */ public function user() { // Static cache of already retrieved user data. $data =& drupal_static(__METHOD__, array()); $user_cid = "moodle-user:{$this->user->id()}"; // If we do not have this user id in the static cache, check {cache_data}. if (!isset($data[$user_cid])) { $cache = $this->cacheBackend->get($user_cid); if ($cache && $cache->data && isset($cache->data[$user_cid])) { $data[$user_cid] = $cache->data[$user_cid]; } } // If nothing in the cache then retrieve it from the database. if (!isset($data[$user_cid])) { $user = new User(); $this->query(); $this->addFields(); $statement = $this->query->execute(); $statement->setFetchMode(\PDO::FETCH_INTO, $user); $data[$user_cid] = $statement->fetch(); // Store the results for a day. $this->cacheBackend->set($user_cid, $data, REQUEST_TIME + 86400); } return $data[$user_cid]; }
/** * Determine whether the page is configured to be offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); $path = $request->attributes->get('_system_path'); if ($this->maintenanceMode->applies($route_match)) { // If the site is offline, log out unprivileged users. if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) { user_logout(); // Redirect to homepage. $event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE]))); return; } if ($this->account->isAnonymous() && $path == 'user') { // Forward anonymous user to login page. $event->setResponse(new RedirectResponse($this->url('user.login', [], ['absolute' => TRUE]))); return; } } if ($this->account->isAuthenticated()) { if ($path == 'user/login') { // If user is logged in, redirect to 'user' instead of giving 403. $event->setResponse(new RedirectResponse($this->url('user.page', [], ['absolute' => TRUE]))); return; } if ($path == 'user/register') { // Authenticated user should be redirected to user edit page. $event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE]))); return; } } }
/** * Redirects on 403 Access Denied kernel exceptions. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The Event to process. */ public function onKernelException(GetResponseEvent $event) { $exception = $event->getException(); if (!$exception instanceof AccessDeniedHttpException) { return; } $config = $this->configFactory->get('r4032login.settings'); $options = array(); $options['query'] = $this->redirectDestination->getAsArray(); $options['absolute'] = TRUE; $code = $config->get('default_redirect_code'); if ($this->currentUser->isAnonymous()) { // Show custom access denied message if set. if ($config->get('display_denied_message')) { $message = $config->get('access_denied_message'); $message_type = $config->get('access_denied_message_type'); drupal_set_message(Xss::filterAdmin($message), $message_type); } // Handle redirection to the login form. $login_route = $config->get('user_login_route'); $url = Url::fromRoute($login_route, array(), $options)->toString(); $response = new RedirectResponse($url, $code); $event->setResponse($response); } else { // Check to see if we are to redirect the user. $redirect = $config->get('redirect_authenticated_users_to'); if ($redirect) { // Custom access denied page for logged in users. $url = Url::fromUserInput($redirect, $options)->toString(); $response = new RedirectResponse($url, $code); $event->setResponse($response); } } }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); $cache_contexts_manager = $this->prophesize(CacheContextsManager::class); $cache_contexts_manager->assertValidTokens()->willReturn(TRUE); $cache_contexts_manager->reveal(); $container = new Container(); $container->set('cache_contexts_manager', $cache_contexts_manager); \Drupal::setContainer($container); $this->viewer = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface'); $this->viewer->expects($this->any())->method('hasPermission')->will($this->returnValue(FALSE)); $this->viewer->expects($this->any())->method('id')->will($this->returnValue(1)); $this->owner = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface'); $this->owner->expects($this->any())->method('hasPermission')->will($this->returnValueMap(array(array('administer users', FALSE), array('change own username', TRUE)))); $this->owner->expects($this->any())->method('id')->will($this->returnValue(2)); $this->admin = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface'); $this->admin->expects($this->any())->method('hasPermission')->will($this->returnValue(TRUE)); $entity_type = $this->getMock('Drupal\\Core\\Entity\\EntityTypeInterface'); $this->accessControlHandler = new UserAccessControlHandler($entity_type); $module_handler = $this->getMock('Drupal\\Core\\Extension\\ModuleHandlerInterface'); $module_handler->expects($this->any())->method('getImplementations')->will($this->returnValue(array())); $this->accessControlHandler->setModuleHandler($module_handler); $this->items = $this->getMockBuilder('Drupal\\Core\\Field\\FieldItemList')->disableOriginalConstructor()->getMock(); $this->items->expects($this->any())->method('defaultAccess')->will($this->returnValue(AccessResult::allowed())); }
/** * {@inheritdoc} */ protected function determineBlockContext() { $current_user = $this->userStorage->load($this->account->id()); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user'))); $context->setContextValue($current_user); $this->addContext('current_user', $context); }
/** * Grants access only to UID 1. * * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(AccountInterface $account) { if ($account->id() == 1) { return AccessResult::allowed()->addCacheContexts(['user']); } return AccessResult::forbidden()->addCacheContexts(['user']); }
/** * {@inheritdoc} * * Cached by role, invalidated whenever permissions change. */ public function generate(AccountInterface $account) { // User 1 is the super user, and can always access all permissions. Use a // different, unique identifier for the hash. if ($account->id() == 1) { return $this->hash('is-super-user'); } $sorted_roles = $account->getRoles(); sort($sorted_roles); $role_list = implode(',', $sorted_roles); $cid = "user_permissions_hash:{$role_list}"; if ($static_cache = $this->static->get($cid)) { return $static_cache->data; } else { $tags = Cache::buildTags('config:user.role', $sorted_roles, '.'); if ($cache = $this->cache->get($cid)) { $permissions_hash = $cache->data; } else { $permissions_hash = $this->doGenerate($sorted_roles); $this->cache->set($cid, $permissions_hash, Cache::PERMANENT, $tags); } $this->static->set($cid, $permissions_hash, Cache::PERMANENT, $tags); } return $permissions_hash; }
/** * Checks translation access for the entity and operation on the given route. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * @param string $source * (optional) For a create operation, the language code of the source. * @param string $target * (optional) For a create operation, the language code of the translation. * @param string $language * (optional) For an update or delete operation, the language code of the * translation being updated or deleted. * @param string $entity_type_id * (optional) The entity type ID. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) { /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ if ($entity = $route_match->getParameter($entity_type_id)) { if ($account->hasPermission('translate any entity')) { return AccessResult::allowed()->cachePerRole(); } $operation = $route->getRequirement('_access_content_translation_manage'); /* @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */ $handler = $this->entityManager->getHandler($entity->getEntityTypeId(), 'translation'); // Load translation. $translations = $entity->getTranslationLanguages(); $languages = $this->languageManager->getLanguages(); switch ($operation) { case 'create': $source_language = $this->languageManager->getLanguage($source) ?: $entity->language(); $target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $is_new_translation = $source_language->getId() != $target_language->getId() && isset($languages[$source_language->getId()]) && isset($languages[$target_language->getId()]) && !isset($translations[$target_language->getId()]); return AccessResult::allowedIf($is_new_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); case 'update': case 'delete': $language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $has_translation = isset($languages[$language->getId()]) && $language->getId() != $entity->getUntranslated()->language()->getId() && isset($translations[$language->getId()]); return AccessResult::allowedIf($has_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); } } // No opinion. return AccessResult::neutral(); }
/** * {@inheritdoc} */ public function onBlockActiveContext(BlockContextEvent $event) { $current_user = $this->userStorage->load($this->account->id()); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user'))); $context->setContextValue($current_user); $event->setContext('user.current_user', $context); }
/** * Checks access to the given user's contact page. * * @param \Drupal\user\UserInterface $user * The user being contacted. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return string * A \Drupal\Core\Access\AccessInterface constant value. */ public function access(UserInterface $user, AccountInterface $account) { $contact_account = $user; // Anonymous users cannot have contact forms. if ($contact_account->isAnonymous()) { return static::DENY; } // Users may not contact themselves. if ($account->id() == $contact_account->id()) { return static::DENY; } // User administrators should always have access to personal contact forms. if ($account->hasPermission('administer users')) { return static::ALLOW; } // If requested user has been blocked, do not allow users to contact them. if ($contact_account->isBlocked()) { return static::DENY; } // If the requested user has disabled their contact form, do not allow users // to contact them. $account_data = $this->userData->get('contact', $contact_account->id(), 'enabled'); if (isset($account_data) && empty($account_data)) { return static::DENY; } else { if (!$this->configFactory->get('contact.settings')->get('user_default_enabled')) { return static::DENY; } } return $account->hasPermission('access user contact forms') ? static::ALLOW : static::DENY; }
/** * {@inheritdoc} */ function render(ResultRow $values) { // Ensure Disqus comments are available on the entity and user has access to edit this entity. $entity = $this->getEntity($values); if (!$entity) { return; } $field = $this->disqusManager->getFields($entity->getEntityTypeId()); if (!$entity->hasField(key($field))) { return; } if ($entity->get(key($field))->status && $this->currentUser->hasPermission('view disqus comments')) { // Build a renderable array for the link. $links['disqus_comments_num'] = array('title' => t('Comments'), 'url' => $entity->urlInfo(), 'fragment' => 'disqus_thread', 'attributes' => array('data-disqus-identifier' => "{$entity->getEntityTypeId()}/{$entity->id()}")); $content = array('#theme' => 'links', '#links' => $links, '#attributes' => array('class' => array('links', 'inline'))); /** * This attaches disqus.js specified in the disqus.libraries.yml file, * which will look for the DOM variable disqusComments which is set below. * When found, the disqus javascript api replaces the html element with * the attribute: "data-disqus-identifier" and replaces the element with * the number of comments on the entity. */ $content['#attached']['library'][] = 'disqus/disqus'; $content['#attached']['drupalSettings']['disqusComments'] = $this->config->get('disqus_domain'); return $content; } }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) { if ($operation == 'delete' && $entity->getFieldStorageDefinition()->isLocked()) { return FALSE; } return $account->hasPermission('administer ' . $entity->entity_type . ' fields'); }
/** * {@inheritdoc} */ public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) { $build = parent::view($node, $view_mode, $langcode); foreach ($node->uriRelationships() as $rel) { $url = $node->toUrl($rel); // Add link relationships if the user is authenticated or if the anonymous // user has access. Access checking must be done for anonymous users to // avoid traffic to inaccessible pages from web crawlers. For // authenticated users, showing the links in HTML head does not impact // user experience or security, since the routes are access checked when // visited and only visible via view source. This prevents doing // potentially expensive and hard to cache access checks on every request. // This means that the page will vary by user.permissions. We also rely on // the access checking fallback to ensure the correct cacheability // metadata if we have to check access. if ($this->currentUser->isAuthenticated() || $url->access($this->currentUser)) { // Set the node path as the canonical URL to prevent duplicate content. $build['#attached']['html_head_link'][] = array(array('rel' => $rel, 'href' => $url->toString()), TRUE); } if ($rel == 'canonical') { // Set the non-aliased canonical path as a default shortlink. $build['#attached']['html_head_link'][] = array(array('rel' => 'shortlink', 'href' => $url->setOption('alias', TRUE)->toString()), TRUE); } } // Given this varies by $this->currentUser->isAuthenticated(), add a cache // context based on the anonymous role. $build['#cache']['contexts'][] = 'user.roles:anonymous'; return $build; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->configFactory->get('examples.cron'); $form['status'] = ['#type' => 'details', '#title' => $this->t('Cron status information'), '#open' => TRUE]; $form['status']['intro'] = ['#type' => 'item', '#markup' => $this->t('The cron example demonstrates hook_cron() and hook_queue_info() processing. If you have administrative privileges you can run cron from this page and see the results.')]; $next_execution = $config->get('next_execution'); $next_execution = !empty($next_execution) ? $next_execution : REQUEST_TIME; $args = ['%time' => date_iso8601($config->get('next_execution')), '%seconds' => $next_execution - REQUEST_TIME]; $form['status']['last'] = ['#type' => 'item', '#markup' => $this->t('cron_example_cron() will next execute the first time cron runs after %time (%seconds seconds from now)', $args)]; if ($this->currentUser->hasPermission('administer site configuration')) { $form['cron_run'] = ['#type' => 'details', '#title' => $this->t('Run cron manually'), '#open' => TRUE]; $form['cron_run']['cron_reset'] = ['#type' => 'checkbox', '#title' => $this->t('Run cron_example\'s cron regardless of whether interval has expired.'), '#default_value' => FALSE]; $form['cron_run']['cron_trigger']['actions'] = ['#type' => 'actions']; $form['cron_run']['cron_trigger']['actions']['sumbit'] = ['#type' => 'submit', '#value' => $this->t('Run cron now'), '#submit' => [[$this, 'cronRun']]]; } $form['cron_queue_setup'] = ['#type' => 'details', '#title' => $this->t('Cron queue setup (for hook_cron_queue_info(), etc.)'), '#open' => TRUE]; $queue_1 = $this->queue->get('cron_example_queue_1'); $queue_2 = $this->queue->get('cron_example_queue_2'); $args = ['%queue_1' => $queue_1->numberOfItems(), '%queue_2' => $queue_2->numberOfItems()]; $form['cron_queue_setup']['current_cron_queue_status'] = ['#type' => 'item', '#markup' => $this->t('There are currently %queue_1 items in queue 1 and %queue_2 items in queue 2', $args)]; $form['cron_queue_setup']['num_items'] = ['#type' => 'select', '#title' => $this->t('Number of items to add to queue'), '#options' => array_combine([1, 5, 10, 100, 1000], [1, 5, 10, 100, 1000]), '#default_value' => 5]; $form['cron_queue_setup']['queue'] = ['#type' => 'radios', '#title' => $this->t('Queue to add items to'), '#options' => ['cron_example_queue_1' => $this->t('Queue 1'), 'cron_example_queue_2' => $this->t('Queue 2')], '#default_value' => 'cron_example_queue_1']; $form['cron_queue_setup']['actions'] = ['#type' => 'actions']; $form['cron_queue_setup']['actions']['submit'] = ['#type' => 'submit', '#value' => $this->t('Add jobs to queue'), '#submit' => [[$this, 'addItems']]]; $form['configuration'] = ['#type' => 'details', '#title' => $this->t('Configuration of cron_example_cron()'), '#open' => TRUE]; $form['configuration']['cron_example_interval'] = ['#type' => 'select', '#title' => $this->t('Cron interval'), '#description' => $this->t('Time after which cron_example_cron will respond to a processing request.'), '#default_value' => $config->get('interval'), '#options' => [60 => $this->t('1 minute'), 300 => $this->t('5 minutes'), 3600 => $this->t('1 hour'), 86400 => $this->t('1 day')]]; return parent::buildForm($form, $form_state); }
/** * {@inheritdoc} */ public function loadMultipleByUser(AccountInterface $account, $profile_type) { return $this->loadByProperties([ 'uid' => $account->id(), 'type' => $profile_type, 'status' => PROFILE_ACTIVE, ]); }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { if ($account->hasPermission('administer tmgmt')) { // Administrators can do everything. return AccessResult::allowed()->cachePerPermissions(); } switch ($operation) { case 'view': case 'update': return AccessResult::allowedIfHasPermission($account, 'create translation jobs')->orIf(AccessResult::allowedIfHasPermission($account, 'accept translation jobs')); break; case 'delete': // Only administrators can delete jobs. return AccessResult::forbidden(); break; // Custom operations. // Custom operations. case 'submit': return AccessResult::allowedIfHasPermission($account, 'submit translation jobs'); break; case 'accept': return AccessResult::allowedIfHasPermission($account, 'accept translation jobs'); break; case 'abort': case 'resubmit': return AccessResult::allowedIfHasPermission($account, 'submit translation jobs'); break; } }
/** * Checks access to the given user's contact page. * * @param \Drupal\user\UserInterface $user * The user being contacted. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(UserInterface $user, AccountInterface $account) { $contact_account = $user; // Anonymous users cannot have contact forms. if ($contact_account->isAnonymous()) { return AccessResult::forbidden(); } // Users may not contact themselves. if ($account->id() == $contact_account->id()) { return AccessResult::forbidden()->cachePerUser(); } // User administrators should always have access to personal contact forms. $access = AccessResult::neutral()->cachePerRole(); $permission_access = AccessResult::allowedIfHasPermission($account, 'administer users'); if ($permission_access->isAllowed()) { return $access->orIf($permission_access); } // If requested user has been blocked, do not allow users to contact them. $access->cacheUntilEntityChanges($contact_account); if ($contact_account->isBlocked()) { return $access; } // If the requested user has disabled their contact form, do not allow users // to contact them. $account_data = $this->userData->get('contact', $contact_account->id(), 'enabled'); if (isset($account_data) && empty($account_data)) { return $access; } else { if (!$this->configFactory->get('contact.settings')->get('user_default_enabled')) { return $access; } } return $access->orIf(AccessResult::allowedIfHasPermission($account, 'access user contact forms')); }
/** * {@inheritdoc} */ protected function blockAccess(AccountInterface $account) { $route_name = $this->routeMatch->getRouteName(); if ($account->isAnonymous() && !in_array($route_name, array('user.login', 'user.logout'))) { return AccessResult::allowed()->addCacheContexts(['route.name', 'user.roles:anonymous']); } return AccessResult::forbidden(); }
/** * {@inheritdoc} */ public function access(Route $route, Request $request, AccountInterface $account) { // Suppress notices when on other pages when menu system still checks access. $name = $request->attributes->get('name'); $token = $request->query->get('token'); $destination = $request->query->get('destination'); return $account->hasPermission('switch users') && $this->csrfToken->validate($token, "devel/switch/{$name}|" . $destination, TRUE) ? static::ALLOW : static::DENY; }
/** * {@inheritdoc} */ public function getRouteName() { if ($this->currentUser->isAuthenticated()) { return 'user.logout'; } else { return 'user.login'; } }
/** * {@inheritdoc} */ public function access(AccountInterface $account) { foreach ($this->permissions as $permission) { if ($account->hasPermission($permission)) { return TRUE; } } }