public function content()
 {
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $userId = $user->get('uid')->value;
     $data = array(array('job_title' => '', 'job_path' => '', 'company_name' => '', 'application_date' => ''));
     $appliedJobs = db_select('user_job_application', 'uja')->condition('uja.user_id', $userId, '=')->fields('uja', array('job_id', 'date'))->orderBy('uja.date', 'DESC')->execute()->fetchAll();
     if ($appliedJobs) {
         $x = 0;
         foreach ($appliedJobs as $appliedJob) {
             $jobNode = \Drupal\node\Entity\Node::load($appliedJob->job_id);
             $jobTitle = $jobNode->getTitle();
             $jobPathAlias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $appliedJob->job_id);
             $companyNodeEntity = $jobNode->get('field_company');
             $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
             $companyName = $companyNode->getTitle();
             $data[$x]['job_title'] = $jobTitle;
             $data[$x]['job_path'] = $jobPathAlias;
             $data[$x]['company_name'] = $companyName;
             $data[$x]['application_date'] = $appliedJob->date;
             $x++;
         }
     }
     $markUp = $this->createMarkUp($data);
     return array('#type' => 'markup', '#markup' => $markUp);
 }
 /**
  * {@inheritdoc}
  *
  * When the $operation is 'add' then the $entity is of type 'profile_type',
  * otherwise $entity is of type 'profile'.
  */
 protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account)
 {
     $account = $this->prepareUser($account);
     $user_page = \Drupal::request()->attributes->get('user');
     // Some times, operation edit is called update.
     // Use edit in any case.
     if ($operation == 'update') {
         $operation = 'edit';
     }
     // Check that if profile type has require roles, the user the profile is
     // being added to has any of the required roles.
     if ($entity->getEntityTypeId() == 'profile') {
         $profile_roles = ProfileType::load($entity->bundle())->getRoles();
         $user_roles = $entity->getOwner()->getRoles(TRUE);
         if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) {
             return AccessResult::forbidden();
         }
     } elseif ($entity->getEntityTypeId() == 'profile_type') {
         $profile_roles = $entity->getRoles();
         $user_roles = User::load($user_page->id())->getRoles(TRUE);
         if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) {
             return AccessResult::forbidden();
         }
     }
     if ($account->hasPermission('bypass profile access')) {
         return AccessResult::allowed()->cachePerPermissions();
     } elseif ($operation == 'add' && ($user_page->id() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->id() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->id() . ' profile')) || $operation != 'add' && ($entity->getOwnerId() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->getType() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->getType() . ' profile'))) {
         return AccessResult::allowed()->cachePerPermissions();
     } else {
         return AccessResult::forbidden()->cachePerPermissions();
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installSchema('system', 'sequences');
     $this->installEntitySchema('user');
     $this->manager = $this->container->get('plugin.manager.condition');
     // Set up the authenticated and anonymous roles.
     Role::create(array('id' => DRUPAL_ANONYMOUS_RID, 'label' => 'Anonymous user'))->save();
     Role::create(array('id' => DRUPAL_AUTHENTICATED_RID, 'label' => 'Authenticated user'))->save();
     // Create new role.
     $rid = strtolower($this->randomMachineName(8));
     $label = $this->randomString(8);
     $role = Role::create(array('id' => $rid, 'label' => $label));
     $role->save();
     $this->role = $role;
     // Setup an anonymous user for our tests.
     $this->anonymous = User::create(array('uid' => 0));
     $this->anonymous->save();
     // Loading the anonymous user adds the correct role.
     $this->anonymous = User::load($this->anonymous->id());
     // Setup an authenticated user for our tests.
     $this->authenticated = User::create(array('name' => $this->randomMachineName()));
     $this->authenticated->save();
     // Add the custom role.
     $this->authenticated->addRole($this->role->id());
 }
 /**
  * Helper function, which creates node of type person
  *
  * @param \Drupal\user\Entity\User $user
  * @param bool $isIndividualSponsor
  */
 public function createUserProfile(User $user, $isIndividualSponsor = FALSE)
 {
     $values = ['type' => 'person', 'title' => $user->getUsername(), 'uid' => 1, 'field_referenced_user' => ['target_id' => $user->id()]];
     if ($isIndividualSponsor) {
         $values['field_person_type'] = ['target_id' => 8];
     }
     $node = entity_create('node', $values);
     $node->save();
 }
 /**
  * {@inheritdoc}
  */
 protected function setUpFixtures()
 {
     $this->installEntitySchema('user');
     $this->installConfig(array('user'));
     parent::setUpFixtures();
     // Create a record for uid 1.
     $this->rootUser = User::create(['name' => $this->randomMachineName()]);
     $this->rootUser->save();
     Views::viewsData()->clear();
 }
Esempio n. 6
0
 /**
  * Checks whether skip() marks the check as skipped, and checks the
  * skippedBy() value.
  */
 public function testSkipCheck()
 {
     foreach ($this->checks as $check) {
         $check->skip();
         $isSkipped = $check->isSkipped();
         $skippedBy = $check->skippedBy();
         $this->assertTrue($isSkipped, $check->getTitle() . ' skipped.');
         $this->assertEqual($this->user->id(), $skippedBy->id(), 'Skipped by ' . $skippedBy->label());
     }
 }
 /**
  * Overrides \Drupal\views\Tests\ViewUnitTestBase::setUpFixtures().
  */
 protected function setUpFixtures()
 {
     $this->installEntitySchema('user');
     $this->installConfig(array('user'));
     parent::setUpFixtures();
     // Create a record for uid 1.
     $this->installSchema('system', 'sequences');
     $this->root_user = entity_create('user', array('name' => $this->randomMachineName()));
     $this->root_user->save();
     Views::viewsData()->clear();
 }
Esempio n. 8
0
 /**
  * Tests that CSRF check is not triggered for Basic Auth requests.
  */
 public function testBasicAuth()
 {
     $curl_options = $this->getCurlOptions();
     $curl_options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
     $curl_options[CURLOPT_USERPWD] = $this->account->getUsername() . ':' . $this->account->pass_raw;
     $this->curlExec($curl_options);
     $this->assertResponse(201);
     // Ensure that the entity was created.
     $loaded_entity = $this->loadEntityFromLocationHeader($this->drupalGetHeader('location'));
     $this->assertTrue($loaded_entity, 'An entity was created in the database');
 }
 /**
  * Provide a list of tokens.
  */
 public function tokenList(User $user)
 {
     $entity_type = 'access_token';
     $storage = $this->entityManager()->getStorage($entity_type);
     $ids = $storage->getQuery()->condition('auth_user_id', $user->id())->execute();
     if (empty($ids)) {
         return ['#markup' => $this->t('There are no tokens for this user.')];
     }
     $view_controller = $this->entityManager()->getViewBuilder($entity_type);
     $tokens = $storage->loadMultiple($ids);
     return $view_controller->viewMultiple($tokens);
 }
 /**
  * Creates a test entity.
  *
  * @param string $entity_type
  *   An entity type.
  *
  * @return \Drupal\Core\Entity\EntityInterface
  *   The created test entity.
  */
 protected function createTestEntity($entity_type)
 {
     $this->entity_name = $this->randomMachineName();
     $this->entity_user = $this->createUser();
     $this->entity_field_text = $this->randomMachineName();
     // Pass in the value of the name field when creating. With the user
     // field we test setting a field after creation.
     $entity = entity_create($entity_type);
     $entity->user_id->target_id = $this->entity_user->id();
     $entity->name->value = $this->entity_name;
     // Set a value for the test field.
     $entity->field_test_text->value = $this->entity_field_text;
     return $entity;
 }
Esempio n. 11
0
 /**
  * Sets new hash password in smf
  *
  * @param \Drupal\User\Entity\User $drupalUser
  * @param \stdClass $smfMember
  */
 protected function syncSmfPassword(\Drupal\User\Entity\User $drupalUser, \stdClass $smfMember)
 {
     /**
      * @var \Drupal\Core\Database\Connection $this ->smfConnection
      */
     $hashedPasswd = sha1($drupalUser->getPassword());
     $id_member = $this->smfConnection->select('members', 'm')->fields('m', ['id_member'])->condition('m.member_name', $drupalUser->getUsername())->condition('m.passwd', $hashedPasswd)->execute()->fetchField();
     if (!$id_member) {
         $updateResult = $this->smfConnection->update('members')->fields(['passwd' => $hashedPasswd, 'password_salt' => ''])->condition('member_name', $drupalUser->getUsername())->execute();
         if ($updateResult) {
             $smfMember->passwd = $hashedPasswd;
         }
     }
 }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 protected function setUp($import_test_views = TRUE)
 {
     parent::setUp($import_test_views);
     $this->installEntitySchema('user');
     $this->installEntitySchema('comment');
     // Create the anonymous role.
     $this->installConfig(['user']);
     // Create an anonymous user.
     $storage = \Drupal::entityManager()->getStorage('user');
     // Insert a row for the anonymous user.
     $storage->create(array('uid' => 0, 'name' => '', 'status' => 0))->save();
     $admin_role = Role::create(['id' => 'admin', 'permissions' => ['administer comments', 'access user profiles']]);
     $admin_role->save();
     /* @var \Drupal\user\RoleInterface $anonymous_role */
     $anonymous_role = Role::load(Role::ANONYMOUS_ID);
     $anonymous_role->grantPermission('access comments');
     $anonymous_role->save();
     $this->adminUser = User::create(['name' => $this->randomMachineName(), 'roles' => [$admin_role->id()]]);
     $this->adminUser->save();
     // Create some comments.
     $comment = Comment::create(['subject' => 'My comment title', 'uid' => $this->adminUser->id(), 'name' => $this->adminUser->label(), 'entity_type' => 'entity_test', 'comment_type' => 'entity_test', 'status' => 1]);
     $comment->save();
     $comment_anonymous = Comment::create(['subject' => 'Anonymous comment title', 'uid' => 0, 'name' => 'barry', 'mail' => '*****@*****.**', 'homepage' => 'https://example.com', 'entity_type' => 'entity_test', 'comment_type' => 'entity_test', 'created' => 123456, 'status' => 1]);
     $comment_anonymous->save();
 }
Esempio n. 13
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $config = $this->config('system.theme');
     $config->set('default', 'bartik');
     $config->set('admin', 'seven');
     $config->save();
     foreach (static::$modules as $module) {
         $function = $module . '_schema';
         module_load_install($module);
         if (function_exists($function)) {
             $schema = $function();
             $this->installSchema($module, array_keys($schema));
         }
     }
     $this->installEntitySchema('aggregator_feed');
     $this->installEntitySchema('aggregator_item');
     $this->installEntitySchema('block_content');
     $this->installEntitySchema('comment');
     $this->installEntitySchema('file');
     $this->installEntitySchema('node');
     $this->installEntitySchema('menu_link_content');
     $this->installEntitySchema('taxonomy_term');
     $this->installEntitySchema('user');
     $this->installConfig(['block_content', 'comment', 'file', 'node', 'simpletest']);
     // Install one of D8's test themes.
     \Drupal::service('theme_handler')->install(array('test_theme'));
     // Create a new user which needs to have UID 1, because that is expected by
     // the assertions from
     // \Drupal\migrate_drupal\Tests\d6\MigrateNodeRevisionTest.
     User::create(['uid' => 1, 'name' => $this->randomMachineName(), 'status' => 1])->enforceIsNew(TRUE)->save();
     $this->installMigrations('Drupal 6');
 }
Esempio n. 14
0
 /**
  * Tests some of the methods.
  *
  * @see \Drupal\user\Entity\User::getRoles()
  * @see \Drupal\user\Entity\User::addRole()
  * @see \Drupal\user\Entity\User::removeRole()
  */
 public function testUserMethods()
 {
     $role_storage = $this->container->get('entity.manager')->getStorage('user_role');
     $role_storage->create(array('id' => 'test_role_one'))->save();
     $role_storage->create(array('id' => 'test_role_two'))->save();
     $role_storage->create(array('id' => 'test_role_three'))->save();
     $values = array('uid' => 1, 'roles' => array('test_role_one'));
     $user = User::create($values);
     $this->assertTrue($user->hasRole('test_role_one'));
     $this->assertFalse($user->hasRole('test_role_two'));
     $this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_one'), $user->getRoles());
     $user->addRole('test_role_one');
     $this->assertTrue($user->hasRole('test_role_one'));
     $this->assertFalse($user->hasRole('test_role_two'));
     $this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_one'), $user->getRoles());
     $user->addRole('test_role_two');
     $this->assertTrue($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
     $this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two'), $user->getRoles());
     $user->removeRole('test_role_three');
     $this->assertTrue($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
     $this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two'), $user->getRoles());
     $user->removeRole('test_role_one');
     $this->assertFalse($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
     $this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_two'), $user->getRoles());
 }
 /**
  * Test the shortcut set migration.
  */
 public function testShortcutSetUsersMigration() {
   // Check if migrated user has correct migrated shortcut set assigned.
   $account = User::load(2);
   $shortcut_set = shortcut_current_displayed_set($account);
   /** @var \Drupal\shortcut\ShortcutSetInterface $shortcut_set */
   $this->assertIdentical('shortcut_set_2', $shortcut_set->id());
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('node');
     $this->installConfig(['node']);
     $this->installSchema('node', ['node_access']);
     $this->installSchema('system', ['sequences']);
     // Create a new user which needs to have UID 1, because that is expected by
     // the assertions from
     // \Drupal\migrate_drupal\Tests\d6\MigrateNodeRevisionTest.
     User::create(['uid' => 1, 'name' => $this->randomMachineName(), 'status' => 1])->enforceIsNew(TRUE)->save();
     $node_type = entity_create('node_type', array('type' => 'test_planet'));
     $node_type->save();
     node_add_body_field($node_type);
     $node_type = entity_create('node_type', array('type' => 'story'));
     $node_type->save();
     node_add_body_field($node_type);
     $id_mappings = array('d6_node_type' => array(array(array('test_story'), array('story'))), 'd6_filter_format' => array(array(array(1), array('filtered_html')), array(array(2), array('full_html'))), 'd6_user' => array(array(array(1), array(1)), array(array(2), array(2))), 'd6_field_instance_widget_settings' => array(array(array('page', 'field_test'), array('node', 'page', 'default', 'test'))), 'd6_field_formatter_settings' => array(array(array('page', 'default', 'node', 'field_test'), array('node', 'page', 'default', 'field_test'))));
     $this->prepareMigrations($id_mappings);
     $migration = entity_load('migration', 'd6_node_settings');
     $migration->setMigrationResult(MigrationInterface::RESULT_COMPLETED);
     // Create a test node.
     $node = entity_create('node', array('type' => 'story', 'nid' => 1, 'vid' => 1, 'revision_log' => '', 'title' => $this->randomString()));
     $node->enforceIsNew();
     $node->save();
     $node = entity_create('node', array('type' => 'test_planet', 'nid' => 3, 'vid' => 4, 'revision_log' => '', 'title' => $this->randomString()));
     $node->enforceIsNew();
     $node->save();
 }
Esempio n. 17
0
 /**
  * Tests removal of role references on role entity delete.
  *
  * @see user_user_role_delete()
  */
 public function testRoleDeleteUserRoleReferenceDelete()
 {
     // Create two test roles.
     $role_storage = $this->container->get('entity.manager')->getStorage('user_role');
     $role_storage->create(array('id' => 'test_role_one'))->save();
     $role_storage->create(array('id' => 'test_role_two'))->save();
     // Create user and assign both test roles.
     $values = array('uid' => 1, 'name' => $this->randomString(), 'roles' => array('test_role_one', 'test_role_two'));
     $user = User::create($values);
     $user->save();
     // Check that user has both roles.
     $this->assertTrue($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
     // Delete test role one.
     $test_role_one = $role_storage->load('test_role_one');
     $test_role_one->delete();
     // Load user again from the database.
     $user = User::load($user->id());
     // Check that user does not have role one anymore, still has role two.
     $this->assertFalse($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
     // Create new role with same name.
     $role_storage->create(array('id' => 'test_role_one'))->save();
     // Load user again from the database.
     $user = User::load($user->id());
     // Check that user does not have role one.
     $this->assertFalse($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
 }
 /**
  * Tests that fields are synchronized using the Subscriber form.
  */
 public function testSubscriberFormFieldSync()
 {
     // Create a subscriber for the user.
     $subscriber = Subscriber::create(array('uid' => $this->user->id(), 'mail' => '*****@*****.**'));
     $subscriber->save();
     // Edit subscriber field and assert user field is changed accordingly.
     $this->drupalLogin($this->user);
     $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id());
     $this->assertField('field_shared[0][value]');
     $this->assertRaw($this->user->field_shared->value);
     $new_value = $this->randomMachineName();
     $this->drupalPostForm(NULL, array('field_shared[0][value]' => $new_value), t('Save'));
     $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id());
     $this->assertRaw($new_value);
     $this->user = User::load($this->user->id());
     $this->assertEqual($this->user->field_shared->value, $new_value);
     // Unset the sync setting and assert field is not synced.
     $this->drupalPostForm('admin/config/people/simplenews/settings/subscriber', array('simplenews_sync_fields' => FALSE), t('Save configuration'));
     $unsynced_value = $this->randomMachineName();
     $this->drupalPostForm('admin/people/simplenews/edit/' . $subscriber->id(), array('field_shared[0][value]' => $unsynced_value), t('Save'));
     $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id());
     $this->assertRaw($unsynced_value);
     $this->user = User::load($this->user->id());
     $this->assertEqual($this->user->field_shared->value, $new_value);
     $this->assertNotEqual($this->user->field_shared->value, $unsynced_value);
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 public function create(array $values = array())
 {
     $store_config = \Drupal::config('uc_store.settings');
     // Set the primary email address.
     if (empty($values['primary_email']) && !empty($values['uid'])) {
         if ($account = User::load($values['uid'])) {
             $values['primary_email'] = $account->mail;
         }
     }
     // Set the default order status.
     if (empty($values['order_status'])) {
         $values['order_status'] = uc_order_state_default('in_checkout');
     }
     // Set the default currency.
     if (empty($values['currency'])) {
         $values['currency'] = $store_config->get('currency.code');
     }
     // Set the default country codes.
     if (empty($values['billing_country'])) {
         $values['billing_country'] = $store_config->get('address.country');
     }
     if (empty($values['delivery_country'])) {
         $values['delivery_country'] = $store_config->get('address.country');
     }
     // Set the created time to now.
     if (empty($values['created'])) {
         $values['created'] = REQUEST_TIME;
     }
     return parent::create($values);
 }
 /**
  * Test the user list items.
  */
 public function testSwitchUserListItems()
 {
     $anonymous = \Drupal::config('user.settings')->get('anonymous');
     $this->setBlockConfiguration('list_size', 2);
     // Login as web user so we are sure that this account is prioritized
     // in the list if not enougth user with 'switch users' permission are
     // present.
     $this->drupalLogin($this->webUser);
     $this->drupalLogin($this->develUser);
     $this->drupalGet('');
     // Ensure that user with 'switch users' permission are prioritized.
     $this->assertSwitchUserListCount(2);
     $this->assertSwitchUserListContainsUser($this->develUser->getUsername());
     $this->assertSwitchUserListContainsUser($this->switchUser->getUsername());
     // Ensure that blocked users are not shown in the list.
     $this->switchUser->set('status', 0)->save();
     $this->drupalGet('');
     $this->assertSwitchUserListCount(2);
     $this->assertSwitchUserListContainsUser($this->develUser->getUsername());
     $this->assertSwitchUserListContainsUser($this->webUser->getUsername());
     $this->assertSwitchUserListNoContainsUser($this->switchUser->getUsername());
     // Ensure that anonymous user are prioritized if include_anon is set to true.
     $this->setBlockConfiguration('include_anon', TRUE);
     $this->drupalGet('');
     $this->assertSwitchUserListCount(2);
     $this->assertSwitchUserListContainsUser($this->develUser->getUsername());
     $this->assertSwitchUserListContainsUser($anonymous);
 }
    /**
     * Tests Drupal 6 profile values to Drupal 8 migration.
     */
    public function testUserProfileValues()
    {
        $user = User::load(2);
        $this->assertFalse(is_null($user));
        $this->assertIdentical('red', $user->profile_color->value);
        $expected = <<<EOT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam nulla sapien, congue nec risus ut, adipiscing aliquet felis. Maecenas quis justo vel nulla varius euismod. Quisque metus metus, cursus sit amet sem non, bibendum vehicula elit. Cras dui nisl, eleifend at iaculis vitae, lacinia ut felis. Nullam aliquam ligula volutpat nulla consectetur accumsan. Maecenas tincidunt molestie diam, a accumsan enim fringilla sit amet. Morbi a tincidunt tellus. Donec imperdiet scelerisque porta. Sed quis sem bibendum eros congue sodales. Vivamus vel fermentum est, at rutrum orci. Nunc consectetur purus ut dolor pulvinar, ut volutpat felis congue. Cras tincidunt odio sed neque sollicitudin, vehicula tempor metus scelerisque.
EOT;
        $this->assertIdentical($expected, $user->profile_biography->value);
        $this->assertIdentical('1', $user->profile_sell_address->value);
        $this->assertIdentical('Back\\slash', $user->profile_sold_to->value);
        $this->assertIdentical('AC/DC', $user->profile_bands[0]->value);
        $this->assertIdentical('Eagles', $user->profile_bands[1]->value);
        $this->assertIdentical('Elton John', $user->profile_bands[2]->value);
        $this->assertIdentical('Lemonheads', $user->profile_bands[3]->value);
        $this->assertIdentical('Rolling Stones', $user->profile_bands[4]->value);
        $this->assertIdentical('Queen', $user->profile_bands[5]->value);
        $this->assertIdentical('The White Stripes', $user->profile_bands[6]->value);
        $this->assertIdentical('1974-06-02', $user->profile_birthdate->value);
        $this->assertIdentical('http://example.com/blog', $user->profile_blog->uri);
        $this->assertNull($user->profile_blog->title);
        $this->assertIdentical([], $user->profile_blog->options);
        $this->assertIdentical('http://example.com/blog', $user->profile_blog->uri);
        $this->assertNull($user->profile_love_migrations->value);
        $user = User::load(8);
        $this->assertIdentical('Forward/slash', $user->profile_sold_to->value);
        $user = User::load(15);
        $this->assertIdentical('Dot.in.the.middle', $user->profile_sold_to->value);
    }
Esempio n. 22
0
 /**
  * Tests contact link.
  */
 public function testContactLink()
 {
     $accounts = array();
     $accounts['root'] = User::load(1);
     // Create an account with access to all contact pages.
     $admin_account = $this->drupalCreateUser(array('administer users'));
     $accounts['admin'] = $admin_account;
     // Create an account with no access to contact pages.
     $no_contact_account = $this->drupalCreateUser();
     $accounts['no_contact'] = $no_contact_account;
     // Create an account with access to contact pages.
     $contact_account = $this->drupalCreateUser(array('access user contact forms'));
     $accounts['contact'] = $contact_account;
     $this->drupalLogin($admin_account);
     $this->drupalGet('test-contact-link');
     // The admin user has access to all contact links beside his own.
     $this->assertContactLinks($accounts, array('root', 'no_contact', 'contact'));
     $this->drupalLogin($no_contact_account);
     $this->drupalGet('test-contact-link');
     // Ensure that the user without the permission doesn't see any link.
     $this->assertContactLinks($accounts, array());
     $this->drupalLogin($contact_account);
     $this->drupalGet('test-contact-link');
     $this->assertContactLinks($accounts, array('root', 'admin', 'no_contact'));
     // Disable contact link for no_contact.
     $this->userData->set('contact', $no_contact_account->id(), 'enabled', FALSE);
     // @todo Remove cache invalidation in https://www.drupal.org/node/2477903.
     Cache::invalidateTags($no_contact_account->getCacheTagsToInvalidate());
     $this->drupalGet('test-contact-link');
     $this->assertContactLinks($accounts, array('root', 'admin'));
 }
Esempio n. 23
0
 /**
  * Create a user with a given set of permissions.
  *
  * @param array $permissions
  *   Array of permission names to assign to user. Note that the user always
  *   has the default permissions derived from the "authenticated users" role.
  * @param string $name
  *   The user name.
  * @param bool $admin
  *   (optional) Whether the user should be an administrator
  *   with all the available permissions.
  *
  * @return \Drupal\user\Entity\User|false
  *   A fully loaded user object with pass_raw property, or FALSE if account
  *   creation fails.
  */
 protected function createUser(array $permissions = array(), $name = NULL, $admin = FALSE)
 {
     // Create a role with the given permission set, if any.
     $rid = FALSE;
     if ($permissions) {
         $rid = $this->createRole($permissions);
         if (!$rid) {
             return FALSE;
         }
     }
     // Create a user assigned to that role.
     $edit = array();
     $edit['name'] = !empty($name) ? $name : $this->randomMachineName();
     $edit['mail'] = $edit['name'] . '@example.com';
     $edit['pass'] = user_password();
     $edit['status'] = 1;
     if ($rid) {
         $edit['roles'] = array($rid);
     }
     if ($admin) {
         $edit['roles'][] = $this->createAdminRole();
     }
     $account = User::create($edit);
     $account->save();
     $this->assertTrue($account->id(), SafeMarkup::format('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), 'User login');
     if (!$account->id()) {
         return FALSE;
     }
     // Add the raw password so that we can log in as this user.
     $account->pass_raw = $edit['pass'];
     return $account;
 }
Esempio n. 24
0
 /**
  * Tests the normalization of comments.
  */
 public function testComment()
 {
     $node_type = NodeType::create(['type' => 'example_type']);
     $node_type->save();
     $account = User::create(['name' => $this->randomMachineName()]);
     $account->save();
     // Add comment type.
     $this->container->get('entity.manager')->getStorage('comment_type')->create(array('id' => 'comment', 'label' => 'comment', 'target_entity_type_id' => 'node'))->save();
     $this->addDefaultCommentField('node', 'example_type');
     $node = Node::create(['title' => $this->randomMachineName(), 'uid' => $account->id(), 'type' => $node_type->id(), 'status' => NODE_PUBLISHED, 'promote' => 1, 'sticky' => 0, 'body' => [['value' => $this->randomMachineName(), 'format' => $this->randomMachineName()]]]);
     $node->save();
     $parent_comment = Comment::create(array('uid' => $account->id(), 'subject' => $this->randomMachineName(), 'comment_body' => ['value' => $this->randomMachineName(), 'format' => NULL], 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment'));
     $parent_comment->save();
     $comment = Comment::create(array('uid' => $account->id(), 'subject' => $this->randomMachineName(), 'comment_body' => ['value' => $this->randomMachineName(), 'format' => NULL], 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'pid' => $parent_comment->id(), 'mail' => '*****@*****.**', 'homepage' => 'http://buytaert.net'));
     $comment->save();
     $original_values = $comment->toArray();
     // Hostname will always be denied view access.
     // No value will exist for name as this is only for anonymous users.
     unset($original_values['hostname'], $original_values['name']);
     $normalized = $this->serializer->normalize($comment, $this->format, ['account' => $account]);
     // Assert that the hostname field does not appear at all in the normalized
     // data.
     $this->assertFalse(array_key_exists('hostname', $normalized), 'Hostname was not found in normalized comment data.');
     /** @var \Drupal\comment\CommentInterface $denormalized_comment */
     $denormalized_comment = $this->serializer->denormalize($normalized, 'Drupal\\comment\\Entity\\Comment', $this->format, ['account' => $account]);
     // Before comparing, unset values that are expected to differ.
     $denormalized_comment_values = $denormalized_comment->toArray();
     unset($denormalized_comment_values['hostname'], $denormalized_comment_values['name']);
     $this->assertEqual($original_values, $denormalized_comment_values, 'The expected comment values are restored after normalizing and denormalizing.');
 }
 /**
  * {@inheritdoc}
  */
 protected function createEntity()
 {
     // Create a "Llama" user.
     $user = User::create(['name' => 'Llama', 'status' => TRUE]);
     $user->save();
     return $user;
 }
Esempio n. 26
0
 public function testUserHooks()
 {
     FieldStorageConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user'))->save();
     FieldConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user', 'bundle' => 'user'))->save();
     $this->assertIdentical('', \Drupal::config('name.settings')->get('user_preferred'));
     FieldStorageConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user'))->save();
     FieldStorageConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user'))->save();
     $field = FieldConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
     $field->save();
     $field2 = FieldConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
     $field2->save();
     $this->assertEqual($field->getName(), \Drupal::config('name.settings')->get('user_preferred'));
     \Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field2->getName())->save();
     $field2->delete();
     $this->assertEqual('', \Drupal::config('name.settings')->get('user_preferred'));
     \Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field->getName())->save();
     $account = User::create(array('name' => 'test'));
     $account->field_name_test[0] = array('given' => 'Max', 'family' => 'Mustermann');
     $account->save();
     $account = User::load($account->id());
     $this->assertEqual('Max Mustermann', $account->realname);
     $this->assertEqual('Max Mustermann', user_format_name($account));
     $this->assertEqual('test', $account->getUsername());
     $this->assertEqual('Max Mustermann', $account->getDisplayName());
 }
 /**
  * A route returning a CacheableResponse object.
  *
  * @return \Drupal\Core\Cache\CacheableResponseInterface
  *   A CacheableResponseInterface object.
  */
 public function cacheableResponse()
 {
     $user = User::load(1);
     $response = new CacheableResponse($user->label());
     $response->addCacheableDependency($user);
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('uid');
     $account = User::load($uid);
     if (!$account) {
         // Error loading User entity.
         $io->error(sprintf($this->trans('commands.user.login.clear.attempts.errors.invalid-user'), $uid));
         return 1;
     }
     // Define event name and identifier.
     $event = 'user.failed_login_user';
     // Identifier is created by uid and IP address,
     // Then we defined a generic identifier.
     $identifier = "{$account->id()}-";
     // Retrieve current database connection.
     $database = $this->getDrupalService('database');
     $schema = $database->schema();
     $flood = $schema->findTables('flood');
     if (!$flood) {
         $io->error($this->trans('commands.user.login.clear.attempts.errors.no-flood'));
         return 1;
     }
     // Clear login attempts.
     $database->delete('flood')->condition('event', $event)->condition('identifier', $database->escapeLike($identifier) . '%', 'LIKE')->execute();
     // Command executed successful.
     $io->success(sprintf($this->trans('commands.user.login.clear.attempts.messages.successful'), $uid));
 }
 /**
  * Test registered Serializer's entity serialization for core's formats.
  */
 public function testSerialize()
 {
     // Test that Serializer responds using the ComplexDataNormalizer and
     // JsonEncoder. The output of ComplexDataNormalizer::normalize() is tested
     // elsewhere, so we can just assume that it works properly here.
     $normalized = $this->serializer->normalize($this->entity, 'json');
     $expected = json_encode($normalized);
     // Test 'json'.
     $actual = $this->serializer->serialize($this->entity, 'json');
     $this->assertIdentical($actual, $expected, 'Entity serializes to JSON when "json" is requested.');
     $actual = $this->serializer->serialize($normalized, 'json');
     $this->assertIdentical($actual, $expected, 'A normalized array serializes to JSON when "json" is requested');
     // Test 'ajax'.
     $actual = $this->serializer->serialize($this->entity, 'ajax');
     $this->assertIdentical($actual, $expected, 'Entity serializes to JSON when "ajax" is requested.');
     $actual = $this->serializer->serialize($normalized, 'ajax');
     $this->assertIdentical($actual, $expected, 'A normalized array serializes to JSON when "ajax" is requested');
     // Generate the expected xml in a way that allows changes to entity property
     // order.
     $expected = array('id' => '<id><value>' . $this->entity->id() . '</value></id>', 'uuid' => '<uuid><value>' . $this->entity->uuid() . '</value></uuid>', 'langcode' => '<langcode><value>en</value></langcode>', 'name' => '<name><value>' . $this->values['name'] . '</value></name>', 'type' => '<type><value>entity_test_mulrev</value></type>', 'created' => '<created><value>' . $this->entity->created->value . '</value></created>', 'user_id' => '<user_id><target_id>' . $this->user->id() . '</target_id><url>' . $this->user->url() . '</url></user_id>', 'revision_id' => '<revision_id><value>' . $this->entity->getRevisionId() . '</value></revision_id>', 'default_langcode' => '<default_langcode><value>1</value></default_langcode>', 'field_test_text' => '<field_test_text><value>' . $this->values['field_test_text']['value'] . '</value><format>' . $this->values['field_test_text']['format'] . '</format></field_test_text>');
     // Sort it in the same order as normalised.
     $expected = array_merge($normalized, $expected);
     // Add header and footer.
     array_unshift($expected, '<?xml version="1.0"?>' . PHP_EOL . '<response>');
     $expected[] = '</response>' . PHP_EOL;
     // Reduced the array to a string.
     $expected = implode('', $expected);
     // Test 'xml'. The output should match that of Symfony's XmlEncoder.
     $actual = $this->serializer->serialize($this->entity, 'xml');
     $this->assertIdentical($actual, $expected);
     $actual = $this->serializer->serialize($normalized, 'xml');
     $this->assertIdentical($actual, $expected);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('user');
     $user = User::load($uid);
     if (!$user) {
         $io->error(sprintf($this->trans('commands.user.password.reset.errors.invalid-user'), $uid));
         return;
     }
     $password = $input->getArgument('password');
     if (!$password) {
         $io->error(sprintf($this->trans('commands.user.password.reset.errors.empty-password'), $uid));
         return;
     }
     try {
         $user->setPassword($password);
         $user->save();
         // Clear all failed login attempts after setup new password to user account.
         $this->getChain()->addCommand('user:login:clear:attempts', ['uid' => $uid]);
     } catch (\Exception $e) {
         $io->error($e->getMessage());
         return;
     }
     $io->success(sprintf($this->trans('commands.user.password.reset.messages.reset-successful'), $uid));
 }