/** * Authenticates user on request. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The request event. * * @see \Drupal\Core\Authentication\AuthenticationProviderInterface::authenticate() */ public function onKernelRequestAuthenticate(GetResponseEvent $event) { if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) { $request = $event->getRequest(); if ($this->authenticationProvider->applies($request)) { $account = $this->authenticationProvider->authenticate($request); if ($account) { $this->accountProxy->setAccount($account); } } } }
/** * Authenticates user on request. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The request event. * * @see \Drupal\Core\Authentication\AuthenticationProviderInterface::authenticate() */ public function onKernelRequestAuthenticate(GetResponseEvent $event) { if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) { $request = $event->getRequest(); if ($this->authenticationProvider->applies($request)) { $account = $this->authenticationProvider->authenticate($request); if ($account) { $this->accountProxy->setAccount($account); return; } } // No account has been set explicitly, initialize the timezone here. date_default_timezone_set(drupal_get_user_timezone()); } }
/** * {@inheritdoc} */ public function run() { // Allow execution to continue even if the request gets cancelled. @ignore_user_abort(TRUE); // Prevent session information from being saved while cron is running. $original_session_saving = $this->sessionManager->isEnabled(); $this->sessionManager->disable(); // Force the current user to anonymous to ensure consistent permissions on // cron runs. $original_user = $this->currentUser->getAccount(); $this->currentUser->setAccount(new AnonymousUserSession()); // Try to allocate enough time to run all the hook_cron implementations. drupal_set_time_limit(240); $return = FALSE; // Try to acquire cron lock. if (!$this->lock->acquire('cron', 900.0)) { // Cron is still running normally. $this->logger->warning('Attempting to re-run cron while it is already running.'); } else { $this->invokeCronHandlers(); $this->setCronLastTime(); // Release cron lock. $this->lock->release('cron'); // Return TRUE so other functions can check if it did run successfully $return = TRUE; } // Process cron queues. $this->processQueues(); // Restore the user. $this->currentUser->setAccount($original_user); if ($original_session_saving) { $this->sessionManager->enable(); } return $return; }
/** * {@inheritdoc} */ public function switchBack() { // Restore the previous account from the stack. if (!empty($this->accountStack)) { $this->currentUser->setAccount(array_pop($this->accountStack)); } else { throw new \RuntimeException('No more accounts to revert to.'); } // Restore original session saving status if all account switches are // reverted. if (empty($this->accountStack)) { if ($this->originalSessionSaving) { $this->writeSafeHandler->setSessionWritable(TRUE); } } return $this; }
/** * {@inheritdoc} */ public function enhance(array $defaults, Request $request) { $auth_provider_triggered = $request->attributes->get('_authentication_provider'); if (!empty($auth_provider_triggered)) { $route = isset($defaults[RouteObjectInterface::ROUTE_OBJECT]) ? $defaults[RouteObjectInterface::ROUTE_OBJECT] : NULL; $auth_providers = $route && $route->getOption('_auth') ? $route->getOption('_auth') : array($this->manager->defaultProviderId()); // If the request was authenticated with a non-permitted provider, // force the user back to anonymous. if (!in_array($auth_provider_triggered, $auth_providers)) { $anonymous_user = new AnonymousUserSession(); $this->currentUser->setAccount($anonymous_user); // The global $user object is included for backward compatibility only // and should be considered deprecated. // @todo Remove this line once global $user is no longer used. $GLOBALS['user'] = $anonymous_user; } } return $defaults; }
/** * {@inheritdoc} */ public function preprocessIndexItems(array &$items) { // Change the current user to our dummy implementation to ensure we are // using the configured roles. $original_user = $this->currentUser->getAccount(); // @todo Why not just use \Drupal\Core\Session\UserSession directly here? $this->currentUser->setAccount(new UserSession(array('roles' => $this->configuration['roles']))); // Count of items that don't have a view mode. $unset_view_modes = 0; // Annoyingly, this doc comment is needed for PHPStorm. See // http://youtrack.jetbrains.com/issue/WI-23586 /** @var \Drupal\search_api\Item\ItemInterface $item */ foreach ($items as $item) { if (!($field = $item->getField('rendered_item'))) { continue; } $datasource_id = $item->getDatasourceId(); $datasource = $item->getDatasource(); $bundle = $datasource->getItemBundle($item->getOriginalObject()); if (empty($this->configuration['view_mode'][$datasource_id][$bundle])) { if (!isset($this->configuration['view_mode'][$datasource_id][$bundle])) { ++$unset_view_modes; } continue; } else { $view_mode = (string) $this->configuration['view_mode'][$datasource_id][$bundle]; } $build = $datasource->viewItem($item->getOriginalObject(), $view_mode); $value = (string) $this->getRenderer()->renderPlain($build); if ($value) { $field->addValue($value); } } if ($unset_view_modes > 0) { $context = array( '%index' => $this->index->label(), '%processor' => $this->label(), '@count' => $unset_view_modes, ); $this->getLogger()->warning('Warning: While indexing items on search index %index, @count item(s) did not have a view mode configured for the %processor processor.', $context); } // Restore the original user. $this->currentUser->setAccount($original_user); }
/** * Switches to a different user. * * We don't call session_save_session() because we really want to change users. * Usually unsafe! * * @param string $name * The username to switch to, or NULL to log out. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * A redirect response object. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException */ public function switchUser($name = NULL) { if (empty($name) || !($account = $this->userStorage->loadByProperties(['name' => $name]))) { throw new AccessDeniedHttpException(); } $account = reset($account); // Call logout hooks when switching from original user. $this->moduleHandler->invokeAll('user_logout', [$this->account]); // Regenerate the session ID to prevent against session fixation attacks. $this->sessionManager->regenerate(); // Based off masquarade module as: // https://www.drupal.org/node/218104 doesn't stick and instead only // keeps context until redirect. $this->account->setAccount($account); $this->session->set('uid', $account->id()); // Call all login hooks when switching to masquerading user. $this->moduleHandler->invokeAll('user_login', [$account]); return $this->redirect('<front>'); }
/** * {@inheritdoc} */ public function preprocessIndexItems(array &$items) { // Change the current user to our dummy implementation to ensure we are // using the configured roles. $original_user = $this->currentUser->getAccount(); // @todo Why not just use \Drupal\Core\Session\UserSession directly here? $this->currentUser->setAccount(new UserSession(array('roles' => $this->configuration['roles']))); // Annoyingly, this doc comment is needed for PHPStorm. See // http://youtrack.jetbrains.com/issue/WI-23586 /** @var \Drupal\search_api\Item\ItemInterface $item */ foreach ($items as $item) { if (empty($this->configuration['view_mode'][$item->getDatasourceId()])) { continue; } if (!($field = $item->getField('rendered_item'))) { continue; } $build = $item->getDatasource()->viewItem($item->getOriginalObject(), $this->configuration['view_mode'][$item->getDatasourceId()]); $field->addValue($this->getRenderer()->renderPlain($build)); } // Restore the original user. $this->currentUser->setAccount($original_user); }
/** * Switching back to previous user. * * @return bool * TRUE when switched back, FALSE otherwise. */ public function switchBack() { if (empty($_SESSION['masquerading'])) { return FALSE; } $new_user = $this->entityTypeManager->getStorage('user')->load($_SESSION['masquerading']); // Ensure the flag is cleared. unset($_SESSION['masquerading']); if (!$new_user) { return FALSE; } $account = $this->currentUser; // Call logout hooks when switching from masquerading user. $this->moduleHandler->invokeAll('user_logout', [$account]); // Regenerate the session ID to prevent against session fixation attacks. // @todo Maybe session service migrate. $this->sessionManager->regenerate(); $this->currentUser->setAccount($new_user); \Drupal::service('session')->set('uid', $new_user->id()); // Call all login hooks when switching back to original user. $this->moduleHandler->invokeAll('user_login', [$new_user]); $this->logger->info('User %username stopped masquerading as %old_username.', array('%username' => $new_user->getDisplayName(), '%old_username' => $account->getDisplayName(), 'link' => $this->l($this->t('view'), $new_user->toUrl()))); return TRUE; }