Example #1
0
 function testRegistrationWithEmailVerification()
 {
     $config = $this->config('user.settings');
     // Require email verification.
     $config->set('verify_mail', TRUE)->save();
     // Set registration to administrator only.
     $config->set('register', USER_REGISTER_ADMINISTRATORS_ONLY)->save();
     $this->drupalGet('user/register');
     $this->assertResponse(403, 'Registration page is inaccessible when only administrators can create accounts.');
     // Allow registration by site visitors without administrator approval.
     $config->set('register', USER_REGISTER_VISITORS)->save();
     $edit = array();
     $edit['name'] = $name = $this->randomMachineName();
     $edit['mail'] = $mail = $edit['name'] . '@example.com';
     $this->drupalPostForm('user/register', $edit, t('Create new account'));
     $this->assertText(t('A welcome message with further instructions has been sent to your email address.'), 'User registered successfully.');
     $accounts = entity_load_multiple_by_properties('user', array('name' => $name, 'mail' => $mail));
     $new_user = reset($accounts);
     $this->assertTrue($new_user->isActive(), 'New account is active after registration.');
     $resetURL = user_pass_reset_url($new_user);
     $this->drupalGet($resetURL);
     $this->assertTitle(t('Set password | Drupal'), 'Page title is "Set password".');
     // Allow registration by site visitors, but require administrator approval.
     $config->set('register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)->save();
     $edit = array();
     $edit['name'] = $name = $this->randomMachineName();
     $edit['mail'] = $mail = $edit['name'] . '@example.com';
     $this->drupalPostForm('user/register', $edit, t('Create new account'));
     $this->container->get('entity.manager')->getStorage('user')->resetCache();
     $accounts = entity_load_multiple_by_properties('user', array('name' => $name, 'mail' => $mail));
     $new_user = reset($accounts);
     $this->assertFalse($new_user->isActive(), 'New account is blocked until approved by an administrator.');
 }
Example #2
0
 public function passResetUrl($path = '')
 {
     $options = array();
     if ($path) {
         $options['query']['destination'] = $path;
     }
     // D6,D7 append a /login. Otherwise identical to D8+.
     return drush_url(user_pass_reset_url($this->account) . '/login', $options);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('user-id');
     $user = $this->entityTypeManager->getStorage('user')->load($uid);
     if (!$user) {
         $io->error(sprintf($this->trans('commands.user.login.url.errors.invalid-user'), $uid));
         return 1;
     }
     $url = user_pass_reset_url($user);
     $io->success(sprintf($this->trans('commands.user.login.url.messages.url'), $user->getUsername(), $url));
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('user-id');
     $user = $this->getEntityManager()->getStorage('user')->load($uid);
     if (!$user) {
         $text = $this->trans('commands.user.login.url.errors.invalid-user');
         $text = SafeMarkup::format($text, ['@uid' => $uid]);
         $io->error($text);
         return;
     }
     $url = user_pass_reset_url($user);
     $text = $this->trans('commands.user.login.url.messages.url');
     $text = SafeMarkup::format($text, ['@name' => $user->getUsername(), '@url' => $url]);
     $io->success($text);
 }
 /**
  * Creates a user, then tests the tokens generated from it.
  */
 function testUserTokenReplacement()
 {
     $token_service = \Drupal::token();
     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
     $url_options = array('absolute' => TRUE, 'language' => $language_interface);
     // Create two users and log them in one after another.
     $user1 = $this->drupalCreateUser(array());
     $user2 = $this->drupalCreateUser(array());
     $this->drupalLogin($user1);
     $this->drupalLogout();
     $this->drupalLogin($user2);
     $account = user_load($user1->id());
     $global_account = user_load(\Drupal::currentUser()->id());
     // Generate and test sanitized tokens.
     $tests = array();
     $tests['[user:uid]'] = $account->id();
     $tests['[user:name]'] = String::checkPlain(user_format_name($account));
     $tests['[user:mail]'] = String::checkPlain($account->getEmail());
     $tests['[user:url]'] = $account->url('canonical', $url_options);
     $tests['[user:edit-url]'] = $account->url('edit-form', $url_options);
     $tests['[user:last-login]'] = format_date($account->getLastLoginTime(), 'medium', '', NULL, $language_interface->getId());
     $tests['[user:last-login:short]'] = format_date($account->getLastLoginTime(), 'short', '', NULL, $language_interface->getId());
     $tests['[user:created]'] = format_date($account->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
     $tests['[user:created:short]'] = format_date($account->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
     $tests['[current-user:name]'] = String::checkPlain(user_format_name($global_account));
     // Test to make sure that we generated something for each token.
     $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId()));
         $this->assertEqual($output, $expected, format_string('Sanitized user token %token replaced.', array('%token' => $input)));
     }
     // Generate and test unsanitized tokens.
     $tests['[user:name]'] = user_format_name($account);
     $tests['[user:mail]'] = $account->getEmail();
     $tests['[current-user:name]'] = user_format_name($global_account);
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId(), 'sanitize' => FALSE));
         $this->assertEqual($output, $expected, format_string('Unsanitized user token %token replaced.', array('%token' => $input)));
     }
     // Generate login and cancel link.
     $tests = array();
     $tests['[user:one-time-login-url]'] = user_pass_reset_url($account);
     $tests['[user:cancel-url]'] = user_cancel_url($account);
     // Generate tokens with interface language.
     $link = \Drupal::url('user.page', [], array('absolute' => TRUE));
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId(), 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
         $this->assertTrue(strpos($output, $link) === 0, 'Generated URL is in interface language.');
     }
     // Generate tokens with the user's preferred language.
     $account->preferred_langcode = 'de';
     $account->save();
     $link = \Drupal::url('user.page', [], array('language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()), 'absolute' => TRUE));
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, array('user' => $account), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
         $this->assertTrue(strpos($output, $link) === 0, "Generated URL is in the user's preferred language.");
     }
     // Generate tokens with one specific language.
     $link = \Drupal::url('user.page', [], array('language' => \Drupal::languageManager()->getLanguage('de'), 'absolute' => TRUE));
     foreach ($tests as $input => $expected) {
         foreach (array($user1, $user2) as $account) {
             $output = $token_service->replace($input, array('user' => $account), array('langcode' => 'de', 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
             $this->assertTrue(strpos($output, $link) === 0, "Generated URL in in the requested language.");
         }
     }
 }
 /**
  * Make sure that users cannot forge password reset URLs of other users.
  */
 function testResetImpersonation()
 {
     // Create two identical user accounts except for the user name. They must
     // have the same empty password, so we can't use $this->drupalCreateUser().
     $edit = array();
     $edit['name'] = $this->randomMachineName();
     $edit['mail'] = $edit['name'] . '@example.com';
     $edit['status'] = 1;
     $user1 = User::create($edit);
     $user1->save();
     $edit['name'] = $this->randomMachineName();
     $user2 = User::create($edit);
     $user2->save();
     // Unique password hashes are automatically generated, the only way to
     // change that is to update it directly in the database.
     db_update('users_field_data')->fields(['pass' => NULL])->condition('uid', [$user1->id(), $user2->id()], 'IN')->execute();
     \Drupal::entityManager()->getStorage('user')->resetCache();
     $user1 = User::load($user1->id());
     $user2 = User::load($user2->id());
     $this->assertEqual($user1->getPassword(), $user2->getPassword(), 'Both users have the same password hash.');
     // The password reset URL must not be valid for the second user when only
     // the user ID is changed in the URL.
     $reset_url = user_pass_reset_url($user1);
     $attack_reset_url = str_replace("user/reset/{$user1->id()}", "user/reset/{$user2->id()}", $reset_url);
     $this->drupalGet($attack_reset_url);
     $this->assertNoText($user2->getUsername(), 'The invalid password reset page does not show the user name.');
     $this->assertUrl('user/password', array(), 'The user is redirected to the password reset request page.');
     $this->assertText('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.');
 }
Example #7
0
 /**
  * Build a one time login link.
  *
  * @param string $path
  * @return string
  */
 public function passResetUrl($path = '')
 {
     $url = user_pass_reset_url($this->account);
     if ($path) {
         $url .= '?destination=' . $path;
     }
     return $url;
 }
Example #8
0
 /**
  * Creates a user, then tests the tokens generated from it.
  */
 function testUserTokenReplacement()
 {
     $token_service = \Drupal::token();
     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
     $url_options = array('absolute' => TRUE, 'language' => $language_interface);
     \Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
     \Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE);
     // Create two users and log them in one after another.
     $user1 = $this->drupalCreateUser(array());
     $user2 = $this->drupalCreateUser(array());
     $this->drupalLogin($user1);
     $this->drupalLogout();
     $this->drupalLogin($user2);
     $account = User::load($user1->id());
     $global_account = User::load(\Drupal::currentUser()->id());
     // Generate and test tokens.
     $tests = array();
     $tests['[user:uid]'] = $account->id();
     $tests['[user:name]'] = $account->getAccountName();
     $tests['[user:account-name]'] = $account->getAccountName();
     $tests['[user:display-name]'] = $account->getDisplayName();
     $tests['[user:mail]'] = $account->getEmail();
     $tests['[user:url]'] = $account->url('canonical', $url_options);
     $tests['[user:edit-url]'] = $account->url('edit-form', $url_options);
     $tests['[user:last-login]'] = format_date($account->getLastLoginTime(), 'medium', '', NULL, $language_interface->getId());
     $tests['[user:last-login:short]'] = format_date($account->getLastLoginTime(), 'short', '', NULL, $language_interface->getId());
     $tests['[user:created]'] = format_date($account->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
     $tests['[user:created:short]'] = format_date($account->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
     $tests['[current-user:name]'] = $global_account->getAccountName();
     $tests['[current-user:account-name]'] = $global_account->getAccountName();
     $tests['[current-user:display-name]'] = $global_account->getDisplayName();
     $base_bubbleable_metadata = BubbleableMetadata::createFromObject($account);
     $metadata_tests = [];
     $metadata_tests['[user:uid]'] = $base_bubbleable_metadata;
     $metadata_tests['[user:name]'] = $base_bubbleable_metadata;
     $metadata_tests['[user:account-name]'] = $base_bubbleable_metadata;
     $metadata_tests['[user:display-name]'] = $base_bubbleable_metadata;
     $metadata_tests['[user:mail]'] = $base_bubbleable_metadata;
     $metadata_tests['[user:url]'] = $base_bubbleable_metadata;
     $metadata_tests['[user:edit-url]'] = $base_bubbleable_metadata;
     $bubbleable_metadata = clone $base_bubbleable_metadata;
     // This test runs with the Language module enabled, which means config is
     // overridden by LanguageConfigFactoryOverride (to provide translations of
     // config). This causes the interface language cache context to be added for
     // config entities. The four next tokens use DateFormat Config entities, and
     // therefore have the interface language cache context.
     $bubbleable_metadata->addCacheContexts(['languages:language_interface']);
     $metadata_tests['[user:last-login]'] = $bubbleable_metadata->addCacheTags(['rendered']);
     $metadata_tests['[user:last-login:short]'] = $bubbleable_metadata;
     $metadata_tests['[user:created]'] = $bubbleable_metadata;
     $metadata_tests['[user:created:short]'] = $bubbleable_metadata;
     $metadata_tests['[current-user:name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
     $metadata_tests['[current-user:account-name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
     $metadata_tests['[current-user:display-name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
     // Test to make sure that we generated something for each token.
     $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
     foreach ($tests as $input => $expected) {
         $bubbleable_metadata = new BubbleableMetadata();
         $output = $token_service->replace($input, ['user' => $account], ['langcode' => $language_interface->getId()], $bubbleable_metadata);
         $this->assertEqual($output, $expected, new FormattableMarkup('User token %token replaced.', ['%token' => $input]));
         $this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
     }
     // Generate tokens for the anonymous user.
     $anonymous_user = User::load(0);
     $tests = [];
     $tests['[user:uid]'] = t('not yet assigned');
     $tests['[user:display-name]'] = $anonymous_user->getDisplayName();
     $base_bubbleable_metadata = BubbleableMetadata::createFromObject($anonymous_user);
     $metadata_tests = [];
     $metadata_tests['[user:uid]'] = $base_bubbleable_metadata;
     $bubbleable_metadata = clone $base_bubbleable_metadata;
     $bubbleable_metadata->addCacheableDependency(\Drupal::config('user.settings'));
     $metadata_tests['[user:display-name]'] = $bubbleable_metadata;
     foreach ($tests as $input => $expected) {
         $bubbleable_metadata = new BubbleableMetadata();
         $output = $token_service->replace($input, array('user' => $anonymous_user), array('langcode' => $language_interface->getId()), $bubbleable_metadata);
         $this->assertEqual($output, $expected, format_string('Sanitized user token %token replaced.', array('%token' => $input)));
         $this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
     }
     // Generate login and cancel link.
     $tests = array();
     $tests['[user:one-time-login-url]'] = user_pass_reset_url($account);
     $tests['[user:cancel-url]'] = user_cancel_url($account);
     // Generate tokens with interface language.
     $link = \Drupal::url('user.page', [], array('absolute' => TRUE));
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, ['user' => $account], ['langcode' => $language_interface->getId(), 'callback' => 'user_mail_tokens', 'clear' => TRUE]);
         $this->assertTrue(strpos($output, $link) === 0, 'Generated URL is in interface language.');
     }
     // Generate tokens with the user's preferred language.
     $account->preferred_langcode = 'de';
     $account->save();
     $link = \Drupal::url('user.page', [], array('language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()), 'absolute' => TRUE));
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, ['user' => $account], ['callback' => 'user_mail_tokens', 'clear' => TRUE]);
         $this->assertTrue(strpos($output, $link) === 0, "Generated URL is in the user's preferred language.");
     }
     // Generate tokens with one specific language.
     $link = \Drupal::url('user.page', [], array('language' => \Drupal::languageManager()->getLanguage('de'), 'absolute' => TRUE));
     foreach ($tests as $input => $expected) {
         foreach (array($user1, $user2) as $account) {
             $output = $token_service->replace($input, ['user' => $account], ['langcode' => 'de', 'callback' => 'user_mail_tokens', 'clear' => TRUE]);
             $this->assertTrue(strpos($output, $link) === 0, "Generated URL in the requested language.");
         }
     }
     // Generate user display name tokens when safe markup is returned.
     // @see user_hooks_test_user_format_name_alter()
     \Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE);
     $input = '[user:display-name] [current-user:display-name]';
     $expected = "<em>{$user1->id()}</em> <em>{$user2->id()}</em>";
     $output = $token_service->replace($input, ['user' => $user1]);
     $this->assertEqual($output, $expected, new FormattableMarkup('User token %token does not escape safe markup.', ['%token' => 'display-name']));
 }
Example #9
0
function createNewUser($form_state)
{
    //This will generate a random password, you could set your own here
    $password = user_password(8);
    $userName = $form_state['values']['firstName'] . ' ' . $form_state['values']['lastName'];
    //set up the user fields
    $fields = array('name' => $form_state['values']['primaryEmail'], 'mail' => $form_state['values']['primaryEmail'], 'pass' => $password, 'status' => 1, 'init' => 'email address', 'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'));
    //the first parameter is left blank so a new user is created
    $account = user_save('', $fields);
    // Manually set the password so it appears in the e-mail.
    $account->password = $fields['pass'];
    // Send the e-mail through the user module.
    $params['url'] = user_pass_reset_url($account);
    $params['teamName'] = dbGetTeamName($form_state['TID']);
    drupal_mail('users', 'userCreated', $form_state['values']['primaryEmail'], NULL, $params, '*****@*****.**');
    $fields = array('firstName', 'lastName');
    $profileData = getFields($fields, $form_state['values']);
    $profileData = stripTags($profileData, '');
    $profileData['UID'] = $account->uid;
    dbCreateProfile($profileData);
    // creating new profile
    return $profileData['UID'];
}