RESTful-Drupal / restful

RESTful best practices for Drupal
https://drupal.org/project/restful
419 stars 173 forks source link

email token auth #635

Open bossa opened 9 years ago

bossa commented 9 years ago

Hi, I need generate my token auth with email and password instead username, because username is autogenerated in my drupal system. Any idea ? thanks!

e0ipso commented 9 years ago

Since the token auth is a plugin / class, you can create a new auth provider inheriting from token auth. In that new auth provider you can tweak as much as you want.

Please, if you end up implementing this, write a recipe in https://www.drupal.org/node/2399453

Don't hesitate to contact for more info.

aschmoe commented 7 years ago

The issue in implementing this was how credentials in \Drupal\restful\Http\RequestInterface $request are checked in Drupal\restful\Http\Request::getCredentials(), as there was not a simple location to extend / override as far as I could tell.

This is an admittedly hacky solution, and I'm sure there is a solution more in-line with the RESTful's approach but it works for anyone trying to figure this out:

/**
 * Tries to convert email to username
 */
function my_module_email_to_user($username) {
  if(valid_email_address($username)) {
    $user = user_load_by_mail($username);
    if(!empty($user->name) && $user->name !== 'Anonymous') {
      $_SERVER['PHP_AUTH_USER'] = $user->name;
    }
  }
}

/**
 * Allow altering the request before it is processed.
 *
 * @param \Drupal\restful\Http\RequestInterface $request
 *   The request object.
 */
function my_module_restful_parse_request_alter(\Drupal\restful\Http\RequestInterface &$request) {
  // have a user, so convert to from email to user if applicable
  if(!empty($_SERVER['PHP_AUTH_USER'])) {
    my_module_email_to_user($_SERVER['PHP_AUTH_USER']);
    return;
  }
  // Try to fill PHP_AUTH_USER & PHP_AUTH_PW with REDIRECT_HTTP_AUTHORIZATION
  // for compatibility with Apache PHP CGI/FastCGI.
  // This requires the following line in your ".htaccess"-File:
  // RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
  $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : NULL;
  $authorization_header = $authorization_header ?: (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) ? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] : NULL);
  if (!empty($authorization_header)) {
    if (!$token = Drupal\restful\Util\StringHelper::removePrefix('Basic ', $authorization_header)) {
      return NULL;
    }
    $authentication = base64_decode($token);
    list($username, $password) = explode(':', $authentication);
    // have a user, so convert to from email to user if applicable
    my_module_email_to_user($username);
    $_SERVER['PHP_AUTH_PW'] = $password;
  }
}