You are here

protected function RestfulCsrfTokenTestCase::checkCsrfRequest in RESTful 7.2

Same name and namespace in other branches
  1. 7 tests/RestfulCsrfTokenTestCase.test \RestfulCsrfTokenTestCase::checkCsrfRequest()

Perform requests without, with invalid and with valid CSRF tokens.

Parameters

array $methods: Array with HTTP method names.

bool $csrf_required: Indicate if CSRF is required for the request, thus errors would be set if no CSRF or invalid one is sent with the request.

bool $auth_user: Determine if a user should be created and logged in. Defaults to TRUE.

2 calls to RestfulCsrfTokenTestCase::checkCsrfRequest()
RestfulCsrfTokenTestCase::testCsrfToken in tests/RestfulCsrfTokenTestCase.test
Test the validation of a CSRF token for authenticated users.
RestfulCsrfTokenTestCase::testCsrfTokenAnon in tests/RestfulCsrfTokenTestCase.test
Test the validation of a CSRF token for anonymous users.

File

tests/RestfulCsrfTokenTestCase.test, line 100
Contains RestfulCsrfTokenTestCase

Class

RestfulCsrfTokenTestCase

Code

protected function checkCsrfRequest($methods = array(), $csrf_required, $auth_user = TRUE) {
  $params['@role'] = $auth_user ? 'authenticated' : 'anonymous';
  foreach ($methods as $method) {
    $request = Request::isReadMethod($method) ? array() : array(
      'label' => $this
        ->randomName(),
    );
    $params['@method'] = $method;

    // No CSRF token.
    $result = $this
      ->httpRequest($this
      ->getPath($method), $method, $request, array(
      'Content-Type' => 'application/x-www-form-urlencoded',
    ), FALSE);
    if ($csrf_required) {
      $params['@code'] = 400;
      $this
        ->assertEqual($result['code'], $params['@code'], format_string('@code on @method without CSRF token for @role user.', $params));
    }
    else {
      $this
        ->assertTrue($result['code'] >= 200 && $result['code'] <= 204, format_string('@method without CSRF token for @role user is allowed.', $params));
    }

    // Invalid CSRF token.
    $result = $this
      ->httpRequest($this
      ->getPath($method), $method, $request, array(
      'Content-Type' => 'application/x-www-form-urlencoded',
      'X-CSRF-Token' => 'invalidToken',
    ), FALSE);
    if ($csrf_required) {
      $params['@code'] = 403;
      $this
        ->assertEqual($result['code'], $params['@code'], format_string('@code on @method with invalid CSRF token for @role user.', $params));
    }
    else {
      $this
        ->assertTrue($result['code'] >= 200 && $result['code'] <= 204, format_string('@method with invalid CSRF token for @role user is allowed.', $params));
    }

    // Valid CSRF token.
    $result = $this
      ->httpRequest($this
      ->getPath($method), $method, $request, array(
      'Content-Type' => 'application/x-www-form-urlencoded',
    ));
    $this
      ->assertTrue($result['code'] >= 200 && $result['code'] <= 204, format_string('@method allowed with CSRF token for @role user.', $params));
  }
}