How can you contact us

2By phone at +40 749 014 360

If you still have problems, please let us know, by sending an email to info@westweb-solutions.com Thank you!

OFFICE HOURS

Mon-Fri 9:00AM - 6:00AM
Sat - 9:00AM - 1:00PM
Sundays by appointment only!

Drupal 7 - Custom User Verification

/ / Drupal 7

In this article, we will implement a custom user mail verification.

The workflow would be something like this:
- the user registers
- he starts using the application
- he needs to "unlock" a few more steps by verifying his email and/or phone number

We will start by creating a custom module and we'll call it "custom_module_user".

 

1. Create "Email verified" field

The easiest way to store the "mail verified" value is to create a new field on the user entity.
In order to achieve this, we will implement "hook_install" and "hook_uninstall" in our custom_module_user.install

<?php

define('FIELD_EMAIL_VERIFIED', 'field_email_verified');

/**
 * Implements hook_install().
 */
function custom_module_user_install() {
  $fields = array(
    FIELD_EMAIL_VERIFIED => array(
      'field' => array(
        'field_name' => FIELD_EMAIL_VERIFIED,
        'module' => 'list',
        'cardinality' => 1,
        'type' => 'list_boolean',
        'settings' => array(
          'allowed_values' => array(
             0 => 'Unverified',
             1 => 'Verified',
           ),
          'allowed_values_function' => ''
        ),
      ),
      'field_instance' => array(
        'label' => t('Email verified'),
        'default_value' => array(
          0 => array(
            'value' => 0
          )
        ),
        'required' => FALSE,
        'widget' => array(
          'active' => 1,
          'module' => 'options',
          'settings' => array(
            'display_label' => 1,
          ),
          'type' => 'options_onoff',
        ),
      )
    )
  );

  foreach ($fields as $field_machine_name => $field_info) {
    field_create_field($field_info['field']);

    // Create the instance.
    $field_instance = array(
      'field_name' => $field_machine_name,
      'entity_type' => 'user',
      'bundle' => 'user',
    ) + $field_info['field_instance'];

    field_create_instance($field_instance);
    watchdog('custom_module_user', t('!field_name was added successfully.', array('!field_name' => $field_machine_name)));
  }
}

/**
 * Implements hook_uninstall().
 */
function custom_module_user_uninstall() {
  $instance = array(
    'field_name' => FIELD_EMAIL_VERIFIED,
    'bundle' => 'user',
    'entity_type' => 'user',
  );
  field_delete_instance($instance);
}

By using these hooks, we automatically create the field during the module install and remove it when uninstalling it.

 

2. Create routes using the "hook_menu"

2.1. Settings form

  $items['admin/config/custom_module_user'] = [
    'title' => 'Custom Module User - Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => ['custom_module_user_config_form'],
    'file' => 'includes/custom_module_user.admin.inc',
    'access arguments' => ['access administration pages'],
  ];

function custom_module_user_config_form($form, $form_state) {
  $form['custom_module_user_verification_body'] = array(
    '#type' => 'textarea',
    '#title' => t('User verification mail body'),
    '#default_value' => variable_get('custom_module_user_verification_body', "Follow the link below to make sure you activated your account.\n\r
[user:verification-url]"),
    '#description' => 'Use the following token [user:verification-url] for the verification link.'
  );

  return system_settings_form($form);
}

drupal7 mail verification settings

2.2. Ajax route for sending the verification mail

  $items['custom-module-user/send-activation-link'] = array(
    'title' => 'Send Activation Link',
    'page callback' => 'custom_module_user_send_activation_link',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'file' => 'includes/custom_module_user.pages.inc',
    'delivery callback' => 'ajax_deliver',
  );

function custom_module_user_send_activation_link() {
  global $user;

  if ($user->uid) {
    $status = drupal_mail('custom_module_user', 'verification', $user->mail, language_default(), array());
    if ($status) {
      $commands[] = ajax_command_replace('#user-verified', 'Verification mail sent; please check your inbox.');
    }
    else {
      $commands[] = ajax_command_replace('#user-verified', 'Verification mail not sent; please try again later.');
    }
  }

  $ajax_deliver = array('#type' => 'ajax', '#commands' => $commands);
  return $ajax_deliver;
}
drupal7 mail verification unverified
drupal7 mail verification sent
drupal7 mail verification email

2.3. Verification route

  $items['verify/email/%user/%'] = array(
    'title' => 'Verify Email',
    'page callback' => 'custom_module_user_verify_email',
    'page arguments' => array(2, 3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'includes/custom_module_user.pages.inc',
  );

function custom_module_user_verify_email($account, $token) {
  global $user;
  $output = '';

  if ($user->uid == $account->uid) {
    if (! isset($account->field_email_verified[LANGUAGE_NONE][0]['value']) || ! $account->field_email_verified[LANGUAGE_NONE][0]['value']) {
      if ($token = md5($account->mail)) {
        $transaction = db_transaction();
        try {
          $update_user = new stdClass();
          $update_user->uid = $user->uid;
          $update_user->field_email_verified[LANGUAGE_NONE][0]['value'] = TRUE;
          field_attach_update('user', $update_user);
          $message = t('E-mail verified.');
        }
        catch (Exception $e) {
          $message = t('An error occured while trying to verify the e-mail.');
          $transaction->rollback();
          throw $e;
        }
      }
      else {
        $message = t('Token unrecognized.');
      }
    }
    else {
      $message = t('E-mail already verified.');
    }
  }
  else {
    if ($user->uid) {
      $message = t('Token do not match with the current logged in user.');
    }
    else {
      $message = t('Please login before verifying the e-mail.');
    }
  }

  $output = $message;

  return $output;
}

drupal7 mail verification mail verified

 

3. Define and implement the "verification url" token

/**
 * Implements hook_token_info(). This hook will register "verification url" token.
 */
function custom_module_user_token_info() {
  $info['tokens']['user']['verification-url'] = array(
    'name' => t('Verification URL'),
    'restricted' => TRUE,
  );

  return $info;
}

/**
 * Implements hook_tokens().
 */
function custom_module_user_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  $url_options = array('absolute' => TRUE);

  // User tokens.
  if ($type == 'user' && !empty($data['user'])) {
    $account = $data['user'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'verification-url':
          $url = url("verify/email/{$account->uid}/" . md5($account->mail), $url_options);
          $replacements[$original] = l(
            $url,
            $url
          );
          break;
      }
    }
  }

  return $replacements;
}

Sign in your account to have access to different features

Forgot your details?

TOP