You are here

public function Client::authenticate in Media: Acquia DAM 8

Authenticates a user.

Parameters

array $data: An array of API parameters to pass. Defaults to password based authentication information.

Throws

\GuzzleHttp\Exception\GuzzleException

\cweagans\webdam\Exception\InvalidCredentialsException

1 call to Client::authenticate()
Client::checkAuth in src/Client.php
Authenticates with the DAM service and retrieves or uses an access token.

File

src/Client.php, line 158

Class

Client
Overridden implementation of the cweagans php-webdam-client.

Namespace

Drupal\media_acquiadam

Code

public function authenticate(array $data = []) {
  $url = $this->baseUrl . '/oauth2/token';
  if (empty($data)) {
    $data = [
      'grant_type' => 'password',
      'username' => $this->username,
      'password' => $this->password,
      'client_id' => $this->clientId,
      'client_secret' => $this->clientSecret,
    ];
  }

  // For error response body details:
  // @see \cweagans\webdam\tests\ClientTest::testInvalidClient().
  // @see \cweagans\webdam\tests\ClientTest::testInvalidGrant().
  // For successful auth response body details:
  // @see \cweagans\webdam\tests\ClientTest::testSuccessfulAuthentication().
  try {
    $response = $this->client
      ->request("POST", $url, [
      'form_params' => $data,
    ]);

    // Body properties: access_token, expires_in, token_type, refresh_token.
    $body = (string) $response
      ->getBody();
    $body = json_decode($body);
    $this->accessToken = $body->access_token;
    $this->accessTokenExpiry = time() + $body->expires_in;

    // We should only get an initial refresh_token and reuse it after the
    // first session. The access_token gets replaced instead of a new
    // refresh_token.
    $this->refreshToken = !empty($body->refresh_token) ? $body->refresh_token : $this->refreshToken;
  } catch (ClientException $e) {

    // For bad auth, the WebDAM API has been observed to return either
    // 400 or 403, so handle those via InvalidCredentialsException.
    $status_code = $e
      ->getResponse()
      ->getStatusCode();
    if ($status_code == 400 || $status_code == 403) {
      $body = (string) $e
        ->getResponse()
        ->getBody();
      $body = json_decode($body);
      throw new InvalidCredentialsException($body->error_description . ' (' . $body->error . ').');
    }
    else {

      // We've received an error status other than 400 or 403; log it
      // and move on.
      \Drupal::logger('media_acquiadam')
        ->error('Unable to authenticate. DAM API client returned a @code exception code with the following message: %message', [
        '@code' => $status_code,
        '%message' => $e
          ->getMessage(),
      ]);
    }
  }
}