Example #1
0
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
 {
     $config = $this->configFactory->get('shield.settings');
     $allow_cli = $config->get('allow_cli');
     $user = $config->get('user');
     $pass = $config->get('pass');
     if (empty($user) || PHP_SAPI === 'cli' && $allow_cli) {
         // If username is empty, then authentication is disabled,
         // or if request is coming from a cli and it is allowed,
         // then proceed with response without shield authentication.
         return $this->httpKernel->handle($request, $type, $catch);
     } else {
         if ($request->server->has('PHP_AUTH_USER') && $request->server->has('PHP_AUTH_PW')) {
             $input_user = $request->server->get('PHP_AUTH_USER');
             $input_pass = $request->server->get('PHP_AUTH_PW');
         } elseif ($request->server->has('HTTP_AUTHORIZATION')) {
             list($input_user, $input_pass) = explode(':', base64_decode(substr($request->server->get('HTTP_AUTHORIZATION'), 6)), 2);
         } elseif ($request->server->has('REDIRECT_HTTP_AUTHORIZATION')) {
             list($input_user, $input_pass) = explode(':', base64_decode(substr($request->server->get('REDIRECT_HTTP_AUTHORIZATION'), 6)), 2);
         }
         if (isset($input_user) && $input_user === $user && Crypt::hashEquals($pass, $input_pass)) {
             return $this->httpKernel->handle($request, $type, $catch);
         }
     }
     $response = new Response();
     $response->headers->add(['WWW-Authenticate' => 'Basic realm="' . strtr($config->get('print'), ['[user]' => $user, '[pass]' => $pass]) . '"']);
     $response->setStatusCode(401);
     return $response;
 }
 /**
  * Confirms cancelling a user account via an email link.
  *
  * @param \Drupal\user\UserInterface $user
  *   The user account.
  * @param int $timestamp
  *   The timestamp.
  * @param string $hashed_pass
  *   The hashed password.
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  *   A redirect response.
  */
 public function confirmCancel(UserInterface $user, $timestamp = 0, $hashed_pass = '')
 {
     // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds.
     $timeout = 86400;
     $current = REQUEST_TIME;
     // Basic validation of arguments.
     $account_data = $this->userData->get('user', $user->id());
     if (isset($account_data['cancel_method']) && !empty($timestamp) && !empty($hashed_pass)) {
         // Validate expiration and hashed password/login.
         if ($timestamp <= $current && $current - $timestamp < $timeout && $user->id() && $timestamp >= $user->getLastLoginTime() && Crypt::hashEquals($hashed_pass, user_pass_rehash($user, $timestamp))) {
             $edit = array('user_cancel_notify' => isset($account_data['cancel_notify']) ? $account_data['cancel_notify'] : $this->config('user.settings')->get('notify.status_canceled'));
             user_cancel($edit, $user->id(), $account_data['cancel_method']);
             // Since user_cancel() is not invoked via Form API, batch processing
             // needs to be invoked manually and should redirect to the front page
             // after completion.
             return batch_process('');
         } else {
             drupal_set_message(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'), 'error');
             return $this->redirect('entity.user.cancel_form', ['user' => $user->id()], ['absolute' => TRUE]);
         }
     }
     throw new AccessDeniedHttpException();
 }
Example #3
0
 /**
  * Checks access for the subtree controller.
  *
  * @param string $hash
  *   The hash of the toolbar subtrees.
  *
  * @return \Drupal\Core\Access\AccessResultInterface
  *   The access result.
  */
 public function checkSubTreeAccess($hash)
 {
     $expected_hash = _toolbar_get_subtrees_hash()[0];
     return AccessResult::allowedIf($this->currentUser()->hasPermission('access toolbar') && Crypt::hashEquals($expected_hash, $hash))->cachePerPermissions();
 }
Example #4
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     /** @var \Drupal\user\UserInterface $account */
     $account = $this->entity;
     $user = $this->currentUser();
     $config = \Drupal::config('user.settings');
     $form['#cache']['tags'] = $config->getCacheTags();
     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
     $register = $account->isAnonymous();
     $admin = $user->hasPermission('administer users');
     // Account information.
     $form['account'] = array('#type' => 'container', '#weight' => -10);
     // The mail field is NOT required if account originally had no mail set
     // and the user performing the edit has 'administer users' permission.
     // This allows users without email address to be edited and deleted.
     // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired.
     $form['account']['mail'] = array('#type' => 'email', '#title' => $this->t('Email address'), '#description' => $this->t('A valid email address. All emails from the system will be sent to this address. The email address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by email.'), '#required' => !(!$account->getEmail() && $user->hasPermission('administer users')), '#default_value' => !$register ? $account->getEmail() : '');
     // Only show name field on registration form or user can change own username.
     $form['account']['name'] = array('#type' => 'textfield', '#title' => $this->t('Username'), '#maxlength' => USERNAME_MAX_LENGTH, '#description' => $this->t("Several special characters are allowed, including space, period (.), hyphen (-), apostrophe ('), underscore (_), and the @ sign."), '#required' => TRUE, '#attributes' => array('class' => array('username'), 'autocorrect' => 'off', 'autocapitalize' => 'off', 'spellcheck' => 'false'), '#default_value' => !$register ? $account->getUsername() : '', '#access' => $register || $user->id() == $account->id() && $user->hasPermission('change own username') || $admin);
     // Display password field only for existing users or when user is allowed to
     // assign a password during registration.
     if (!$register) {
         $form['account']['pass'] = array('#type' => 'password_confirm', '#size' => 25, '#description' => $this->t('To change the current user password, enter the new password in both fields.'));
         // To skip the current password field, the user must have logged in via a
         // one-time link and have the token in the URL. Store this in $form_state
         // so it persists even on subsequent Ajax requests.
         if (!$form_state->get('user_pass_reset') && ($token = $this->getRequest()->get('pass-reset-token'))) {
             $session_key = 'pass_reset_' . $account->id();
             $user_pass_reset = isset($_SESSION[$session_key]) && Crypt::hashEquals($_SESSION[$session_key], $token);
             $form_state->set('user_pass_reset', $user_pass_reset);
         }
         // The user must enter their current password to change to a new one.
         if ($user->id() == $account->id()) {
             $form['account']['current_pass'] = array('#type' => 'password', '#title' => $this->t('Current password'), '#size' => 25, '#access' => !$form_state->get('user_pass_reset'), '#weight' => -5, '#attributes' => array('autocomplete' => 'off'));
             $form_state->set('user', $account);
             // The user may only change their own password without their current
             // password if they logged in via a one-time login link.
             if (!$form_state->get('user_pass_reset')) {
                 $form['account']['current_pass']['#description'] = $this->t('Required if you want to change the %mail or %pass below. <a href=":request_new_url" title="Send password reset instructions via email.">Reset your password</a>.', array('%mail' => $form['account']['mail']['#title'], '%pass' => $this->t('Password'), ':request_new_url' => $this->url('user.pass')));
             }
         }
     } elseif (!$config->get('verify_mail') || $admin) {
         $form['account']['pass'] = array('#type' => 'password_confirm', '#size' => 25, '#description' => $this->t('Provide a password for the new account in both fields.'), '#required' => TRUE);
     }
     // When not building the user registration form, prevent web browsers from
     // autofilling/prefilling the email, username, and password fields.
     if ($this->getOperation() != 'register') {
         foreach (array('mail', 'name', 'pass') as $key) {
             if (isset($form['account'][$key])) {
                 $form['account'][$key]['#attributes']['autocomplete'] = 'off';
             }
         }
     }
     if ($admin || !$register) {
         $status = $account->get('status')->value;
     } else {
         $status = $config->get('register') == USER_REGISTER_VISITORS ? 1 : 0;
     }
     $form['account']['status'] = array('#type' => 'radios', '#title' => $this->t('Status'), '#default_value' => $status, '#options' => array($this->t('Blocked'), $this->t('Active')), '#access' => $admin);
     $roles = array_map(array('\\Drupal\\Component\\Utility\\Html', 'escape'), user_role_names(TRUE));
     $form['account']['roles'] = array('#type' => 'checkboxes', '#title' => $this->t('Roles'), '#default_value' => !$register ? $account->getRoles() : array(), '#options' => $roles, '#access' => $roles && $user->hasPermission('administer permissions'));
     // Special handling for the inevitable "Authenticated user" role.
     $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = array('#default_value' => TRUE, '#disabled' => TRUE);
     $form['account']['notify'] = array('#type' => 'checkbox', '#title' => $this->t('Notify user of new account'), '#access' => $register && $admin);
     $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode();
     $user_preferred_admin_langcode = $register ? $language_interface->getId() : $account->getPreferredAdminLangcode(FALSE);
     // Is the user preferred language added?
     $user_language_added = FALSE;
     if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
         $negotiator = $this->languageManager->getNegotiator();
         $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
     }
     $form['language'] = array('#type' => $this->languageManager->isMultilingual() ? 'details' : 'container', '#title' => $this->t('Language settings'), '#open' => TRUE, '#access' => !$register || $user->hasPermission('administer users'));
     $form['language']['preferred_langcode'] = array('#type' => 'language_select', '#title' => $this->t('Site language'), '#languages' => LanguageInterface::STATE_CONFIGURABLE, '#default_value' => $user_preferred_langcode, '#description' => $user_language_added ? $this->t("This account's preferred language for emails and site presentation.") : $this->t("This account's preferred language for emails."), '#pre_render' => ['user_langcode' => [$this, 'alterPreferredLangcodeDescription']]);
     // Only show the account setting for Administration pages language to users
     // if one of the detection and selection methods uses it.
     $show_admin_language = FALSE;
     if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) {
         $negotiator = $this->languageManager->getNegotiator();
         $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID);
     }
     $form['language']['preferred_admin_langcode'] = array('#type' => 'language_select', '#title' => $this->t('Administration pages language'), '#languages' => LanguageInterface::STATE_CONFIGURABLE, '#default_value' => $user_preferred_admin_langcode, '#access' => $show_admin_language, '#empty_option' => $this->t('- No preference -'), '#empty_value' => '');
     // User entities contain both a langcode property (for identifying the
     // language of the entity data) and a preferred_langcode property (see
     // above). Rather than provide a UI forcing the user to choose both
     // separately, assume that the user profile data is in the user's preferred
     // language. This entity builder provides that synchronization. For
     // use-cases where this synchronization is not desired, a module can alter
     // or remove this item.
     $form['#entity_builders']['sync_user_langcode'] = [$this, 'syncUserLangcode'];
     return parent::form($form, $form_state, $account);
 }
 /**
  * {@inheritdoc}
  */
 public function check($password, $hash)
 {
     if (substr($hash, 0, 2) == 'U$') {
         // This may be an updated password from user_update_7000(). Such hashes
         // have 'U' added as the first character and need an extra md5() (see the
         // Drupal 7 documentation).
         $stored_hash = substr($hash, 1);
         $password = md5($password);
     } else {
         $stored_hash = $hash;
     }
     $type = substr($stored_hash, 0, 3);
     switch ($type) {
         case '$S$':
             // A normal Drupal 7 password using sha512.
             $computed_hash = $this->crypt('sha512', $password, $stored_hash);
             break;
         case '$H$':
             // phpBB3 uses "$H$" for the same thing as "$P$".
         // phpBB3 uses "$H$" for the same thing as "$P$".
         case '$P$':
             // A phpass password generated using md5.  This is an
             // imported password or from an earlier Drupal version.
             $computed_hash = $this->crypt('md5', $password, $stored_hash);
             break;
         default:
             return FALSE;
     }
     // Compare using hashEquals() instead of === to mitigate timing attacks.
     return $computed_hash && Crypt::hashEquals($stored_hash, $computed_hash);
 }
Example #6
0
use Drupal\Component\Utility\Crypt;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
// Change the directory to the Drupal root.
chdir('..');
$autoloader = (require_once __DIR__ . '/../autoload.php');
require_once __DIR__ . '/includes/utility.inc';
$request = Request::createFromGlobals();
// Manually resemble early bootstrap of DrupalKernel::boot().
require_once __DIR__ . '/includes/bootstrap.inc';
DrupalKernel::bootEnvironment();
try {
    Settings::initialize(dirname(__DIR__), DrupalKernel::findSitePath($request), $autoloader);
} catch (HttpExceptionInterface $e) {
    $response = new Response('', $e->getStatusCode());
    $response->prepare($request)->send();
    exit;
}
if (Settings::get('rebuild_access', FALSE) || $request->query->get('token') && $request->query->get('timestamp') && REQUEST_TIME - $request->query->get('timestamp') < 300 && Crypt::hashEquals(Crypt::hmacBase64($request->query->get('timestamp'), Settings::get('hash_salt')), $request->query->get('token'))) {
    // Clear the APCu cache to ensure APCu class loader is reset.
    if (function_exists('apcu_clear_cache')) {
        apcu_clear_cache();
    }
    drupal_rebuild($autoloader, $request);
    drupal_set_message('Cache rebuild complete.');
}
$base_path = dirname(dirname($request->getBaseUrl()));
header('Location: ' . $base_path);