3 namespace Drupal\Tests\user\Functional;
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Entity\Entity\EntityFormDisplay;
7 use Drupal\Core\Field\FieldStorageDefinitionInterface;
8 use Drupal\field\Entity\FieldConfig;
9 use Drupal\field\Entity\FieldStorageConfig;
10 use Drupal\Tests\BrowserTestBase;
13 * Tests registration of user under different configurations.
17 class UserRegistrationTest extends BrowserTestBase {
24 public static $modules = ['field_test'];
26 public function testRegistrationWithEmailVerification() {
27 $config = $this->config('user.settings');
28 // Require email verification.
29 $config->set('verify_mail', TRUE)->save();
31 // Set registration to administrator only.
32 $config->set('register', USER_REGISTER_ADMINISTRATORS_ONLY)->save();
33 $this->drupalGet('user/register');
34 $this->assertResponse(403, 'Registration page is inaccessible when only administrators can create accounts.');
36 // Allow registration by site visitors without administrator approval.
37 $config->set('register', USER_REGISTER_VISITORS)->save();
39 $edit['name'] = $name = $this->randomMachineName();
40 $edit['mail'] = $mail = $edit['name'] . '@example.com';
41 $this->drupalPostForm('user/register', $edit, t('Create new account'));
42 $this->assertText(t('A welcome message with further instructions has been sent to your email address.'), 'User registered successfully.');
44 /** @var EntityStorageInterface $storage */
45 $storage = $this->container->get('entity_type.manager')->getStorage('user');
46 $accounts = $storage->loadByProperties(['name' => $name, 'mail' => $mail]);
47 $new_user = reset($accounts);
48 $this->assertTrue($new_user->isActive(), 'New account is active after registration.');
49 $resetURL = user_pass_reset_url($new_user);
50 $this->drupalGet($resetURL);
51 $this->assertTitle(t('Set password | Drupal'), 'Page title is "Set password".');
53 // Allow registration by site visitors, but require administrator approval.
54 $config->set('register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)->save();
56 $edit['name'] = $name = $this->randomMachineName();
57 $edit['mail'] = $mail = $edit['name'] . '@example.com';
58 $this->drupalPostForm('user/register', $edit, t('Create new account'));
59 $this->container->get('entity.manager')->getStorage('user')->resetCache();
60 $accounts = $storage->loadByProperties(['name' => $name, 'mail' => $mail]);
61 $new_user = reset($accounts);
62 $this->assertFalse($new_user->isActive(), 'New account is blocked until approved by an administrator.');
65 public function testRegistrationWithoutEmailVerification() {
66 $config = $this->config('user.settings');
67 // Don't require email verification and allow registration by site visitors
68 // without administrator approval.
70 ->set('verify_mail', FALSE)
71 ->set('register', USER_REGISTER_VISITORS)
75 $edit['name'] = $name = $this->randomMachineName();
76 $edit['mail'] = $mail = $edit['name'] . '@example.com';
78 // Try entering a mismatching password.
79 $edit['pass[pass1]'] = '99999.0';
80 $edit['pass[pass2]'] = '99999';
81 $this->drupalPostForm('user/register', $edit, t('Create new account'));
82 $this->assertText(t('The specified passwords do not match.'), 'Typing mismatched passwords displays an error message.');
84 // Enter a correct password.
85 $edit['pass[pass1]'] = $new_pass = $this->randomMachineName();
86 $edit['pass[pass2]'] = $new_pass;
87 $this->drupalPostForm('user/register', $edit, t('Create new account'));
88 $this->container->get('entity.manager')->getStorage('user')->resetCache();
89 $accounts = $this->container->get('entity_type.manager')->getStorage('user')
90 ->loadByProperties(['name' => $name, 'mail' => $mail]);
91 $new_user = reset($accounts);
92 $this->assertNotNull($new_user, 'New account successfully created with matching passwords.');
93 $this->assertText(t('Registration successful. You are now logged in.'), 'Users are logged in after registering.');
94 $this->drupalLogout();
96 // Allow registration by site visitors, but require administrator approval.
97 $config->set('register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)->save();
99 $edit['name'] = $name = $this->randomMachineName();
100 $edit['mail'] = $mail = $edit['name'] . '@example.com';
101 $edit['pass[pass1]'] = $pass = $this->randomMachineName();
102 $edit['pass[pass2]'] = $pass;
103 $this->drupalPostForm('user/register', $edit, t('Create new account'));
104 $this->assertText(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.'), 'Users are notified of pending approval');
106 // Try to log in before administrator approval.
111 $this->drupalPostForm('user/login', $auth, t('Log in'));
112 $this->assertText(t('The username @name has not been activated or is blocked.', ['@name' => $name]), 'User cannot log in yet.');
114 // Activate the new account.
115 $accounts = $this->container->get('entity_type.manager')->getStorage('user')
116 ->loadByProperties(['name' => $name, 'mail' => $mail]);
117 $new_user = reset($accounts);
118 $admin_user = $this->drupalCreateUser(['administer users']);
119 $this->drupalLogin($admin_user);
123 $this->drupalPostForm('user/' . $new_user->id() . '/edit', $edit, t('Save'));
124 $this->drupalLogout();
126 // Log in after administrator approval.
127 $this->drupalPostForm('user/login', $auth, t('Log in'));
128 $this->assertText(t('Member for'), 'User can log in after administrator approval.');
131 public function testRegistrationEmailDuplicates() {
132 // Don't require email verification and allow registration by site visitors
133 // without administrator approval.
134 $this->config('user.settings')
135 ->set('verify_mail', FALSE)
136 ->set('register', USER_REGISTER_VISITORS)
139 // Set up a user to check for duplicates.
140 $duplicate_user = $this->drupalCreateUser();
143 $edit['name'] = $this->randomMachineName();
144 $edit['mail'] = $duplicate_user->getEmail();
146 // Attempt to create a new account using an existing email address.
147 $this->drupalPostForm('user/register', $edit, t('Create new account'));
148 $this->assertText(t('The email address @email is already taken.', ['@email' => $duplicate_user->getEmail()]), 'Supplying an exact duplicate email address displays an error message');
150 // Attempt to bypass duplicate email registration validation by adding spaces.
151 $edit['mail'] = ' ' . $duplicate_user->getEmail() . ' ';
153 $this->drupalPostForm('user/register', $edit, t('Create new account'));
154 $this->assertText(t('The email address @email is already taken.', ['@email' => $duplicate_user->getEmail()]), 'Supplying a duplicate email address with added whitespace displays an error message');
158 * Tests that UUID isn't cached in form state on register form.
160 * This is a regression test for https://www.drupal.org/node/2500527 to ensure
161 * that the form is not cached on GET requests.
163 public function testUuidFormState() {
164 \Drupal::service('module_installer')->install(['image']);
165 \Drupal::service('router.builder')->rebuild();
167 // Add a picture field in order to ensure that no form cache is written,
168 // which breaks registration of more than 1 user every 6 hours.
169 $field_storage = FieldStorageConfig::create([
170 'field_name' => 'user_picture',
171 'entity_type' => 'user',
174 $field_storage->save();
176 $field = FieldConfig::create([
177 'field_name' => 'user_picture',
178 'entity_type' => 'user',
183 $form_display = EntityFormDisplay::create([
184 'targetEntityType' => 'user',
189 $form_display->setComponent('user_picture', [
190 'type' => 'image_image',
192 $form_display->save();
194 // Don't require email verification and allow registration by site visitors
195 // without administrator approval.
196 $this->config('user.settings')
197 ->set('verify_mail', FALSE)
198 ->set('register', USER_REGISTER_VISITORS)
202 $edit['name'] = $this->randomMachineName();
203 $edit['mail'] = $edit['name'] . '@example.com';
204 $edit['pass[pass2]'] = $edit['pass[pass1]'] = $this->randomMachineName();
206 // Create one account.
207 $this->drupalPostForm('user/register', $edit, t('Create new account'));
208 $this->assertResponse(200);
210 $user_storage = \Drupal::entityManager()->getStorage('user');
212 $this->assertTrue($user_storage->loadByProperties(['name' => $edit['name']]));
213 $this->drupalLogout();
215 // Create a second account.
216 $edit['name'] = $this->randomMachineName();
217 $edit['mail'] = $edit['name'] . '@example.com';
218 $edit['pass[pass2]'] = $edit['pass[pass1]'] = $this->randomMachineName();
220 $this->drupalPostForm('user/register', $edit, t('Create new account'));
221 $this->assertResponse(200);
223 $this->assertTrue($user_storage->loadByProperties(['name' => $edit['name']]));
226 public function testRegistrationDefaultValues() {
227 // Don't require email verification and allow registration by site visitors
228 // without administrator approval.
229 $config_user_settings = $this->config('user.settings')
230 ->set('verify_mail', FALSE)
231 ->set('register', USER_REGISTER_VISITORS)
234 // Set the default timezone to Brussels.
235 $config_system_date = $this->config('system.date')
236 ->set('timezone.user.configurable', 1)
237 ->set('timezone.default', 'Europe/Brussels')
240 // Check the presence of expected cache tags.
241 $this->drupalGet('user/register');
242 $this->assertCacheTag('config:user.settings');
245 $edit['name'] = $name = $this->randomMachineName();
246 $edit['mail'] = $mail = $edit['name'] . '@example.com';
247 $edit['pass[pass1]'] = $new_pass = $this->randomMachineName();
248 $edit['pass[pass2]'] = $new_pass;
249 $this->drupalPostForm(NULL, $edit, t('Create new account'));
251 // Check user fields.
252 $accounts = $this->container->get('entity_type.manager')->getStorage('user')
253 ->loadByProperties(['name' => $name, 'mail' => $mail]);
254 $new_user = reset($accounts);
255 $this->assertEqual($new_user->getUsername(), $name, 'Username matches.');
256 $this->assertEqual($new_user->getEmail(), $mail, 'Email address matches.');
257 $this->assertTrue(($new_user->getCreatedTime() > REQUEST_TIME - 20), 'Correct creation time.');
258 $this->assertEqual($new_user->isActive(), $config_user_settings->get('register') == USER_REGISTER_VISITORS ? 1 : 0, 'Correct status field.');
259 $this->assertEqual($new_user->getTimezone(), $config_system_date->get('timezone.default'), 'Correct time zone field.');
260 $this->assertEqual($new_user->langcode->value, \Drupal::languageManager()->getDefaultLanguage()->getId(), 'Correct language field.');
261 $this->assertEqual($new_user->preferred_langcode->value, \Drupal::languageManager()->getDefaultLanguage()->getId(), 'Correct preferred language field.');
262 $this->assertEqual($new_user->init->value, $mail, 'Correct init field.');
266 * Tests username and email field constraints on user registration.
268 * @see \Drupal\user\Plugin\Validation\Constraint\UserNameUnique
269 * @see \Drupal\user\Plugin\Validation\Constraint\UserMailUnique
271 public function testUniqueFields() {
272 $account = $this->drupalCreateUser();
274 $edit = ['mail' => 'test@example.com', 'name' => $account->getUsername()];
275 $this->drupalPostForm('user/register', $edit, t('Create new account'));
276 $this->assertRaw(new FormattableMarkup('The username %value is already taken.', ['%value' => $account->getUsername()]));
278 $edit = ['mail' => $account->getEmail(), 'name' => $this->randomString()];
279 $this->drupalPostForm('user/register', $edit, t('Create new account'));
280 $this->assertRaw(new FormattableMarkup('The email address %value is already taken.', ['%value' => $account->getEmail()]));
284 * Tests Field API fields on user registration forms.
286 public function testRegistrationWithUserFields() {
287 // Create a field on 'user' entity type.
288 $field_storage = FieldStorageConfig::create([
289 'field_name' => 'test_user_field',
290 'entity_type' => 'user',
291 'type' => 'test_field',
294 $field_storage->save();
295 $field = FieldConfig::create([
296 'field_storage' => $field_storage,
297 'label' => 'Some user field',
302 entity_get_form_display('user', 'user', 'default')
303 ->setComponent('test_user_field', ['type' => 'test_field_widget'])
305 entity_get_form_display('user', 'user', 'register')
308 // Check that the field does not appear on the registration form.
309 $this->drupalGet('user/register');
310 $this->assertNoText($field->label(), 'The field does not appear on user registration form');
311 $this->assertCacheTag('config:core.entity_form_display.user.user.register');
312 $this->assertCacheTag('config:user.settings');
314 // Have the field appear on the registration form.
315 entity_get_form_display('user', 'user', 'register')
316 ->setComponent('test_user_field', ['type' => 'test_field_widget'])
319 $this->drupalGet('user/register');
320 $this->assertText($field->label(), 'The field appears on user registration form');
321 $this->assertRegistrationFormCacheTagsWithUserFields();
323 // Check that validation errors are correctly reported.
325 $edit['name'] = $name = $this->randomMachineName();
326 $edit['mail'] = $mail = $edit['name'] . '@example.com';
327 // Missing input in required field.
328 $edit['test_user_field[0][value]'] = '';
329 $this->drupalPostForm(NULL, $edit, t('Create new account'));
330 $this->assertRegistrationFormCacheTagsWithUserFields();
331 $this->assertRaw(t('@name field is required.', ['@name' => $field->label()]), 'Field validation error was correctly reported.');
333 $edit['test_user_field[0][value]'] = '-1';
334 $this->drupalPostForm(NULL, $edit, t('Create new account'));
335 $this->assertRegistrationFormCacheTagsWithUserFields();
336 $this->assertRaw(t('%name does not accept the value -1.', ['%name' => $field->label()]), 'Field validation error was correctly reported.');
338 // Submit with valid data.
339 $value = rand(1, 255);
340 $edit['test_user_field[0][value]'] = $value;
341 $this->drupalPostForm(NULL, $edit, t('Create new account'));
342 // Check user fields.
343 $accounts = $this->container->get('entity_type.manager')->getStorage('user')
344 ->loadByProperties(['name' => $name, 'mail' => $mail]);
345 $new_user = reset($accounts);
346 $this->assertEqual($new_user->test_user_field->value, $value, 'The field value was correctly saved.');
348 // Check that the 'add more' button works.
349 $field_storage->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
350 $field_storage->save();
351 $this->drupalGet('user/register');
352 $this->assertRegistrationFormCacheTagsWithUserFields();
354 $value = rand(1, 255);
356 $edit['test_user_field[0][value]'] = $value;
357 $this->drupalPostForm(NULL, $edit, t('Add another item'));
358 $this->drupalPostForm(NULL, $edit, t('Add another item'));
359 // Submit with three values.
360 $edit['test_user_field[1][value]'] = $value + 1;
361 $edit['test_user_field[2][value]'] = $value + 2;
362 $edit['name'] = $name = $this->randomMachineName();
363 $edit['mail'] = $mail = $edit['name'] . '@example.com';
364 $this->drupalPostForm(NULL, $edit, t('Create new account'));
365 // Check user fields.
366 $accounts = $this->container->get('entity_type.manager')->getStorage('user')
367 ->loadByProperties(['name' => $name, 'mail' => $mail]);
368 $new_user = reset($accounts);
369 $this->assertEqual($new_user->test_user_field[0]->value, $value, 'The field value was correctly saved.');
370 $this->assertEqual($new_user->test_user_field[1]->value, $value + 1, 'The field value was correctly saved.');
371 $this->assertEqual($new_user->test_user_field[2]->value, $value + 2, 'The field value was correctly saved.');
375 * Asserts the presence of cache tags on registration form with user fields.
377 protected function assertRegistrationFormCacheTagsWithUserFields() {
378 $this->assertCacheTag('config:core.entity_form_display.user.user.register');
379 $this->assertCacheTag('config:field.field.user.user.test_user_field');
380 $this->assertCacheTag('config:field.storage.user.test_user_field');
381 $this->assertCacheTag('config:user.settings');