You are here

function yandex_services_auth_oauth_callback in Yandex Services Authorization API 6

Same name and namespace in other branches
  1. 7 yandex_services_auth.admin.inc \yandex_services_auth_oauth_callback()

Menu callback. Perform auth token request by code parameter from url. More information at (Russian): http://api.yandex.ru/oauth/doc/dg/reference/obtain-access-token.xml

1 string reference to 'yandex_services_auth_oauth_callback'
yandex_services_auth_menu in ./yandex_services_auth.module
Implements hook_menu().

File

./yandex_services_auth.admin.inc, line 85
Admin pages for the Yandex Services Authorization API module.

Code

function yandex_services_auth_oauth_callback() {
  if (empty($_GET['code'])) {
    watchdog('yandex_services_auth', 'The "code" parameter is empty.', array(), WATCHDOG_WARNING);
    drupal_set_message(t('An error has occurred. Please try again.'), 'error');
    drupal_goto('admin/settings/yandex_services_auth');
  }
  if (empty($_GET['state']) || empty($_SESSION['yandex_services_auth']['state']) || $_GET['state'] !== $_SESSION['yandex_services_auth']['state']) {
    watchdog('yandex_services_auth', 'The "state" parameter is invalid.', array(), WATCHDOG_WARNING);
    drupal_set_message(t('An error has occurred. Please try again.'), 'error');
    drupal_goto('admin/config/system/yandex_services_auth');
  }
  $client_id = variable_get('yandex_services_auth_client_id', '');
  $client_secret = variable_get('yandex_services_auth_client_secret', '');
  $data = 'grant_type=authorization_code&client_id=' . $client_id . '&code=' . $_GET['code'];
  if (!empty($client_secret)) {
    $data .= '&client_secret=' . $client_secret;
  }
  $result = drupal_http_request('https://oauth.yandex.ru/token', array(), 'POST', $data);
  if (isset($result->error)) {
    watchdog('yandex_services_auth', 'Token request failed with error "%error".', array(
      '%error' => $result->code . ' ' . $result->error,
    ), WATCHDOG_WARNING);
    drupal_set_message(t('An error has occurred. Please try again.'), 'error');
    drupal_goto('admin/settings/yandex_services_auth');
  }
  $response = json_decode($result->data);
  variable_set('yandex_services_auth_token', $response->access_token);
  if (isset($response->expires_in)) {
    variable_set('yandex_services_auth_timestamp', time() + $response->expires_in);
  }
  else {

    // If no 'expires_in' returned - then there is no expiration.
    variable_del('yandex_services_auth_timestamp');
  }
  watchdog('yandex_services_auth', 'Token request is successful.');
  drupal_set_message(t('Congratulations! Your application has been authorized by Yandex.'));
  drupal_goto('admin/settings/yandex_services_auth');
}