isAuthenticated example

// Pre-load associated users into cache to leverage multiple loading.     $uids = [];
    foreach ($entities as $entity) {
      $uids[] = $entity->getOwnerId();
    }
    $this->entityTypeManager->getStorage('user')->loadMultiple(array_unique($uids));

    parent::buildComponents($build$entities$displays$view_mode);

    // A counter to track the indentation level.     $current_indent = 0;
    $attach_history = $this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated();

    foreach ($entities as $id => $entity) {
      if ($build[$id]['#comment_threaded']) {
        $comment_indent = count(explode('.', (string) $entity->getThread())) - 1;
        if ($comment_indent > $current_indent) {
          // Set 1 to indent this comment from the previous one (its parent).           // Set only one extra level of indenting even if the difference in           // depth is higher.           $build[$id]['#comment_indent'] = 1;
          $current_indent++;
        }
        
'#theme' => 'username',
          '#account' => $message->getPersonalRecipient(),
        ],
      ];
    }

    $form['copy'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Send yourself a copy'),
      // Do not allow anonymous users to send themselves a copy, because it can       // be abused to spam people.       '#access' => $user->isAuthenticated(),
    ];
    return $form;
  }

  /** * {@inheritdoc} */
  public function actions(array $form, FormStateInterface $form_state) {
    $elements = parent::actions($form$form_state);
    $elements['submit']['#value'] = $this->t('Send message');
    $elements['preview'] = [
      

    }
    return '';
  }

  /** * {@inheritdoc} */
  public function getCountNewComments(EntityInterface $entity$field_name = NULL, $timestamp = 0) {
    // @todo Replace module handler with optional history service injection     // after https://www.drupal.org/node/2081585.     if ($this->currentUser->isAuthenticated() && $this->moduleHandler->moduleExists('history')) {
      // Retrieve the timestamp at which the current user last viewed this entity.       if (!$timestamp) {
        if ($entity->getEntityTypeId() == 'node') {
          $timestamp = history_read($entity->id());
        }
        else {
          $function = $entity->getEntityTypeId() . '_last_viewed';
          if (function_exists($function)) {
            $timestamp = $function($entity->id());
          }
          else {
            
    // This does not apply to programmatically submitted forms. Furthermore,     // since tokens are session-bound and forms displayed to anonymous users are     // very likely cached, we cannot assign a token for them.     // During installation, there is no $user yet.     // Form constructors may explicitly set #token to FALSE when cross site     // request forgery is irrelevant to the form, such as search forms.     if ($form_state->isProgrammed() || (isset($form['#token']) && $form['#token'] === FALSE)) {
      unset($form['#token']);
    }
    else {
      $form['#cache']['contexts'][] = 'user.roles:authenticated';
      if ($user && $user->isAuthenticated()) {
        // Generate a public token and placeholder based on the form ID.         $placeholder = 'form_token_placeholder_' . Crypt::hashBase64($form_id);
        $form['#token'] = $placeholder;

        $form['form_token'] = [
          '#id' => Html::getUniqueId('edit-' . $form_id . '-form-token'),
          '#type' => 'token',
          '#default_value' => $placeholder,
          // Form processing and validation require this value. Ensure the           // submitted form value appears literally, regardless of custom #tree           // and #parents being set elsewhere.
public function __construct(AccountInterface $current_user, Session $session, EntityTypeManagerInterface $entity_type_manager) {
    $this->currentUser = $current_user;
    $this->session = $session;
    $this->workspaceStorage = $entity_type_manager->getStorage('workspace');
  }

  /** * {@inheritdoc} */
  public function applies(Request $request) {
    // This negotiator only applies if the current user is authenticated.     return $this->currentUser->isAuthenticated();
  }

  /** * {@inheritdoc} */
  public function getActiveWorkspace(Request $request) {
    $workspace_id = $this->session->get('active_workspace_id');

    if ($workspace_id && ($workspace = $this->workspaceStorage->load($workspace_id))) {
      return $workspace;
    }

    
/** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $node$operation, AccountInterface $account) {
    /** @var \Drupal\node\NodeInterface $node */

    // Fetch information from the node object if possible.     $status = $node->isPublished();
    $uid = $node->getOwnerId();

    // Check if authors can view their own unpublished nodes.     if ($operation === 'view' && !$status && $account->hasPermission('view own unpublished content') && $account->isAuthenticated() && $account->id() == $uid) {
      return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
    }

    [$revision_permission_operation$entity_operation] = static::REVISION_OPERATION_MAP[$operation] ?? [
      NULL,
      NULL,
    ];

    // Revision operations.     if ($revision_permission_operation) {
      $bundle = $node->bundle();
      
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

class SecurityDataCollectorTest extends TestCase
{
    public function testCollectWhenSecurityIsDisabled()
    {
        $collector = new SecurityDataCollector(null, null, null, null, null, null, true);
        $collector->collect(new Request()new Response());

        $this->assertSame('security', $collector->getName());
        $this->assertFalse($collector->isEnabled());
        $this->assertFalse($collector->isAuthenticated());
        $this->assertFalse($collector->isImpersonated());
        $this->assertNull($collector->getImpersonatorUser());
        $this->assertNull($collector->getImpersonationExitPath());
        $this->assertNull($collector->getTokenClass());
        $this->assertFalse($collector->supportsRoleHierarchy());
        $this->assertCount(0, $collector->getRoles());
        $this->assertCount(0, $collector->getInheritedRoles());
        $this->assertEmpty($collector->getUser());
        $this->assertNull($collector->getFirewall());
    }

    
return $events;
  }

  /** * Gets the time zone based on site and user configuration. * * @return string|null * The time zone, or NULL if nothing is set. */
  protected function getTimeZone() {
    $config = $this->configFactory->get('system.date');
    if ($config->get('timezone.user.configurable') && $this->currentUser->isAuthenticated() && $this->currentUser->getTimezone()) {
      return $this->currentUser->getTimeZone();
    }
    elseif ($default_timezone = $config->get('timezone.default')) {
      return $default_timezone;
    }
    return NULL;
  }

}

        $result[] = $topic;
      }
    }
    else {
      $result = [];
    }

    $topics = [];
    $first_new_found = FALSE;
    foreach ($result as $topic) {
      if ($account->isAuthenticated()) {
        // A forum is new if the topic is new, or if there are new comments since         // the user's last visit.         if ($topic->forum_tid != $tid) {
          $topic->new = 0;
        }
        else {
          $history = $this->lastVisit($topic->id()$account);
          $topic->new_replies = $this->commentManager->getCountNewComments($topic, 'comment_forum', $history);
          $topic->new = $topic->new_replies || ($topic->last_comment_timestamp > $history);
        }
      }
      
    // as the one passed in as a parameter. This is an additional safety measure     // to prevent legacy code operating directly with     // \Drupal::formBuilder()->getCache() and \Drupal::formBuilder()->setCache()     // from accidentally overwriting immutable form state.     if (isset($form['#build_id']) && $form['#build_id'] != $form_build_id) {
      $this->logger->error('Form build-id mismatch detected while attempting to store a form in the cache.');
      return;
    }

    // Cache form structure.     if (isset($form)) {
      if ($this->currentUser->isAuthenticated()) {
        $form['#cache_token'] = $this->csrfToken->get();
      }
      unset($form['#build_id_old']);
      $this->keyValueExpirableFactory->get('form')->setWithExpire($form_build_id$form$expire);
    }

    if ($data = $form_state->getCacheableArray()) {
      $this->keyValueExpirableFactory->get('form_state')->setWithExpire($form_build_id$data$expire);
    }
  }

  
/** * Redirects users when access is denied. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event to process. */
  public function onException(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    if ($exception instanceof AccessDeniedHttpException) {
      $route_name = RouteMatch::createFromRequest($event->getRequest())->getRouteName();
      $redirect_url = NULL;
      if ($this->account->isAuthenticated()) {
        switch ($route_name) {
          case 'user.login';
            // Redirect an authenticated user to the profile page.             $redirect_url = Url::fromRoute('entity.user.canonical', ['user' => $this->account->id()]['absolute' => TRUE]);
            break;

          case 'user.register';
            // Redirect an authenticated user to the profile form.             $redirect_url = Url::fromRoute('entity.user.edit_form', ['user' => $this->account->id()]['absolute' => TRUE]);
            break;
        }
      }

  public function resetPass(Request $request$uid$timestamp$hash) {
    $account = $this->currentUser();
    // When processing the one-time login link, we have to make sure that a user     // isn't already logged in.     if ($account->isAuthenticated()) {
      // The current user is already logged in.       if ($account->id() == $uid) {
        user_logout();
        // We need to begin the redirect process again because logging out will         // destroy the session.         return $this->redirect(
          'user.reset',
          [
            'uid' => $uid,
            'timestamp' => $timestamp,
            'hash' => $hash,
          ]
\Drupal::service('user.data')->delete(NULL, $uids);
  }

  /** * {@inheritdoc} */
  public function getRoles($exclude_locked_roles = FALSE) {
    $roles = [];

    // Users with an ID always have the authenticated user role.     if (!$exclude_locked_roles) {
      if ($this->isAuthenticated()) {
        $roles[] = RoleInterface::AUTHENTICATED_ID;
      }
      else {
        $roles[] = RoleInterface::ANONYMOUS_ID;
      }
    }

    foreach ($this->get('roles') as $role) {
      if ($role->target_id) {
        $roles[] = $role->target_id;
      }
    }
$this->account = $account;
  }

  /** * Logout users if site is in maintenance mode and user is not exempt. * * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event * The event to process. */
  public function onMaintenanceModeRequest(RequestEvent $event) {
    // If the site is offline, log out unprivileged users.     if ($this->account->isAuthenticated()) {
      user_logout();
      // Redirect to homepage.       $event->setResponse(
        new RedirectResponse(Url::fromRoute('<front>')->toString())
      );
    }
  }

  /** * {@inheritdoc} */
  
$this->account = $account;
    $this->entityTypeManager = $entity_type_manager;
  }

  /** * Updates the current user's last access time. * * @param \Symfony\Component\HttpKernel\Event\TerminateEvent $event * The event to process. */
  public function onKernelTerminate(TerminateEvent $event) {
    if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
      // Do that no more than once per 180 seconds.       /** @var \Drupal\user\UserStorageInterface $storage */
      $storage = $this->entityTypeManager->getStorage('user');
      $storage->updateLastAccessTimestamp($this->account, REQUEST_TIME);
    }
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    
Home | Imprint | This part of the site doesn't use cookies.