You are here

function _services_keyauth_authenticate_call in Services 6.2

Same name and namespace in other branches
  1. 7 auth/services_keyauth/services_keyauth.inc \_services_keyauth_authenticate_call()

Authenticate a services method call with key authentication.

Parameters

$method: A method definition as returned by services_method_get().

$method_name: The name of the method being called

$args: An array of arguments required by key authentication. These are hash, domain, timestamp, and nonce. They must be in the array in this order.

1 string reference to '_services_keyauth_authenticate_call'
services_keyauth_authentication_info in auth/services_keyauth/services_keyauth.module
Implementation of hook_authentication_info().

File

auth/services_keyauth/services_keyauth.inc, line 191
The implementation of the key authentication scheme

Code

function _services_keyauth_authenticate_call($method, $method_name, &$args) {
  if ($method['key'] && variable_get('services_use_key', TRUE)) {
    $hash = array_shift($args);
    $domain = array_shift($args);
    $timestamp = array_shift($args);
    $nonce = array_shift($args);
    $expiry_time = $timestamp + variable_get('services_key_expiry', 30);
    if ($expiry_time < time()) {
      return services_error(t('Token has expired.'), 401);
    }

    // Still in time but has it been used before
    if (db_result(db_query("SELECT count(*) FROM {services_timestamp_nonce}\n        WHERE domain = '%s' AND nonce = '%s'", $domain, $nonce))) {
      return services_error(t('Token has been used previously for a request. Re-try with another nonce key.'), 401);
    }
    else {
      db_query("INSERT INTO {services_timestamp_nonce} (domain, timestamp, nonce)\n        VALUES ('%s', %d, '%s')", $domain, $timestamp, $nonce);
    }
    $api_key = db_result(db_query("SELECT kid FROM {services_keys} WHERE domain = '%s'", $domain));

    //if (!services_keyauth_validate_key($api_key, $timestamp, $domain, $nonce, $method_name, $hash_parameters, $hash)) {
    if ($hash != services_get_hash($timestamp, $domain, $nonce, $method, $args)) {
      return services_error(t('Invalid API key.'), 401);
    }
    if (!db_result(db_query("SELECT COUNT(*) FROM {services_key_permissions}\n        WHERE kid = '%s' AND method = '%s'", $api_key, $method_name))) {
      return services_error(t('Access denied.'), 401);
    }
  }

  // Add additonal processing for methods requiring session
  $session_backup = NULL;
  if ($method['auth'] && variable_get('services_use_sessid', TRUE)) {
    $sessid = array_shift($args);
    if (empty($sessid)) {
      return services_error(t('Invalid sessid.'), 401);
    }
    $session_backup = services_session_load($sessid);
  }
}