You are here

RestfulTokenAuthenticationTestCase.test in RESTful 7.2

Contains RestfulTokenAuthenticationTestCase.

File

modules/restful_token_auth/tests/RestfulTokenAuthenticationTestCase.test
View source
<?php

/**
 * @file
 * Contains RestfulTokenAuthenticationTestCase.
 */
use Drupal\restful\Exception\BadRequestException;
use Drupal\restful\Exception\UnauthorizedException;
use Drupal\restful\Http\Request;
class RestfulTokenAuthenticationTestCase extends DrupalWebTestCase {

  /**
   * {@inheritdoc}
   */
  public static function getInfo() {
    return array(
      'name' => 'Token Authentication',
      'description' => 'Test the request authentication with a token.',
      'group' => 'RESTful',
    );
  }

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp('restful_example', 'restful_token_auth', 'restful_token_auth_test');
    $this->user = $this
      ->drupalCreateUser();
  }

  /**
   * Testing the user's access token will be invalidate one the user is blocked.
   */
  function testTokenInvalidating() {
    $this
      ->drupalLogin($this->user);
    $resource_manager = restful()
      ->getResourceManager();
    $handler = $resource_manager
      ->getPlugin('access_token:1.0');

    // Generating token.
    $handler
      ->doGet();

    // Blocking the user.
    user_save($this->user, array(
      'status' => FALSE,
    ));

    // Verify the token removed.
    $query = new EntityFieldQuery();
    $result = $query
      ->entityCondition('entity_type', 'restful_token_auth')
      ->propertyCondition('uid', $this->user->uid)
      ->execute();
    $this
      ->assertTrue(empty($result), 'The access tokens invalidated when blocking the user.');
  }

  /**
   * Test authenticating a user.
   */
  function testAuthentication() {

    // Create user.
    $this
      ->drupalLogin($this->user);

    // Create "Article" node.
    $title1 = $this
      ->randomName();
    $settings = array(
      'type' => 'article',
      'title' => $title1,
      'uid' => $this->user->uid,
    );
    $node1 = $this
      ->drupalCreateNode($settings);
    $id = $node1->nid;
    $resource_manager = restful()
      ->getResourceManager();
    $formatter = restful()
      ->getFormatterManager()
      ->getPlugin('single_json');

    // Get a token for the user, using the handler.
    $handler = $resource_manager
      ->getPlugin('access_token:1.0');
    $formatter
      ->setResource($handler);
    $result = $formatter
      ->prepare($handler
      ->doGet());
    $access_token = $result['access_token'];
    $refresh_token = $result['refresh_token'];
    $this
      ->assertNotNull($access_token);
    $this
      ->assertNotNull($refresh_token);

    // Assert the token did not change.
    $result = $formatter
      ->prepare($handler
      ->doGet());
    $this
      ->assertEqual($access_token, $result['access_token'], 'Access token did not change.');

    // Get a "protected" resource without the access token.
    $handler = $resource_manager
      ->getPlugin('articles:1.3');
    $handler
      ->setRequest(Request::create('api/v1.3/articles'));
    $handler
      ->setPath('');
    $formatter
      ->setResource($handler);
    try {

      // Reset the account to trigger the auth process.
      $handler
        ->setAccount(NULL);
      $handler
        ->getAccount();
      $this
        ->fail('"Unauthorized" exception not thrown.');
    } catch (UnauthorizedException $e) {
      $this
        ->pass('"Unauthorized" exception was thrown.');
    }

    // Get a "protected" resource with invalid access token.
    $handler
      ->setRequest(Request::create('api/v1.3/articles', array(
      'access_token' => 'invalid',
    )));
    try {

      // Reset the account to trigger the auth process.
      $handler
        ->setAccount(NULL);
      $handler
        ->getAccount();
      $this
        ->fail('"Unauthorized" exception not thrown.');
    } catch (UnauthorizedException $e) {
      $this
        ->pass('"Unauthorized" exception was thrown.');
    }

    // Get a "protected" resource with refresh token as access token.
    $handler
      ->setRequest(Request::create('api/v1.3/articles/' . $id, array(
      'access_token' => 'invalid',
    )));
    $handler
      ->setPath($id);
    try {

      // Reset the account to trigger the auth process.
      $handler
        ->setAccount(NULL);
      $handler
        ->getAccount();
      $this
        ->fail('"Unauthorized" exception not thrown.');
    } catch (UnauthorizedException $e) {
      $this
        ->pass('"Unauthorized" exception was thrown.');
    }

    // Get a "protected" resource with refresh token.
    $handler
      ->setRequest(Request::create('api/v1.3/articles/' . $id, array(
      'refresh_token' => $refresh_token,
    )));
    $handler
      ->setPath($id);
    try {

      // Reset the account to trigger the auth process.
      $handler
        ->setAccount(NULL);
      $handler
        ->getAccount();
      $this
        ->fail('"Unauthorized" exception not thrown.');
    } catch (UnauthorizedException $e) {
      $this
        ->pass('"Unauthorized" exception was thrown.');
    }

    // Get a "protected" resource with the access token.
    $response = restful()
      ->getFormatterManager()
      ->negotiateFormatter(NULL)
      ->prepare($handler
      ->doGet($id, array(
      'access_token' => $access_token,
    )));
    $handler
      ->setAccount(NULL);
    $handler
      ->getAccount();

    // Validate the returned content.
    $result = $response['data'][0];
    $this
      ->assertEqual($result['label'], $title1, 'Article resource can be accessed with valid access token.');

    // Set the expiration token to the past.
    $query = new \EntityFieldQuery();
    $result = $query
      ->entityCondition('entity_type', 'restful_token_auth')
      ->entityCondition('bundle', 'access_token')
      ->propertyCondition('token', $access_token)
      ->execute();
    if (empty($result['restful_token_auth'])) {
      $this
        ->fail('No token was found.');
    }

    // Load the token.
    $access_id = key($result['restful_token_auth']);
    $token = entity_load_single('restful_token_auth', $access_id);
    $token->expire = REQUEST_TIME - 60 * 24;
    $token
      ->save();

    // Make a GET request to trigger a deletion of the token.
    $handler = $resource_manager
      ->getPlugin('articles:1.3');
    $formatter
      ->setResource($handler);
    $handler
      ->setRequest(Request::create('api/v1.3/articles/' . $id, array(
      'access_token' => $access_token,
    )));
    $handler
      ->setPath($id);
    try {

      // Reset the account to trigger the auth process.
      $handler
        ->setAccount(NULL);
      $handler
        ->getAccount();
      $this
        ->fail('"Unauthorized" exception not thrown for expired token.');
    } catch (UnauthorizedException $e) {
      $this
        ->pass('"Unauthorized" exception was thrown for expired token.');
    }

    // Make sure the token was deleted.
    $query = new \EntityFieldQuery();
    $count = $query
      ->entityCondition('entity_type', 'restful_token_auth')
      ->entityCondition('bundle', 'access_token')
      ->propertyCondition('token', $access_token)
      ->count()
      ->execute();
    $this
      ->assertFalse($count, 'The token was deleted.');

    // Test the refresh capabilities.
    $handler = $resource_manager
      ->getPlugin('refresh_token:1.0');
    $formatter
      ->setResource($handler);
    $result = $formatter
      ->prepare($handler
      ->doGet($refresh_token));
    $this
      ->assertNotNull($result['access_token'], 'A new access token granted for a valid refresh token.');
    $this
      ->assertNotNull($result['refresh_token'], 'A new refresh token granted for a valid refresh token.');
    $this
      ->assertNotEqual($refresh_token, $result['refresh_token']);

    // Test invalid refresh token.
    try {
      $handler
        ->doGet('invalid');
      $this
        ->fail('"Bad Request" exception not thrown.');
    } catch (BadRequestException $e) {
      $this
        ->pass('"Bad Request" exception was thrown.');
    }
  }

}