2 min read

Programmatically creating and authenticating a user in Drupal 7

Drupal’s default login and registration interfaces are not always sufficient. Therefore, you might need to create your own solutions. Here’s an example of creating a user account and authenticating the user from a form that only asks for an email.

function one_click_register_form($form_state) {
  $form['email'] = array(
    '#id' => 'email',
    '#type' => 'textfield',
    '#title' => 'Email',
    '#size' => '20',
    '#description' => 'Your email address, e.g., google@google.com',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Register'),
  );
  return $form;
}

function one_click_register_form_validate($form_id, &$form_state) {
  if (!valid_email_address($form_state['values']['email'])) {
    form_set_error('email', 'Invalid email address provided');
  }
  else {
    // Check if a user already exists with this email.
    $count = db_select('users')
      ->condition('mail', $form_state['values']['email'])
      ->countQuery()
      ->execute()
      ->fetchField();
    if ($count != 0 ) {
      form_set_error('email', 'This email address is already in use. Enter another email.');
    }
  }
}

function one_click_register_form_submit($form_id, &$form_state) {
  global $user;
  // Data array to create user.
  $arguments = array(
    'name' => $form_state['values']['email'],
    'pass' => user_password(), // Generate password.
    'mail' => $form_state['values']['email'],
    'init' => $form_state['values']['email'],
    'status' => 1,
    'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
  );
  // Create user.
  user_save(NULL, $arguments);
  // Authenticate user.
  $uid = user_authenticate($arguments['name'], $arguments['pass']);
  $user = user_load($uid);
  user_login_finalize();
  // Required for rpt (Registration Password Token), otherwise token will be empty.
  $user->password = $arguments['pass'];
  // Trigger email sending event.
  _user_mail_notify('register_no_approval_required', $user);
  if ($user->uid) {
    drupal_set_message('Registration successful. The password has been sent to your email.');
  }
}

This way, we’ve created a form that requires only one field for registration and authentication. You can display this form using menu callbacks, Ctools popup, drupal_get_form, or other available methods.