You are here

function services_api_key_auth_services_authenticate in Services API Key Authentication 7

Apply authentication rules.

1 string reference to 'services_api_key_auth_services_authenticate'
services_api_key_auth_services_authentication_info in ./services_api_key_auth.module
Implements hook_services_authentication_info().

File

./services_api_key_auth.module, line 22
Extend services to allow API key authentication on endpoints.

Code

function services_api_key_auth_services_authenticate() {

  // Get function arguments.
  $args = func_get_args();

  // Get the key from the request.
  $api_key = '';
  switch ($args[0]['api_key_source']) {
    case 'request':
      $api_key = empty($_REQUEST['api-key']) ? '' : $_REQUEST['api-key'];
      break;
    case 'header':
      $api_key = empty($_SERVER['HTTP_API_KEY']) ? '' : $_SERVER['HTTP_API_KEY'];
      break;
  }

  // Validate request.
  $valid = (bool) services_api_key_auth_compare_key($api_key, $args[0]['api_key']);

  // Allow other modules to have their say.
  drupal_alter('services_api_key_valid', $valid, $args);
  if ($valid) {

    // If a valid request, switch to user to perform drupal response.
    if (!empty($args[0]['user'])) {
      global $user;
      $current_user = user_load_by_name($args[0]['user']);
      if (!empty($current_user)) {
        $user = $current_user;
        drupal_session_regenerate();
        drupal_add_http_header('Cache-Control', 'no-cache, must-revalidate, post-check=0, pre-check=0');
      }
    }
    return FALSE;
  }
  return services_error('Unauthorised access.', 403);
}