Blog/ Create a service to request password

Services module makes it very easy to create a web service. The module includes common services such as reading a node, creating a node, reading user profile, logging in a user, among many others. One service I found missing was requesting a new password for a user. In this blog entry, we will write code to do exactly that. Create a module and implement "hook_services_resources_alter()". Using this hook, we will create an additional Action called "pass" to request for a new password.

/**
 * Implements hook_services_resources_alter().
 */
function mymodule_services_resources_alter(&$resources, &$endpoint) {
  // Add "pass" service.
  $resources['user']['actions']['pass'] = array(
    'help' => 'Request new password',
    'callback' => 'mymodule_user_resource_pass',
    'args' => array(
      array(
        'name' => 'name',
        'type' => 'string',
        'description' => 'A valid username or email address',
        'source' => array('data' => 'name'),
        'optional' => FALSE,
      ),
    ),
    'access callback' => 'services_access_menu',
  );
}

Assuming the user resource is at "rest/user.json", the above function will add a service at "rest/user/pass.json". Whenever this path is accessed, the Service module will call the callback function "mymodule_user_resource_pass()". Now let's write this function:

/**
 * Callback function for requesting a new password web service.
 */
function mymodule_user_resource_pass($name) {
  // Adds backward compatibility with regression fixed in #1083242
  $name = _service_arg_value($name, 'name');

  // Load required include files for requesting user's password
  module_load_include('inc', 'user', 'user.pages');

  // Fill form_state.
  $form_state['values']['name'] = $name;
  $form_state['values']['op'] = 'E-mail new password';

  // Execute the register form.
  drupal_form_submit('user_pass', $form_state);

  if ($errors = form_get_errors()) {
    // The supplied name is neither a username nor an email address.
    return service_error(implode(" ", $errors), 406, array('form_errors' => $errors));
  }
  else {
    // Requesting new password has been successful.
    return TRUE;
  }
}

The above function simulates filling user_pass() form by creating a form_state array with username in it. Then it submits the form. If there is any error, error 406 is returned. If form submission was successful, then an email is forwarded to the user with a link to create new password and the function returns TRUE to the web service client.

 

 
Ready to get started?REQUEST A QUOTE