You are here

public static function drupalchatController::_drupalchat_get_auth in DrupalChat 8

3 calls to drupalchatController::_drupalchat_get_auth()
drupalchatController::drupalchat_app_settings in src/Controller/drupalchatController.php
Function to render drupalchat app settings iframe.
drupalchatController::ex_auth in src/Controller/drupalchatController.php
drupalchatSettingsForm::validateForm in src/Form/drupalchatSettingsForm.php
Form validation handler.

File

src/Controller/drupalchatController.php, line 944
Contains Drupal\drupalchat\Controller\drupalchatController

Class

drupalchatController

Namespace

Drupal\drupalchat\Controller

Code

public static function _drupalchat_get_auth($formValues) {

  // Load the current user.
  $user = \Drupal::currentUser();

  // check if the auth request is from the setttings page.
  if (array_key_exists('api_key', $formValues)) {
    $api_key = $formValues['api_key'];
  }
  else {
    $api_key_from_database = \Drupal::config('drupalchat.settings')
      ->get('drupalchat_external_api_key') ?: NULL;
    $api_key = trim($api_key_from_database);
  }
  if (array_key_exists('app_id', $formValues)) {
    $app_id = $formValues['app_id'];
  }
  else {
    $app_id_from_database = \Drupal::config('drupalchat.settings')
      ->get('drupalchat_app_id') ?: NULL;
    $app_id = trim($app_id_from_database);
  }
  $data = array(
    'api_key' => $api_key,
    'app_id' => $app_id,
    'version' => 'D8-8.1.0',
  );
  $user_data = drupalchatController::_drupalchat_get_user_details();
  $data = array_merge($data, $user_data);
  $_SESSION['user_data'] = json_encode($user_data);
  $url = DRUPALCHAT_EXTERNAL_A_HOST . ':' . DRUPALCHAT_EXTERNAL_A_PORT . '/api/1.1/token/generate';
  $client = \Drupal::httpClient();

  // print_r($data);
  try {
    $request = $client
      ->post($url, [
      'verify' => false,
      'form_params' => $data,
    ]);
  } catch (BadResponseException $exception) {
    $code = $exception
      ->getResponse()
      ->getStatusCode();
    $error = $exception
      ->getResponse()
      ->getReasonPhrase();
    $e = array(
      'code' => $code,
      'error' => $error,
    );
    return $e;
  } catch (RequestException $exception) {
    $e = array(
      'code' => $exception
        ->getResponse()
        ->getStatusCode(),
      'error' => $exception
        ->getResponse()
        ->getReasonPhrase(),
    );
    return $e;
  }
  if (json_decode($request
    ->getStatusCode()) == 200) {
    $response = json_decode($request
      ->getBody());
    if ($user
      ->isAuthenticated()) {
      $_SESSION['token'] = $response->key;
    }
    if (array_key_exists('app_id', $response)) {
      \Drupal::configFactory()
        ->getEditable('drupalchat.settings')
        ->set('drupalchat_app_id', $response->app_id)
        ->save();
    }
    return $response;
  }
}