/**
  * {@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);
 }
示例#2
0
 /**
  * {@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);
 }
示例#3
0
 /**
  * Adds in the current user as a context.
  *
  * @param \Drupal\page_manager\Event\PageManagerContextEvent $event
  *   The page entity context event.
  */
 public function onPageContext(PageManagerContextEvent $event)
 {
     $id = $this->account->id();
     $current_user = $this->userStorage->load($id);
     $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')));
     $context->setContextValue($current_user);
     $event->getPageExecutable()->addContext('current_user', $context);
 }
 /**
  * Adds in the current user as a context.
  *
  * @param \Drupal\page_manager\Event\PageManagerContextEvent $event
  *   The page entity context event.
  */
 public function onPageContext(PageManagerContextEvent $event)
 {
     $id = $this->account->id();
     $current_user = $this->userStorage->load($id);
     $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user);
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['user']);
     $context->addCacheableDependency($cacheability);
     $event->getPage()->addContext('current_user', $context);
 }
示例#5
0
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     $current_user = $this->userStorage->load($this->account->id());
     $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user);
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['user']);
     $context->addCacheableDependency($cacheability);
     $result = ['current_user' => $context];
     return $result;
 }
示例#6
0
 /**
  * {@inheritdoc}
  */
 public function getRuntimeContexts(array $unqualified_context_ids)
 {
     $current_user = $this->userStorage->load($this->account->id());
     $context1 = new Context(new ContextDefinition('entity:user', 'User 1'), $current_user);
     $context2 = new Context(new ContextDefinition('entity:user', 'User 2'), $current_user);
     $cacheability = new CacheableMetadata();
     $cacheability->setCacheContexts(['user']);
     $context1->addCacheableDependency($cacheability);
     $context2->addCacheableDependency($cacheability);
     return ['user1' => $context1, 'user2' => $context2];
 }
示例#7
0
 /**
  * Validates user, hash, and timestamp; logs the user in if correct.
  *
  * @param int $uid
  *   User ID of the user requesting reset.
  * @param int $timestamp
  *   The current timestamp.
  * @param string $hash
  *   Login link hash.
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  *   Returns a redirect to the user edit form if the information is correct.
  *   If the information is incorrect redirects to 'user.pass' route with a
  *   message for the user.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  *   If $uid is for a blocked user or invalid user ID.
  */
 public function resetPassLogin($uid, $timestamp, $hash)
 {
     // The current user is not logged in, so check the parameters.
     $current = REQUEST_TIME;
     /** @var \Drupal\user\UserInterface $user */
     $user = $this->userStorage->load($uid);
     // Verify that the user exists and is active.
     if ($user === NULL || !$user->isActive()) {
         // Blocked or invalid user ID, so deny access. The parameters will be in
         // the watchdog's URL for the administrator to check.
         throw new AccessDeniedHttpException();
     }
     // Time out, in seconds, until login URL expires.
     $timeout = $this->config('user.settings')->get('password_reset_timeout');
     // No time out for first time login.
     if ($user->getLastLoginTime() && $current - $timestamp > $timeout) {
         drupal_set_message($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'error');
         return $this->redirect('user.pass');
     } elseif ($user->isAuthenticated() && $timestamp >= $user->getLastLoginTime() && $timestamp <= $current && Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp))) {
         user_login_finalize($user);
         $this->logger->notice('User %name used one-time login link at time %timestamp.', ['%name' => $user->getDisplayName(), '%timestamp' => $timestamp]);
         drupal_set_message($this->t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.'));
         // Let the user's password be changed without the current password
         // check.
         $token = Crypt::randomBytesBase64(55);
         $_SESSION['pass_reset_' . $user->id()] = $token;
         return $this->redirect('entity.user.edit_form', ['user' => $user->id()], ['query' => ['pass-reset-token' => $token], 'absolute' => TRUE]);
     }
     drupal_set_message($this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
     return $this->redirect('user.pass');
 }
示例#8
0
 /**
  * {@inheritdoc}
  */
 public function entityQueryAlter(SelectInterface $query)
 {
     // Bail out early if we do not need to match the Anonymous user.
     $handler_settings = $this->configuration['handler_settings'];
     if (isset($handler_settings['include_anonymous']) && !$handler_settings['include_anonymous']) {
         return;
     }
     if ($this->currentUser->hasPermission('administer users')) {
         // In addition, if the user is administrator, we need to make sure to
         // match the anonymous user, that doesn't actually have a name in the
         // database.
         $conditions =& $query->conditions();
         foreach ($conditions as $key => $condition) {
             if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users_field_data.name') {
                 // Remove the condition.
                 unset($conditions[$key]);
                 // Re-add the condition and a condition on uid = 0 so that we end up
                 // with a query in the form:
                 // WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
                 $or = db_or();
                 $or->condition($condition['field'], $condition['value'], $condition['operator']);
                 // Sadly, the Database layer doesn't allow us to build a condition
                 // in the form ':placeholder = :placeholder2', because the 'field'
                 // part of a condition is always escaped.
                 // As a (cheap) workaround, we separately build a condition with no
                 // field, and concatenate the field and the condition separately.
                 $value_part = db_and();
                 $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
                 $value_part->compile($this->connection, $query);
                 $or->condition(db_and()->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => user_format_name($this->userStorage->load(0))))->condition('base_table.uid', 0));
                 $query->condition($or);
             }
         }
     }
 }
示例#9
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $this->config('system.site')->set('name', (string) $form_state->getValue('site_name'))->set('mail', (string) $form_state->getValue('site_mail'))->save(TRUE);
     $this->config('system.date')->set('timezone.default', (string) $form_state->getValue('date_default_timezone'))->set('country.default', (string) $form_state->getValue('site_default_country'))->save(TRUE);
     $account_values = $form_state->getValue('account');
     // Enable update.module if this option was selected.
     $update_status_module = $form_state->getValue('update_status_module');
     if ($update_status_module[1]) {
         $this->moduleInstaller->install(array('file', 'update'), FALSE);
         // Add the site maintenance account's email address to the list of
         // addresses to be notified when updates are available, if selected.
         if ($update_status_module[2]) {
             // Reset the configuration factory so it is updated with the new module.
             $this->resetConfigFactory();
             $this->config('update.settings')->set('notification.emails', array($account_values['mail']))->save(TRUE);
         }
     }
     // We precreated user 1 with placeholder values. Let's save the real values.
     $account = $this->userStorage->load(1);
     $account->init = $account->mail = $account_values['mail'];
     $account->roles = $account->getRoles();
     $account->activate();
     $account->timezone = $form_state->getValue('date_default_timezone');
     $account->pass = $account_values['pass'];
     $account->name = $account_values['name'];
     $account->save();
     // Record when this install ran.
     $this->state->set('install_time', $_SERVER['REQUEST_TIME']);
 }
示例#10
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     $current_user_id = $this->currentUser()->id();
     // Clear out the accounts from the temp store.
     $this->tempStoreFactory->get('user_user_operations_cancel')->delete($current_user_id);
     if ($form_state['values']['confirm']) {
         foreach ($form_state['values']['accounts'] as $uid => $value) {
             // Prevent programmatic form submissions from cancelling user 1.
             if ($uid <= 1) {
                 continue;
             }
             // Prevent user administrators from deleting themselves without confirmation.
             if ($uid == $current_user_id) {
                 $admin_form_mock = array();
                 $admin_form_state = $form_state;
                 unset($admin_form_state['values']['user_cancel_confirm']);
                 // The $user global is not a complete user entity, so load the full
                 // entity.
                 $account = $this->userStorage->load($uid);
                 $admin_form = $this->entityManager->getFormObject('user', 'cancel');
                 $admin_form->setEntity($account);
                 // Calling this directly required to init form object with $account.
                 $admin_form->buildForm($admin_form_mock, $admin_form_state);
                 $admin_form->submit($admin_form_mock, $admin_form_state);
             } else {
                 user_cancel($form_state['values'], $uid, $form_state['values']['user_cancel_method']);
             }
         }
     }
     $form_state['redirect_route']['route_name'] = 'user.admin_account';
 }
示例#11
0
 /**
  * Returns the user password reset page.
  *
  * @param int $uid
  *   UID of user requesting reset.
  * @param int $timestamp
  *   The current timestamp.
  * @param string $hash
  *   Login link hash.
  *
  * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
  *   The form structure or a redirect response.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  *   If the login link is for a blocked user or invalid user ID.
  */
 public function resetPass($uid, $timestamp, $hash)
 {
     $account = $this->currentUser();
     $config = $this->config('user.settings');
     // 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) {
             drupal_set_message($this->t('You are logged in as %user. <a href="!user_edit">Change your password.</a>', array('%user' => $account->getUsername(), '!user_edit' => $this->url('user.edit', array('user' => $account->id())))));
         } else {
             if ($reset_link_user = $this->userStorage->load($uid)) {
                 drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href="!logout">logout</a> and try using the link again.', array('%other_user' => $account->getUsername(), '%resetting_user' => $reset_link_user->getUsername(), '!logout' => $this->url('user.logout'))));
             } else {
                 // Invalid one-time link specifies an unknown user.
                 drupal_set_message($this->t('The one-time login link you clicked is invalid.'));
             }
         }
         return $this->redirect('<front>');
     } else {
         // The current user is not logged in, so check the parameters.
         // Time out, in seconds, until login URL expires.
         $timeout = $config->get('password_reset_timeout');
         $current = REQUEST_TIME;
         /* @var \Drupal\user\UserInterface $user */
         $user = $this->userStorage->load($uid);
         // Verify that the user exists and is active.
         if ($user && $user->isActive()) {
             // No time out for first time login.
             if ($user->getLastLoginTime() && $current - $timestamp > $timeout) {
                 drupal_set_message($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'));
                 return $this->redirect('user.pass');
             } elseif ($user->isAuthenticated() && $timestamp >= $user->getLastLoginTime() && $timestamp <= $current && $hash === user_pass_rehash($user->getPassword(), $timestamp, $user->getLastLoginTime())) {
                 $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
                 return $this->formBuilder()->getForm('Drupal\\user\\Form\\UserPasswordResetForm', $user, $expiration_date, $timestamp, $hash);
             } else {
                 drupal_set_message($this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'));
                 return $this->redirect('user.pass');
             }
         }
     }
     // Blocked or invalid user ID, so deny access. The parameters will be in the
     // watchdog's URL for the administrator to check.
     throw new AccessDeniedHttpException();
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $account = $this->userStorage->load($form_state->get('uid'));
     // A destination was set, probably on an exception controller,
     if (!$this->getRequest()->request->has('destination')) {
         $form_state->setRedirect('entity.user.canonical', array('user' => $account->id()));
     } else {
         $this->getRequest()->query->set('destination', $this->getRequest()->request->get('destination'));
     }
     user_login_finalize($account);
 }
示例#13
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     $account = $this->userStorage->load($form_state['uid']);
     // A destination was set, probably on an exception controller,
     if (!$this->getRequest()->request->has('destination')) {
         $form_state['redirect_route'] = array('route_name' => 'user.view', 'route_parameters' => array('user' => $account->id()));
     } else {
         $this->getRequest()->query->set('destination', $this->getRequest()->request->get('destination'));
     }
     user_login_finalize($account);
 }
示例#14
0
 /**
  * Displays details about a specific database log message.
  *
  * @param int $event_id
  *   Unique ID of the database log message.
  *
  * @return array
  *   If the ID is located in the Database Logging table, a build array in the
  *   format expected by drupal_render();
  *
  */
 public function eventDetails($event_id)
 {
     $build = array();
     if ($dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', array(':id' => $event_id))->fetchObject()) {
         $severity = RfcLogLevel::getLevels();
         $message = $this->formatMessage($dblog);
         $username = array('#theme' => 'username', '#account' => $dblog->uid ? $this->userStorage->load($dblog->uid) : User::getAnonymousUser());
         $rows = array(array(array('data' => $this->t('Type'), 'header' => TRUE), $this->t($dblog->type)), array(array('data' => $this->t('Date'), 'header' => TRUE), $this->dateFormatter->format($dblog->timestamp, 'long')), array(array('data' => $this->t('User'), 'header' => TRUE), array('data' => $username)), array(array('data' => $this->t('Location'), 'header' => TRUE), $this->l($dblog->location, $dblog->location ? Url::fromUri($dblog->location) : Url::fromRoute('<none>'))), array(array('data' => $this->t('Referrer'), 'header' => TRUE), $this->l($dblog->referer, $dblog->referer ? Url::fromUri($dblog->referer) : Url::fromRoute('<none>'))), array(array('data' => $this->t('Message'), 'header' => TRUE), $message), array(array('data' => $this->t('Severity'), 'header' => TRUE), $severity[$dblog->severity]), array(array('data' => $this->t('Hostname'), 'header' => TRUE), SafeMarkup::checkPlain($dblog->hostname)), array(array('data' => $this->t('Operations'), 'header' => TRUE), SafeMarkup::checkAdminXss($dblog->link)));
         $build['dblog_table'] = array('#type' => 'table', '#rows' => $rows, '#attributes' => array('class' => array('dblog-event')), '#attached' => array('library' => array('dblog/drupal.dblog')));
     }
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function validate($entity, Constraint $constraint)
 {
     $author_name = $entity->name->value;
     $owner_id = (int) $entity->uid->target_id;
     // Do not allow unauthenticated comment authors to use a name that is
     // taken by a registered user.
     if (isset($author_name) && $author_name !== '' && $owner_id === 0) {
         $users = $this->userStorage->loadByProperties(array('name' => $author_name));
         if (!empty($users)) {
             $this->context->buildViolation($constraint->messageNameTaken, array('%name' => $author_name))->atPath('name')->addViolation();
         }
     } elseif (isset($author_name) && $author_name !== '' && $owner_id) {
         $owner = $this->userStorage->load($owner_id);
         if ($owner->getUsername() != $author_name) {
             $this->context->buildViolation($constraint->messageMatch)->atPath('name')->addViolation();
         }
     }
     // Anonymous account might be required - depending on field settings.
     if ($owner_id === 0 && empty($author_name) && $this->getAnonymousContactDetailsSetting($entity) === COMMENT_ANONYMOUS_MUST_CONTACT) {
         $this->context->buildViolation($constraint->messageRequired)->atPath('name')->addViolation();
     }
 }
 /**
  * Logs in a user.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   A response which contains the ID and CSRF token.
  */
 public function login(Request $request)
 {
     $format = $this->getRequestFormat($request);
     $content = $request->getContent();
     $credentials = $this->serializer->decode($content, $format);
     if (!isset($credentials['name']) && !isset($credentials['pass'])) {
         throw new BadRequestHttpException('Missing credentials.');
     }
     if (!isset($credentials['name'])) {
         throw new BadRequestHttpException('Missing credentials.name.');
     }
     if (!isset($credentials['pass'])) {
         throw new BadRequestHttpException('Missing credentials.pass.');
     }
     $this->floodControl($request, $credentials['name']);
     if ($this->userIsBlocked($credentials['name'])) {
         throw new BadRequestHttpException('The user has not been activated or is blocked.');
     }
     if ($uid = $this->userAuth->authenticate($credentials['name'], $credentials['pass'])) {
         $this->flood->clear('user.http_login', $this->getLoginFloodIdentifier($request, $credentials['name']));
         /** @var \Drupal\user\UserInterface $user */
         $user = $this->userStorage->load($uid);
         $this->userLoginFinalize($user);
         // Send basic metadata about the logged in user.
         $response_data = [];
         if ($user->get('uid')->access('view', $user)) {
             $response_data['current_user']['uid'] = $user->id();
         }
         if ($user->get('roles')->access('view', $user)) {
             $response_data['current_user']['roles'] = $user->getRoles();
         }
         if ($user->get('name')->access('view', $user)) {
             $response_data['current_user']['name'] = $user->getAccountName();
         }
         $response_data['csrf_token'] = $this->csrfToken->get('rest');
         $logout_route = $this->routeProvider->getRouteByName('user.logout.http');
         // Trim '/' off path to match \Drupal\Core\Access\CsrfAccessCheck.
         $logout_path = ltrim($logout_route->getPath(), '/');
         $response_data['logout_token'] = $this->csrfToken->get($logout_path);
         $encoded_response_data = $this->serializer->encode($response_data, $format);
         return new Response($encoded_response_data);
     }
     $flood_config = $this->config('user.flood');
     if ($identifier = $this->getLoginFloodIdentifier($request, $credentials['name'])) {
         $this->flood->register('user.http_login', $flood_config->get('user_window'), $identifier);
     }
     // Always register an IP-based failed login event.
     $this->flood->register('user.failed_login_ip', $flood_config->get('ip_window'));
     throw new BadRequestHttpException('Sorry, unrecognized username or password.');
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $account_values = $form_state->getValue('account');
     // We precreated user 1 with placeholder values. Let's save the real values.
     $account = $this->userStorage->load(1);
     $account->init = $account->mail = $account_values['mail'];
     $account->roles = $account->getRoles();
     $account->activate();
     $account->timezone = $form_state->getValue('date_default_timezone');
     $account->pass = $account_values['pass'];
     $account->name = $account_values['name'];
     $account->save();
     // Record when this install ran.
     $this->state->set('install_time', $_SERVER['REQUEST_TIME']);
 }