Exemple #1
0
/**
 * Set the necessary cookies for the user to be logged into the forum.
 *
 * Frontend cookie names:
 * - lastvisit, lastactivity, sessionhash
 * Backend cookie names:
 * - cpsession, userid, password
 *
 * However, in all cases the cookiedomain is NOT prefixed with a dot unless
 * cookie domain has not been manually altered to either a suggested value or
 * custom value in vB's settings.
 */
function drupalvb_set_login_cookies($userid)
{
    // Load required vB user data.
    $vbuser = db_fetch_array(drupalvb_db_query("SELECT userid, password, salt FROM {user} WHERE userid = %d", $userid));
    if (!$vbuser) {
        return FALSE;
    }
    $vb_config = drupalvb_get('config');
    $vb_options = drupalvb_get('options');
    $cookie_prefix = isset($vb_config['Misc']['cookieprefix']) ? $vb_config['Misc']['cookieprefix'] : 'bb';
    $cookie_path = $vb_options['cookiepath'];
    $cookie_domain = !empty($vb_options['cookiedomain']) ? $vb_options['cookiedomain'] : $GLOBALS['cookie_domain'];
    $now = time();
    $expire = $now + (@ini_get('session.cookie_lifetime') ? ini_get('session.cookie_lifetime') : 60 * 60 * 24 * 365);
    // Clear out old session (if available).
    if (!empty($_COOKIE[$cookie_prefix . 'sessionhash'])) {
        drupalvb_db_query("DELETE FROM {session} WHERE sessionhash = '%s'", $_COOKIE[$cookie_prefix . 'sessionhash']);
    }
    // Setup user session.
    $ip = implode('.', array_slice(explode('.', drupalvb_get_ip()), 0, 4 - $vb_options['ipcheck']));
    $idhash = md5($_SERVER['HTTP_USER_AGENT'] . $ip);
    $sessionhash = md5($now . request_uri() . $idhash . $_SERVER['REMOTE_ADDR'] . user_password(6));
    drupalvb_db_query("REPLACE INTO {session} (sessionhash, userid, host, idhash, lastactivity, location, useragent, loggedin) VALUES ('%s', %d, '%s', '%s', %d, '%s', '%s', %d)", $sessionhash, $vbuser['userid'], substr($_SERVER['REMOTE_ADDR'], 0, 15), $idhash, $now, '/forum/', $_SERVER['HTTP_USER_AGENT'], 2);
    // Setup cookies.
    setcookie($cookie_prefix . 'sessionhash', $sessionhash, $expire, $cookie_path, $cookie_domain);
    setcookie($cookie_prefix . 'lastvisit', $now, $expire, $cookie_path, $cookie_domain);
    setcookie($cookie_prefix . 'lastactivity', $now, $expire, $cookie_path, $cookie_domain);
    setcookie($cookie_prefix . 'userid', $vbuser['userid'], $expire, $cookie_path, $cookie_domain);
    setcookie($cookie_prefix . 'password', md5($vbuser['password'] . variable_get('drupalvb_license', '')), $expire, $cookie_path, $cookie_domain);
    return TRUE;
}
Exemple #2
0
 public function editCustomer($customer_id, $data)
 {
     if (!isset($data['custom_field'])) {
         $data['custom_field'] = array();
     }
     //$this->db->query("UPDATE " . DB_PREFIX . "customer SET customer_group_id = '" . (int)$data['customer_group_id'] . "', fullname = '" . $this->db->escape($data['fullname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "', custom_field = '" . $this->db->escape(isset($data['custom_field']) ? serialize($data['custom_field']) : '') . "', newsletter = '" . (int)$data['newsletter'] . "', status = '" . (int)$data['status'] . "', approved = '" . (int)$data['approved'] . "', safe = '" . (int)$data['safe'] . "' WHERE customer_id = '" . (int)$customer_id . "'");
     $customer = array('customer_group_id' => (int) $data['customer_group_id'], 'username' => $data['username'], 'fullname' => $data['fullname'], 'email' => $data['email'], 'telephone' => $data['telephone'], 'fax' => $data['fax'], 'custom_field' => isset($data['custom_field']) ? serialize($data['custom_field']) : '', 'newsletter' => (int) $data['newsletter'], 'status' => (int) $data['status'], 'approved' => (int) $data['approved'], 'safe' => (int) $data['safe']);
     $this->db_ci->where('customer_id', $customer_id);
     $this->db_ci->update('customer', $customer);
     if ($data['password']) {
         //$this->db->query("UPDATE " . DB_PREFIX . "customer SET salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '******'password'])))) . "' WHERE customer_id = '" . (int)$customer_id . "'");
         $query = $this->db_ci->from('customer')->where('customer_id', $customer_id)->get();
         $data2 = $query->result_one_array();
         $data2['salt'] = substr(md5(uniqid(rand(), true)), 0, 9);
         $data2['password'] = $data['password'];
         $customer2 = array();
         $customer2['salt'] = $data2['salt'];
         $customer2['password'] = user_password($data2);
         $this->db_ci->where('customer_id', (int) $customer_id);
         $this->db_ci->update('customer', $customer2);
     }
     $this->db->query("DELETE FROM " . DB_PREFIX . "address WHERE customer_id = '" . (int) $customer_id . "'");
     if (isset($data['address'])) {
         foreach ($data['address'] as $address) {
             if (!isset($address['custom_field'])) {
                 $address['custom_field'] = array();
             }
             $this->db->query("INSERT INTO " . DB_PREFIX . "address SET address_id = '" . (int) $address['address_id'] . "', customer_id = '" . (int) $customer_id . "', fullname = '" . $this->db->escape($address['fullname']) . "', company = '" . $this->db->escape($address['company']) . "', address = '" . $this->db->escape($address['address']) . "', city = '" . $this->db->escape($address['city']) . "', postcode = '" . $this->db->escape($address['postcode']) . "', country_id = '" . (int) $address['country_id'] . "', zone_id = '" . (int) $address['zone_id'] . "', custom_field = '" . $this->db->escape(isset($address['custom_field']) ? serialize($address['custom_field']) : '') . "'");
             if (isset($address['default'])) {
                 $address_id = $this->db->getLastId();
                 $this->db->query("UPDATE " . DB_PREFIX . "customer SET address_id = '" . (int) $address_id . "' WHERE customer_id = '" . (int) $customer_id . "'");
             }
         }
     }
 }
 /**
  * Create a new user.
  *
  * @param array $data
  *   Array with the user's data from GitHub
  * @param array $options
  *   Options array as passed to drupal_http_request().
  * @param string $access_token
  *   The GitHub access token.
  *
  * @return \stdClass
  *   The newly saved user object.
  */
 protected function createUser($data, $options, $access_token)
 {
     $fields = array('name' => $data['login'], 'mail' => $this->getEmailFromGithub($options), 'pass' => user_password(8), 'status' => TRUE, 'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'), '_github' => array('access_token' => $access_token, 'data' => $data));
     // The first parameter is left blank so a new user is created.
     $account = user_save('', $fields);
     return $account;
 }
 /**
  * Test soft blocking.
  */
 public function testSoftBlocking()
 {
     // Allow 3 attempts to login before being soft-blocking is enforced.
     $config = \Drupal::configFactory()->getEditable('login_security.settings');
     $config->set('user_wrong_count', 0)->save();
     $config->set('host_wrong_count', 2)->save();
     // Remove notices.
     $config->set('notice_attempts_available', 0)->save();
     $normal_user = $this->drupalCreateUser();
     $good_pass = $normal_user->getPassword();
     // Intentionally break the password to repeat invalid logins.
     $new_pass = user_password();
     $normal_user->setPassword($new_pass);
     $site_name = \Drupal::config('system.site')->get('name');
     // First try.
     $this->assertNoSoftBlocked($normal_user);
     // Second try.
     $this->assertNoSoftBlocked($normal_user);
     // Remove error messages display.
     $config->set('disable_core_login_error', 1)->save();
     // Third try, still valid without soft blocking.
     $this->assertNoSoftBlocked($normal_user);
     // Restore error messages.
     $config->set('disable_core_login_error', 0)->save();
     // 4th attempt, the host is not allowed this time.
     $this->assertSoftBlocked($normal_user);
     // Try a normal login because it should be locked out now.
     $normal_user->setPassword($good_pass);
     $this->assertSoftBlocked($normal_user);
 }
Exemple #5
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;
 }
Exemple #6
0
 public function login($username, $password)
 {
     //$user_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "user WHERE username = '******' AND (password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1('" . $this->db->escape($password) . "'))))) OR password = '******') AND status = '1'");
     $query = $this->db_ci->from('user')->where('username', $username)->get();
     $user = $query->result_one_array();
     //$db_password = $user['password'];
     $user['password'] = $password;
     $input_password = user_password($user);
     $where = array('username' => $username, 'password' => $input_password, 'status' => 1);
     $query = $this->db_ci->from('user')->where($where)->get();
     $user = $query->result_one_array();
     if ($user) {
         $this->session->data['user_id'] = $user['user_id'];
         $this->user_id = $user['user_id'];
         $this->username = $user['username'];
         $this->user_group_id = $user['user_group_id'];
         //$user_group_query = $this->db->query("SELECT permission FROM " . DB_PREFIX . "user_group WHERE user_group_id = '" . (int)$user['user_group_id'] . "'");
         $query = $this->db_ci->from('user_group')->where('user_group_id', $user['user_group_id'])->get();
         $user_group = $query->result_one_array();
         $permissions = unserialize($user_group['permission']);
         if (is_array($permissions)) {
             foreach ($permissions as $key => $value) {
                 $this->permission[$key] = $value;
             }
         }
         return true;
     } else {
         return false;
     }
 }
Exemple #7
0
 public function login($login_name, $password, $override = false)
 {
     $type = getLoginType($login_name);
     //email or telephone or username
     if (!$type) {
         return false;
     }
     if ($override) {
         $customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE `" . $type . "` = '" . $this->db->escape($login_name) . "' AND status = '1'");
     } else {
         //$customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE `" . $type . "` = '" . $this->db->escape($login_name) . "' AND (password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1('" . $this->db->escape($password) . "'))))) OR password = '******') AND status = '1' AND approved = '1'");
         $customer_query = $customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE `" . $type . "` = '" . $this->db->escape($login_name) . "' AND `" . $type . "` <>'' AND status = '1'");
         if ($customer_query->num_rows > 0) {
             $data = array();
             $data['username'] = $customer_query->row['username'];
             $data['salt'] = $customer_query->row['salt'];
             $data['date_added'] = $customer_query->row['date_added'];
             $data['password'] = $password;
             $password_md5 = user_password($data);
             $customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE `" . $type . "` = '" . $this->db->escape(utf8_strtolower($login_name)) . "' AND password = '******' AND status = '1' AND approved = '1'");
         }
     }
     if ($customer_query->num_rows) {
         $this->session->data['customer_id'] = $customer_query->row['customer_id'];
         if ($customer_query->row['cart'] && is_string($customer_query->row['cart'])) {
             $cart = unserialize($customer_query->row['cart']);
             foreach ($cart as $key => $value) {
                 if (!array_key_exists($key, $this->session->data['cart'])) {
                     $this->session->data['cart'][$key] = $value;
                 } else {
                     $this->session->data['cart'][$key] += $value;
                 }
             }
         }
         if ($customer_query->row['wishlist'] && is_string($customer_query->row['wishlist'])) {
             if (!isset($this->session->data['wishlist'])) {
                 $this->session->data['wishlist'] = array();
             }
             $wishlist = unserialize($customer_query->row['wishlist']);
             foreach ($wishlist as $product_id) {
                 if (!in_array($product_id, $this->session->data['wishlist'])) {
                     $this->session->data['wishlist'][] = $product_id;
                 }
             }
         }
         $this->customer_id = $customer_query->row['customer_id'];
         $this->username = $customer_query->row['username'];
         $this->fullname = $customer_query->row['fullname'];
         $this->email = $customer_query->row['email'];
         $this->telephone = $customer_query->row['telephone'];
         $this->fax = $customer_query->row['fax'];
         $this->newsletter = $customer_query->row['newsletter'];
         $this->customer_group_id = $customer_query->row['customer_group_id'];
         $this->address_id = $customer_query->row['address_id'];
         $this->db->query("UPDATE " . DB_PREFIX . "customer SET ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "' WHERE customer_id = '" . (int) $this->customer_id . "'");
         return true;
     } else {
         return false;
     }
 }
 /**
  * Tests password reset functionality.
  */
 function testUserPasswordReset()
 {
     // Try to reset the password for an invalid account.
     $this->drupalGet('user/password');
     $edit = array('name' => $this->randomMachineName(32));
     $this->drupalPostForm(NULL, $edit, t('Email new password'));
     $this->assertText(t('Sorry, @name is not recognized as a username or an email address.', array('@name' => $edit['name'])), 'Validation error message shown when trying to request password for invalid account.');
     $this->assertEqual(count($this->drupalGetMails(array('id' => 'user_password_reset'))), 0, 'No email was sent when requesting a password for an invalid account.');
     // Reset the password by username via the password reset page.
     $edit['name'] = $this->account->getUsername();
     $this->drupalPostForm(NULL, $edit, t('Email new password'));
     // Verify that the user was sent an email.
     $this->assertMail('to', $this->account->getEmail(), 'Password email sent to user.');
     $subject = t('Replacement login information for @username at @site', array('@username' => $this->account->getUsername(), '@site' => \Drupal::config('system.site')->get('name')));
     $this->assertMail('subject', $subject, 'Password reset email subject is correct.');
     $resetURL = $this->getResetURL();
     $this->drupalGet($resetURL);
     // Check the one-time login page.
     $this->assertText($this->account->getUsername(), 'One-time login page contains the correct username.');
     $this->assertText(t('This login can be used only once.'), 'Found warning about one-time login.');
     // Check successful login.
     $this->drupalPostForm(NULL, NULL, t('Log in'));
     $this->assertLink(t('Log out'));
     $this->assertTitle(t('@name | @site', array('@name' => $this->account->getUsername(), '@site' => \Drupal::config('system.site')->get('name'))), 'Logged in using password reset link.');
     // Change the forgotten password.
     $password = user_password();
     $edit = array('pass[pass1]' => $password, 'pass[pass2]' => $password);
     $this->drupalPostForm(NULL, $edit, t('Save'));
     $this->assertText(t('The changes have been saved.'), 'Forgotten password changed.');
     // Verify that the password reset session has been destroyed.
     $this->drupalPostForm(NULL, $edit, t('Save'));
     $this->assertText(t('Your current password is missing or incorrect; it\'s required to change the Password.'), 'Password needed to make profile changes.');
     // Log out, and try to log in again using the same one-time link.
     $this->drupalLogout();
     $this->drupalGet($resetURL);
     $this->assertText(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.'), 'One-time link is no longer valid.');
     // Request a new password again, this time using the email address.
     $this->drupalGet('user/password');
     // Count email messages before to compare with after.
     $before = count($this->drupalGetMails(array('id' => 'user_password_reset')));
     $edit = array('name' => $this->account->getEmail());
     $this->drupalPostForm(NULL, $edit, t('Email new password'));
     $this->assertTrue(count($this->drupalGetMails(array('id' => 'user_password_reset'))) === $before + 1, 'Email sent when requesting password reset using email address.');
     // Create a password reset link as if the request time was 60 seconds older than the allowed limit.
     $timeout = \Drupal::config('user.settings')->get('password_reset_timeout');
     $bogus_timestamp = REQUEST_TIME - $timeout - 60;
     $_uid = $this->account->id();
     $this->drupalGet("user/reset/{$_uid}/{$bogus_timestamp}/" . user_pass_rehash($this->account->getPassword(), $bogus_timestamp, $this->account->getLastLoginTime()));
     $this->assertText(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'Expired password reset request rejected.');
     // Create a user, block the account, and verify that a login link is denied.
     $timestamp = REQUEST_TIME - 1;
     $blocked_account = $this->drupalCreateUser()->block();
     $blocked_account->save();
     $this->drupalGet("user/reset/" . $blocked_account->id() . "/{$timestamp}/" . user_pass_rehash($blocked_account->getPassword(), $timestamp, $blocked_account->getLastLoginTime()));
     $this->assertResponse(403);
 }
Exemple #9
0
 function init()
 {
     # Okay, init user session with it's login & password
     $login = @$_COOKIE['login'];
     $passw = @$_COOKIE['passw'];
     $uid = user_password($login, $passw, true);
     if (!$uid) {
         return $this->error('LOGIN_ERROR', 'Invalid login or password');
     }
     $uinfo = user_info($uid);
     $this->make_sid($uid);
     # Generate SID
     echo '<user>';
     echo '<sid>' . $this->sid . '</sid>';
     echo '<lk>' . $this->lk . '</lk>';
     echo '<uid>' . $uid . '</uid>';
     echo '<name>' . htmlspecialchars($uinfo['name']) . '</name>';
     echo '<seed>' . mt_rand() . '</seed>';
     echo '</user>' . "\n";
     # Version info
     if (@$_COOKIE['v'] && @$_COOKIE['os']) {
         $ver = explode('.', $_COOKIE['v']);
         $ver = sprintf('%02d%02d%02d', @$ver[0], @$ver[1], @$ver[2]);
         $ver = intval($ver);
         $os = preg_replace('/[^a-z0-9]/', '', strtolower($_COOKIE['os']));
         # Check version
         $lastv = ldb_select('client_version', array('ver', 'veri', 'tms_publish'), '`veri`>' . $ver . ' AND `os_' . $os . '`=\'Y\' AND `published`=\'Y\' ORDER BY `veri` DESC LIMIT 1');
         $lastv = @$lastv[0];
         if ($lastv) {
             echo '<newversion ver="' . $lastv['ver'] . '" tms_publish="' . $lastv['tms_publish'] . '"/>' . "\n";
         }
     }
     include_once CORE_PATH . '/ttl.php';
     echo '<ttl default="' . $GLOBALS['ttl_def'] . '">' . "\n";
     foreach ($GLOBALS['ttl'] as $k => $v) {
         echo '<rec name="' . htmlspecialchars($v) . '" value="' . $k . '"' . ($k == $GLOBALS['ttl'] ? ' default="default"' : '') . '/>' . "\n";
     }
     echo '</ttl>' . "\n";
     # Get file list...
     $u_list = ldb_select('upload', '*', '`uid`=' . $uid . ' ORDER BY `tms_upload` ASC');
     echo '<uploads>' . "\n";
     for ($x = 0; $x < count($u_list); $x++) {
         echo '<upload id="' . $u_list[$x]['id'] . '" code="' . $u_list[$x]['code'] . '" ph="' . $u_list[$x]['ph'] . '" comment="' . htmlspecialchars($u_list[$x]['comment']) . '" tms_upload="' . $u_list[$x]['tms_upload'] . '" tms_last="' . $u_list[$x]['tms_last'] . '" ttl="' . $u_list[$x]['ttl'] . '" tms_delete="' . $u_list[$x]['tms_delete'] . '" prolong="' . ($u_list[$x]['prolong'] == 'Y' ? 1 : 0) . '">';
         echo '<files>';
         $f_list = ldb_select('file', '*', '`upid`=' . $u_list[$x]['id'] . ' ORDER BY `tms_add` ASC');
         for ($f = 0; $f < count($f_list); $f++) {
             echo '<file id="' . $f_list[$f]['id'] . '" n="' . $f_list[$f]['upn'] . '" dh="' . $f_list[$f]['dh'] . '" name="' . htmlspecialchars($f_list[$f]['file_name']) . '" size="' . $f_list[$f]['file_size'] . '" tms_add="' . $f_list[$f]['tms_add'] . '"/>';
         }
         echo '</files>';
         echo '</upload>';
     }
     echo '</uploads>' . "\n";
     # Save data
     return;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     $values = $form_state['values'];
     $account = \Drupal::currentUser();
     $consumer_key = user_password(32);
     $consumer_secret = user_password(32);
     $key_hash = sha1($consumer_key);
     db_insert('oauth_consumer')->fields(array('uid' => $account->id(), 'consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'key_hash' => $key_hash))->execute();
     drupal_set_message(t('Added a new consumer.'));
     $form_state['redirect'] = $this->urlGenerator->generate('oauth.user_consumer', array('user' => $account->id()), TRUE);
 }
 /**
  * Submit handler for the customer select form.
  *
  * @param array $form
  *   The parent form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public function submitCustomerForm(array &$form, FormStateInterface $form_state)
 {
     $values = $form_state->getValues();
     if ($values['customer_type'] == 'existing') {
         $values['mail'] = User::load($values['uid'])->getEmail();
     } else {
         $user = User::create(['name' => $values['mail'], 'mail' => $values['mail'], 'pass' => $values['generate'] ? user_password() : $values['pass'], 'status' => TRUE]);
         $user->save();
         $values['uid'] = $user->id();
     }
     $form_state->setValues($values);
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $consumer_key = user_password(32);
     $consumer_secret = user_password(32);
     $key_hash = sha1($consumer_key);
     $uid = $form_state->getValue('uid');
     $consumer = array('consumer_secret' => $consumer_secret, 'key_hash' => $key_hash);
     $this->user_data->set('oauth', $uid, $consumer_key, $consumer);
     drupal_set_message($this->t('Added a new consumer.'));
     Cache::invalidateTags(['oauth:' . $uid]);
     $form_state->setRedirect('oauth.user_consumer', array('user' => $uid));
 }
Exemple #13
0
 public function editPassword($user_id, $password)
 {
     //$this->db->query("UPDATE `" . DB_PREFIX . "user` SET salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '******', code = '' WHERE user_id = '" . (int)$user_id . "'");
     //修改密码的时候,不修改salt
     $query = $this->db_ci->from('user')->where('user_id', $user_id)->get();
     $data = $query->result_one_array();
     $data['password'] = $password;
     $user['password'] = user_password($data);
     $user['code'] = '';
     $this->db_ci->where('user_id', (int) $user_id);
     $this->db_ci->update('user', $user);
 }
Exemple #14
0
 /**
  * Overrides Drupal\Core\Entity\EntityForm::submit().
  */
 public function submit(array $form, FormStateInterface $form_state)
 {
     $admin = $form_state['values']['administer_users'];
     if (!\Drupal::config('user.settings')->get('verify_mail') || $admin) {
         $pass = $form_state['values']['pass'];
     } else {
         $pass = user_password();
     }
     // Remove unneeded values.
     form_state_values_clean($form_state);
     $form_state['values']['pass'] = $pass;
     $form_state['values']['init'] = $form_state['values']['mail'];
     parent::submit($form, $form_state);
 }
 /**
  * @Given I am logged in with new user :username
  */
 public function iAmLoggedInWithNewUser($username)
 {
     //This will generate a random password, you could set your own here
     $password = user_password(8);
     //set up the user fields
     $fields = array('name' => $username . user_password(), 'mail' => $username . '@email.com', '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);
     // Now for the actual login.
     $this->getSession()->visit('/user');
     $this->getSession()->getPage()->fillField('edit-name', $username);
     $this->getSession()->getPage()->fillField('edit-pass', $password);
     $this->getSession()->getPage()->pressButton('edit-submit');
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $admin = $form_state->getValue('administer_users');
     if (!\Drupal::config('user.settings')->get('verify_mail') || $admin) {
         $pass = $form_state->getValue('pass');
     } else {
         $pass = user_password();
     }
     // Remove unneeded values.
     $form_state->cleanValues();
     $form_state->setValue('pass', $pass);
     $form_state->setValue('init', $form_state->getValue('mail'));
     parent::submitForm($form, $form_state);
 }
 /**
  * Helper function that creates a user object with the given role.
  */
 protected function createUser($role)
 {
     $edit = array();
     $edit['name'] = $this->randomName();
     $edit['mail'] = $edit['name'] . '@example.com';
     // @todo role ids are completely broken, if modules are enable in the wrong
     // order.
     $edit['roles'] = array($role->rid => $role->name);
     $edit['pass'] = user_password();
     $edit['status'] = 1;
     $user = user_save(drupal_anonymous_user(), $edit);
     $user->pass_raw = $edit['pass'];
     return $user;
 }
 /**
  * Test creating a user with arbitrary uid.
  */
 function testUserImport()
 {
     // User ID must be a number that is not in the database.
     $max_uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField();
     $test_uid = $max_uid + mt_rand(1000, 1000000);
     $test_name = $this->randomMachineName();
     // Create the base user, based on drupalCreateUser().
     $user = entity_create('user', array('name' => $test_name, 'uid' => $test_uid, 'mail' => $test_name . '@example.com', 'pass' => user_password(), 'status' => 1));
     $user->enforceIsNew();
     $user->save();
     // Test if created user exists.
     $user_by_uid = user_load($test_uid);
     $this->assertTrue($user_by_uid, 'Loading user by uid.');
     $user_by_name = user_load_by_name($test_name);
     $this->assertTrue($user_by_name, 'Loading user by name.');
 }
function create_drupal_user()
{
    $user_successfully_created = "false";
    $server_base = variable_get('apiary_research_base_url', 'http://localhost');
    include_once drupal_get_path('module', 'apiary_project') . '/apiaryPermissionsClass.php';
    $user_name = '';
    if (user_access(apiaryPermissionsClass::$ADMINISTER_APIARY)) {
        if (isset($_POST['name']) && $_POST['name'] != '') {
            if (isset($_POST['mail']) && $_POST['mail'] != '') {
                $name = $_POST['name'];
                $mail = $_POST['mail'];
                if (isset($_POST['pass']) && $_POST['pass'] != '') {
                    $pass = $_POST['pass'];
                    //using drupals user_save function does the md5 hash
                    //$pass = md5($_POST['pass']);
                } else {
                    $pass = user_password();
                    //drupal function to create a md5 hash password
                }
                $require_role_to_use_apiary_workflow = 'administrator';
                //this gets assigned to the created user
                $results = db_query("SELECT rid FROM {role} WHERE NAME='%s'", $require_role_to_use_apiary_workflow);
                $result = db_fetch_object($results);
                $rid = $result->rid;
                $newuser = array('name' => $name, 'mail' => $mail, 'status' => 1, 'pass' => $pass, 'roles' => array($rid => $require_role_to_use_apiary_workflow));
                $new_user = user_save('', $newuser);
                if ($new_user != false) {
                    $user_successfully_created = "true";
                    $user_name = $name;
                    $msg = "User " . $new_user->name . " successfully created.";
                } else {
                    $msg = "User " . $new_user->name . " failed to be created.";
                }
            } else {
                $msg = "No e-mail address was provided.";
            }
        } else {
            $msg = "No username was provided.";
        }
    } else {
        $msg = "You do not have permissions to create new users.";
    }
    $returnJSON['user_name'] = $user_name;
    $returnJSON['user_successfully_created'] = $user_successfully_created;
    $returnJSON['msg'] = $msg;
    echo json_encode($returnJSON);
}
Exemple #20
0
 /**
  * Test creating a user with arbitrary uid.
  */
 function testUserImport()
 {
     // User ID must be a number that is not in the database.
     $uids = \Drupal::entityManager()->getStorage('user')->getQuery()->sort('uid', 'DESC')->range(0, 1)->execute();
     $max_uid = reset($uids);
     $test_uid = $max_uid + mt_rand(1000, 1000000);
     $test_name = $this->randomMachineName();
     // Create the base user, based on drupalCreateUser().
     $user = entity_create('user', array('name' => $test_name, 'uid' => $test_uid, 'mail' => $test_name . '@example.com', 'pass' => user_password(), 'status' => 1));
     $user->enforceIsNew();
     $user->save();
     // Test if created user exists.
     $user_by_uid = User::load($test_uid);
     $this->assertTrue($user_by_uid, 'Loading user by uid.');
     $user_by_name = user_load_by_name($test_name);
     $this->assertTrue($user_by_name, 'Loading user by name.');
 }
function wyc_add_user($user_data)
{
    $joined = ($date = strtotime($user_data['JoinDate'])) && $date != false ? $date : null;
    $expires = ($date = strtotime($user_data['d_membership_expires'])) && $date != false ? date('Y-m-d H:i:s', $date) : null;
    $mail = strpos($user_data['Email'], '@') === false ? $user_data['WYCNumber'] . '@wyc_intranet.com' : $user_data['Email'];
    //set up the user fields
    $fields = array('name' => $user_data['WYCNumber'], 'mail' => $mail, 'pass' => user_password(8), 'status' => 1, 'init' => 'email address', 'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'), 'field_full_name' => array(LANGUAGE_NONE => array(array('value' => $user_data['First'] . ' ' . $user_data['Last']))), 'field_wyc_number' => array(LANGUAGE_NONE => array(array('value' => $user_data['WYCNumber']))), 'field_phone_number' => array(LANGUAGE_NONE => array(array('value' => $user_data['Phone1']), array('value' => $user_data['Phone2']))), 'field_address' => array(LANGUAGE_NONE => array(array('thoroughfare' => $user_data['StreetAddress'], 'locality' => $user_data['City'], 'administrative_area' => $user_data['State'], 'postal_code' => $user_data['ZipCode']))), 'field_membership_expires' => array(LANGUAGE_NONE => array(array('value' => $expires))), 'created' => date('U', $joined));
    $old = user_load_by_mail($mail);
    if (empty($old->uid)) {
        $new = user_save('', $fields);
        wyc_log('wyc_user_created', $user_data);
        if (empty($new->uid)) {
            wyc_log('wyc_user_create_failed', $user_data);
        }
    } else {
        wyc_log('wyc_user_create_skipped', $user_data);
    }
}
 /**
  * Tests that user account for uid 1 cannot be cancelled.
  *
  * This should never be possible, or the site owner would become unable to
  * administer the site.
  */
 function testUserCancelUid1()
 {
     \Drupal::moduleHandler()->install(array('views'));
     // Update uid 1's name and password to we know it.
     $password = user_password();
     $account = array('name' => 'user1', 'pass' => $this->container->get('password')->hash(trim($password)));
     // We cannot use $account->save() here, because this would result in the
     // password being hashed again.
     db_update('users_field_data')->fields($account)->condition('uid', 1)->execute();
     // Reload and log in uid 1.
     $user1 = user_load(1, TRUE);
     $user1->pass_raw = $password;
     // Try to cancel uid 1's account with a different user.
     $this->admin_user = $this->drupalCreateUser(array('administer users'));
     $this->drupalLogin($this->admin_user);
     $edit = array('action' => 'user_cancel_user_action', 'user_bulk_form[0]' => TRUE);
     $this->drupalPostForm('admin/people', $edit, t('Apply'));
     // Verify that uid 1's account was not cancelled.
     $user1 = user_load(1, TRUE);
     $this->assertTrue($user1->isActive(), 'User #1 still exists and is not blocked.');
 }
 /**
  * Tests authorization.
  */
 public function testAuthorize()
 {
     // Create a user with limited permissions. We can't use
     // $this->drupalCreateUser here because we need to to set a specific user
     // name.
     $edit = array('name' => 'Poor user', 'mail' => '*****@*****.**', 'pass' => user_password(), 'status' => 1);
     $account = user_save(drupal_anonymous_user(), $edit);
     // // Adding a mapping to the user_name will invoke authorization.
     $this->addMappings('comment', array(5 => array('source' => 'mail', 'target' => 'user_mail')));
     $url = $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'feeds_comment_processor') . '/tests/test.csv';
     $nid = $this->createFeedNode('comment', $url, 'Comment test');
     $this->assertText('Failed importing 1 comment');
     $this->assertText('User ' . $account->name . ' is not permitted to post comments.');
     $this->assertEqual(0, db_query("SELECT COUNT(*) FROM {comment}")->fetchField());
     user_role_change_permissions(2, array('post comments' => TRUE));
     $this->drupalPost("node/{$nid}/import", array(), 'Import');
     $this->assertText('Created 1 comment.');
     $this->assertEqual(1, db_query("SELECT COUNT(*) FROM {comment}")->fetchField());
     $comment = comment_load(1);
     $this->assertEqual(0, $comment->status);
 }
Exemple #24
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'];
}
 /**
  * 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.
  *
  * @return object|false
  *   A fully loaded user object with pass_raw property, or FALSE if account
  *   creation fails.
  */
 protected function backdropCreateUser(array $permissions = array())
 {
     // Create a role with the given permission set, if any.
     $role_name = FALSE;
     if ($permissions) {
         $role_name = $this->backdropCreateRole($permissions);
         if (!$role_name) {
             return FALSE;
         }
     }
     // Create a user assigned to that role.
     $edit = array();
     $edit['name'] = $this->randomName();
     $edit['mail'] = $edit['name'] . '@example.com';
     $edit['pass'] = user_password();
     $edit['status'] = 1;
     if ($role_name) {
         $edit['roles'] = array($role_name);
     }
     $account = entity_create('user', $edit);
     $account->save();
     $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
     if (empty($account->uid)) {
         return FALSE;
     }
     // Add the raw password so that we can log in as this user.
     $account->pass_raw = $edit['pass'];
     return $account;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     switch ($form_state->getValue('customer_type')) {
         case 'search':
             $uid = $form_state->getValue(['customer', 'uid']);
             break;
         case 'create':
             // Create new account.
             $email = trim($form_state->getValue(['customer', 'email']));
             $fields = array('name' => uc_store_email_to_username($email), 'mail' => $email, 'pass' => user_password(), 'status' => $this->config('uc_cart.settings')->get('new_customer_status_active') ? 1 : 0);
             $account = \Drupal\user\Entity\User::create($fields);
             $account->save();
             $uid = $account->id();
             if ($form_state->getValue(['customer', 'sendmail'])) {
                 // Manually set the password so it appears in the e-mail.
                 $account->password = $fields['pass'];
                 \Drupal::service('plugin.manager.mail')->mail('user', 'register_admin_created', $email, uc_store_mail_recipient_langcode($email), array('account' => $account), uc_store_email_from());
                 drupal_set_message(t('A welcome message has been e-mailed to the new user.'));
             }
             break;
         default:
             $uid = 0;
     }
     $order = \Drupal\uc_order\Entity\Order::create(array('uid' => $uid, 'order_status' => uc_order_state_default('post_checkout')));
     $order->save();
     uc_order_comment_save($order->id(), \Drupal::currentUser()->id(), t('Order created by the administration.'), 'admin');
     $form_state->setRedirect('entity.uc_order.edit_form', ['uc_order' => $order->id()]);
 }
Exemple #27
0
 /**
  * Generates and then verifies some user events.
  */
 private function doUser()
 {
     // Set user variables.
     $name = $this->randomMachineName();
     $pass = user_password();
     // Add a user using the form to generate an add user event (which is not
     // triggered by drupalCreateUser).
     $edit = array();
     $edit['name'] = $name;
     $edit['mail'] = $name . '@example.com';
     $edit['pass[pass1]'] = $pass;
     $edit['pass[pass2]'] = $pass;
     $edit['status'] = 1;
     $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
     $this->assertResponse(200);
     // Retrieve the user object.
     $user = user_load_by_name($name);
     $this->assertTrue($user != NULL, format_string('User @name was loaded', array('@name' => $name)));
     // pass_raw property is needed by drupalLogin.
     $user->pass_raw = $pass;
     // Log in user.
     $this->drupalLogin($user);
     // Log out user.
     $this->drupalLogout();
     // Fetch the row IDs in watchdog that relate to the user.
     $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', array(':uid' => $user->id()));
     foreach ($result as $row) {
         $ids[] = $row->wid;
     }
     $count_before = isset($ids) ? count($ids) : 0;
     $this->assertTrue($count_before > 0, format_string('DBLog contains @count records for @name', array('@count' => $count_before, '@name' => $user->getUsername())));
     // Log in the admin user.
     $this->drupalLogin($this->adminUser);
     // Delete the user created at the start of this test.
     // We need to POST here to invoke batch_process() in the internal browser.
     $this->drupalPostForm('user/' . $user->id() . '/cancel', array('user_cancel_method' => 'user_cancel_reassign'), t('Cancel account'));
     // View the database log report.
     $this->drupalGet('admin/reports/dblog');
     $this->assertResponse(200);
     // Verify that the expected events were recorded.
     // Add user.
     // Default display includes name and email address; if too long, the email
     // address is replaced by three periods.
     $this->assertLogMessage(t('New user: %name %email.', array('%name' => $name, '%email' => '<' . $user->getEmail() . '>')), 'DBLog event was recorded: [add user]');
     // Log in user.
     $this->assertLogMessage(t('Session opened for %name.', array('%name' => $name)), 'DBLog event was recorded: [login user]');
     // Log out user.
     $this->assertLogMessage(t('Session closed for %name.', array('%name' => $name)), 'DBLog event was recorded: [logout user]');
     // Delete user.
     $message = t('Deleted user: %name %email.', array('%name' => $name, '%email' => '<' . $user->getEmail() . '>'));
     $message_text = Unicode::truncate(Html::decodeEntities(strip_tags($message)), 56, TRUE, TRUE);
     // Verify that the full message displays on the details page.
     $link = FALSE;
     if ($links = $this->xpath('//a[text()="' . $message_text . '"]')) {
         // Found link with the message text.
         $links = array_shift($links);
         foreach ($links->attributes() as $attr => $value) {
             if ($attr == 'href') {
                 // Extract link to details page.
                 $link = Unicode::substr($value, strpos($value, 'admin/reports/dblog/event/'));
                 $this->drupalGet($link);
                 // Check for full message text on the details page.
                 $this->assertRaw($message, 'DBLog event details was found: [delete user]');
                 break;
             }
         }
     }
     $this->assertTrue($link, 'DBLog event was recorded: [delete user]');
     // Visit random URL (to generate page not found event).
     $not_found_url = $this->randomMachineName(60);
     $this->drupalGet($not_found_url);
     $this->assertResponse(404);
     // View the database log page-not-found report page.
     $this->drupalGet('admin/reports/page-not-found');
     $this->assertResponse(200);
     // Check that full-length URL displayed.
     $this->assertText($not_found_url, 'DBLog event was recorded: [page not found]');
 }
 /**
  * Test the user-specific overrides of the entity handler.
  */
 public function testUserHandler()
 {
     $selection_options = array('target_type' => 'user', 'handler' => 'default', 'handler_settings' => array('target_bundles' => array(), 'include_anonymous' => TRUE));
     // Build a set of test data.
     $user_values = array('anonymous' => User::load(0), 'admin' => User::load(1), 'non_admin' => array('name' => 'non_admin <&>', 'mail' => '*****@*****.**', 'roles' => array(), 'pass' => user_password(), 'status' => 1), 'blocked' => array('name' => 'blocked <&>', 'mail' => '*****@*****.**', 'roles' => array(), 'pass' => user_password(), 'status' => 0));
     $user_values['anonymous']->name = $this->config('user.settings')->get('anonymous');
     $users = array();
     $user_labels = array();
     foreach ($user_values as $key => $values) {
         if (is_array($values)) {
             $account = entity_create('user', $values);
             $account->save();
         } else {
             $account = $values;
         }
         $users[$key] = $account;
         $user_labels[$key] = Html::escape($account->getUsername());
     }
     // Test as a non-admin.
     \Drupal::currentUser()->setAccount($users['non_admin']);
     $referenceable_tests = array(array('arguments' => array(array(NULL, 'CONTAINS')), 'result' => array('user' => array($users['admin']->id() => $user_labels['admin'], $users['non_admin']->id() => $user_labels['non_admin']))), array('arguments' => array(array('non_admin', 'CONTAINS'), array('NON_ADMIN', 'CONTAINS')), 'result' => array('user' => array($users['non_admin']->id() => $user_labels['non_admin']))), array('arguments' => array(array('invalid user', 'CONTAINS')), 'result' => array()), array('arguments' => array(array('blocked', 'CONTAINS')), 'result' => array()));
     $this->assertReferenceable($selection_options, $referenceable_tests, 'User handler');
     \Drupal::currentUser()->setAccount($users['admin']);
     $referenceable_tests = array(array('arguments' => array(array(NULL, 'CONTAINS')), 'result' => array('user' => array($users['anonymous']->id() => $user_labels['anonymous'], $users['admin']->id() => $user_labels['admin'], $users['non_admin']->id() => $user_labels['non_admin'], $users['blocked']->id() => $user_labels['blocked']))), array('arguments' => array(array('blocked', 'CONTAINS')), 'result' => array('user' => array($users['blocked']->id() => $user_labels['blocked']))), array('arguments' => array(array('Anonymous', 'CONTAINS'), array('anonymous', 'CONTAINS')), 'result' => array('user' => array($users['anonymous']->id() => $user_labels['anonymous']))));
     $this->assertReferenceable($selection_options, $referenceable_tests, 'User handler (admin)');
     // Test the 'include_anonymous' option.
     $selection_options['handler_settings']['include_anonymous'] = FALSE;
     $referenceable_tests = array(array('arguments' => array(array('Anonymous', 'CONTAINS'), array('anonymous', 'CONTAINS')), 'result' => array()));
     $this->assertReferenceable($selection_options, $referenceable_tests, 'User handler (does not include anonymous)');
 }
 /**
  * Create a user with a given set of permissions. The permissions correspond to the
  * names given on the privileges page.
  *
  * @param $role
  *   Role for the user: admin, manager, user
  * @param $groups
  *   Optional: An array of group nids or group node objects to which the newly
  *   created account should be a member of.
  * @return
  *   A fully loaded user object with pass_raw property, or FALSE if account
  *   creation fails.
  */
 function atriumCreateUser($role = 'user', $groups = array())
 {
     // Abbreviate 'authenticated user' to just 'user'.
     $role = $role === 'user' ? 'authenticated user' : $role;
     $rid = db_result(db_query("SELECT rid FROM {role} WHERE name = '%s'", $role));
     if ($rid) {
         // Create a user assigned to that role.
         $edit = array();
         $edit['name'] = $this->randomName();
         $edit['mail'] = $edit['name'] . '@example.com';
         $edit['roles'] = array($rid => $rid);
         $edit['pass'] = user_password();
         $edit['status'] = 1;
         $account = user_save('', $edit);
         // Add groups.
         if (!empty($account->uid) && !empty($groups)) {
             foreach ($groups as $value) {
                 $gid = is_object($value) && !empty($value->nid) ? $value->nid : $value;
                 og_save_subscription($gid, $account->uid, array('is_active' => TRUE));
             }
             // Reload user account with OG associations.
             og_get_subscriptions($account->uid, 1, TRUE);
             // Reset static cache.
             $account = user_load($account->uid);
         }
         $this->assertTrue(!empty($account->uid), t('User created with name %name, pass %pass and mail %mail', array('%name' => $edit['name'], '%pass' => $edit['pass'], '%mail' => $edit['mail'])), t('User login'));
         if (!empty($account->uid)) {
             // Add the raw password so that we can log in as this user.
             $account->pass_raw = $edit['pass'];
             return $account;
         }
     }
     return FALSE;
 }
 /**
  * Create a user with a given set of permissions. The permissions correspond to the
  * names given on the privileges page.
  *
  * @param $permissions
  *   Array of permission names to assign to user.
  * @return
  *   A fully loaded user object with pass_raw property, or FALSE if account
  *   creation fails.
  */
 protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'skip comment approval'))
 {
     // Create a role with the given permission set.
     if (!($rid = $this->drupalCreateRole($permissions))) {
         return FALSE;
     }
     // Create a user assigned to that role.
     $edit = array();
     $edit['name'] = $this->randomName();
     $edit['mail'] = $edit['name'] . '@example.com';
     $edit['roles'] = array($rid => $rid);
     $edit['pass'] = user_password();
     $edit['status'] = 1;
     $account = user_save(drupal_anonymous_user(), $edit);
     $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
     if (empty($account->uid)) {
         return FALSE;
     }
     // Add the raw password so that we can log in as this user.
     $account->pass_raw = $edit['pass'];
     return $account;
 }