Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#102: Fix status codes for expired tokens #103

Merged
merged 5 commits into from
Mar 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased
- Add OAuth support for Google [#97](https://github.com/nicumicle/simple-jwt-login/issues/97)
- Fix status code for expired tokens [#102](https://github.com/nicumicle/simple-jwt-login/issues/102)

## 3.5.3 (16 November 2023)
- Fix licence in composer.json
Expand Down
Binary file modified download/simple-jwt-login.zip
Binary file not shown.
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
bootstrap="phpunit_bootstrap.php"
backupGlobals="false"
colors="true"
testdox="true"
processIsolation="true"
stopOnFailure="false"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.3/phpunit.xsd"
Expand Down
18 changes: 10 additions & 8 deletions simple-jwt-login/routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use SimpleJWTLogin\Helpers\CorsHelper;
use SimpleJWTLogin\Helpers\ServerHelper;
use SimpleJWTLogin\Helpers\StatusCodeHelper;
use SimpleJWTLogin\Libraries\ParseRequest;
use SimpleJWTLogin\Modules\SimpleJWTLoginHooks;
use SimpleJWTLogin\Services\ProtectEndpointService;
Expand Down Expand Up @@ -82,15 +83,16 @@
->loginUser(
$routeService->getUserFromJwt($jwt)
);
} catch (\Exception $e) {
} catch (\Exception $exception) {
@header('Content-Type: application/json; charset=UTF-8');

wp_send_json_error(
[
'message' => $e->getMessage(),
'errorCode' => $e->getCode(),
'message' => $exception->getMessage(),
'errorCode' => $exception->getCode(),
'type' => 'simple-jwt-login-middleware'
],
400
StatusCodeHelper::getStatusCodeFromExeption($exception, 400)
);
return false;
}
Expand Down Expand Up @@ -178,14 +180,14 @@
$service->withSession($_SESSION);
}
return $service->makeAction();
} catch (Exception $e) {
} catch (Exception $exception) {
@header('Content-Type: application/json; charset=UTF-8');
wp_send_json_error(
[
'message' => $e->getMessage(),
'errorCode' => $e->getCode()
'message' => $exception->getMessage(),
'errorCode' => $exception->getCode()
],
400
StatusCodeHelper::getStatusCodeFromExeption($exception, 400)
);

return false;
Expand Down
28 changes: 28 additions & 0 deletions simple-jwt-login/src/Helpers/StatusCodeHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace SimpleJWTLogin\Helpers;

use SimpleJWTLogin\ErrorCodes;

class StatusCodeHelper
{
/**
* @param \Exception $exception
* @return int
*/
public static function getStatusCodeFromExeption($exception, $defaultStatusCode)

Check warning on line 13 in simple-jwt-login/src/Helpers/StatusCodeHelper.php

View check run for this annotation

Codecov / codecov/patch

simple-jwt-login/src/Helpers/StatusCodeHelper.php#L13

Added line #L13 was not covered by tests
{
$unauthorizedCode = array(
ErrorCodes::ERR_REVOKED_TOKEN,
ErrorCodes::ERR_TOKEN_EXPIRED,
ErrorCodes::ERR_TOKEN_IAT,
ErrorCodes::ERR_TOKEN_NBF,
);

Check warning on line 20 in simple-jwt-login/src/Helpers/StatusCodeHelper.php

View check run for this annotation

Codecov / codecov/patch

simple-jwt-login/src/Helpers/StatusCodeHelper.php#L15-L20

Added lines #L15 - L20 were not covered by tests

if (in_array($exception->getCode(), $unauthorizedCode)) {
return 401;

Check warning on line 23 in simple-jwt-login/src/Helpers/StatusCodeHelper.php

View check run for this annotation

Codecov / codecov/patch

simple-jwt-login/src/Helpers/StatusCodeHelper.php#L22-L23

Added lines #L22 - L23 were not covered by tests
}

return $defaultStatusCode;

Check warning on line 26 in simple-jwt-login/src/Helpers/StatusCodeHelper.php

View check run for this annotation

Codecov / codecov/patch

simple-jwt-login/src/Helpers/StatusCodeHelper.php#L26

Added line #L26 was not covered by tests
}
}
6 changes: 4 additions & 2 deletions tests/Feature/AccessEndpoints/EmptyOptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

namespace SimpleJwtLoginTests\Feature\AccessEndpoints;

use PHPUnit\Framework\Attributes\TestDox;
use SimpleJWTLogin\ErrorCodes;
use SimpleJwtLoginTests\Feature\TestBase;
use PHPUnit\Framework\Attributes\DataProvider;

class EmptyOptionsTest extends TestBase
{
Expand Down Expand Up @@ -88,9 +90,9 @@ public static function endpointsProvider()
];
}

#[DataProvider('endpointsProvider')]
#[TestDox("Access endpoints is not allowed")]
/**
* @testdox Access endpoints is not allowed
* @dataProvider endpointsProvider
* @return void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
Expand Down
10 changes: 6 additions & 4 deletions tests/Feature/AccessEndpoints/RevokedJWTTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace SimpleJwtLoginTests\Feature\AccessEndpoints;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestDox;
use SimpleJWTLogin\ErrorCodes;
use SimpleJwtLoginTests\Feature\TestBase;

Expand Down Expand Up @@ -80,9 +82,9 @@ public static function endpointsProvider()
];
}

#[DataProvider('endpointsProvider')]
#[TestDox("Calling endpoints with revoked JWT")]
/**
* @testdox Calling endpoints with revoked JWT
* @dataProvider endpointsProvider
* @param string $method
* @param string $endpoint
* @return void
Expand All @@ -96,7 +98,7 @@ public function testRevokedJWT($method, $endpoint)
'allow_redirects' => [
'track_redirects' => true,
],
],
]
);

// Register random user
Expand Down Expand Up @@ -142,7 +144,7 @@ public function testRevokedJWT($method, $endpoint)
'email' => $email,
'password' => $password,
]),
],
]
);

$contents = $response->getBody()->getContents();
Expand Down
14 changes: 5 additions & 9 deletions tests/Feature/Authentication/SuccessTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace SimpleJwtLoginTests\Feature\Authentication;

use PHPUnit\Framework\Attributes\TestDox;
use SimpleJwtLoginTests\Feature\TestBase;

class SuccessTest extends TestBase
Expand Down Expand Up @@ -39,9 +40,7 @@ public static function setUpBeforeClass(): void
]);
}

/**
* @testdox User can authenticate with email and password
*/
#[TestDox("User can authenticate with email and password")]
public function testAuthenticationEmail()
{
// Register random user
Expand All @@ -68,9 +67,8 @@ public function testAuthenticationEmail()
$this->assertSame(200, $statusCode, "unable to delete the user");
}

/**
* @testdox User can refresh a valid JWT
*/

#[TestDox("User can refresh a valid JWT")]
public function testRefreshToken()
{
// Register random user
Expand Down Expand Up @@ -107,9 +105,7 @@ public function testRefreshToken()
$this->assertSame(200, $statusCode, "unable to delete the user");
}

/**
* @testdox User can validate a JWT
*/
#[TestDox("User can validate a JWT")]
public function testValidateToken()
{
// Register random user
Expand Down
2 changes: 1 addition & 1 deletion tests/Feature/Autologin/SuccessTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function testSuccessAutologin()
'allow_redirects' => [
'track_redirects' => true,
],
],
]
);

// Register random user
Expand Down
50 changes: 26 additions & 24 deletions tests/Feature/Autologin/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace SimpleJwtLoginTests\Feature\Autologin;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestDox;
use SimpleJWTLogin\ErrorCodes;
use SimpleJwtLoginTests\Feature\TestBase;

Expand Down Expand Up @@ -47,82 +49,82 @@ public static function autologinValidationProvider()
return [
'empty_jwt' => [
'jwt' => null,
'error_message' => 'Wrong Request.',
'error_code' => ErrorCodes::ERR_VALIDATE_LOGIN_WRONG_REQUEST,
'errorMessage' => 'Wrong Request.',
'errorCode' => ErrorCodes::ERR_VALIDATE_LOGIN_WRONG_REQUEST,
],
'invalid_jwt' => [
'jwt' => "123",
'error_message' => 'Wrong number of segments',
'error_code' => ErrorCodes::ERR_WRONG_NUMBER_OF_SEGMENTS,
'errorMessage' => 'Wrong number of segments',
'errorCode' => ErrorCodes::ERR_WRONG_NUMBER_OF_SEGMENTS,
],
'invalid_jwt_values' => [
'jwt' => "1.1.2",
'error_message' => 'Syntax error, malformed JSON',
'error_code' => ErrorCodes::ERR_UNKNOWN_ERROR,
'errorMessage' => 'Syntax error, malformed JSON',
'errorCode' => ErrorCodes::ERR_UNKNOWN_ERROR,
],
];
}

#[DataProvider('autologinValidationProvider')]
#[TestDox("Autologin Validation with JWT as Query Parameter")]
/**
* @testdox Autologin Validation with JWT as Query Parameter
* @dataProvider autologinValidationProvider
* @param ?string $jwt
* @param string $expectedErrorMessage
* @param int $expectedErrorCode
* @param string $errorMessage
* @param int $errorCode
* @return void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function testJWTInQueryParams($jwt, $expectedErrorMessage, $expectedErrorCode)
public function testJWTInQueryParams($jwt, $errorMessage, $errorCode)
{
$response = $this->client->get(
self::API_URL . "?rest_route=/simple-jwt-login/v1/autologin&JWT=" . $jwt,
self::API_URL . "?rest_route=/simple-jwt-login/v1/autologin&JWT=" . $jwt
);

$contents = $response->getBody()->getContents();
$contentsArr = json_decode($contents, true);

$expectedError = $this->generateErrorJson(
$expectedErrorMessage,
$expectedErrorCode
$errorMessage,
$errorCode
);

$this->assertSame(
$expectedError,
$contentsArr,
$contentsArr
);
}

#[DataProvider('autologinValidationProvider')]
#[TestDox("Autologin Validation with JWT in the Header")]
/**
* @testdox Autologin Validation with JWT in the Header
* @dataProvider autologinValidationProvider
* @param ?string $jwt
* @param string $expectedErrorMessage
* @param int $expectedErrorCode
* @param string $errorMessage
* @param int $errorCode
* @return void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function testJWTInHeader($jwt, $expectedErrorMessage, $expectedErrorCode)
public function testJWTInHeader($jwt, $errorMessage, $errorCode)
{
$response = $this->client->get(
self::API_URL . "?rest_route=/simple-jwt-login/v1/autologin",
[
'headers' => [
'Authorization' => $jwt,
],
],
]
);

$contents = $response->getBody()->getContents();
$contentsArr = json_decode($contents, true);

$expectedError = $this->generateErrorJson(
$expectedErrorMessage,
$expectedErrorCode
$errorMessage,
$errorCode
);

$this->assertSame(
$expectedError,
$contentsArr,
$contentsArr
);
}
}
11 changes: 6 additions & 5 deletions tests/Feature/ProtectEndpoints/ActiveOnAllEndpointsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace SimpleJwtLoginTests\Feature\ProtectEndpoints;

use PHPUnit\Framework\Attributes\TestDox;
use SimpleJWTLogin\Modules\Settings\ProtectEndpointSettings;
use SimpleJwtLoginTests\Feature\TestBase;

Expand Down Expand Up @@ -51,8 +52,8 @@ public static function setUpBeforeClass(): void
]);
}

#[TestDox("WordPress endpoint can be accessed without JWT if whitelisted")]
/**
* @testdox WordPress endpoint can be accessed without JWT if whitelisted
* @return void
*/
public function testCanAccessWhitelistedEndpoint()
Expand All @@ -62,8 +63,8 @@ public function testCanAccessWhitelistedEndpoint()
$this->assertEquals(200, $resp->getStatusCode());
}

#[TestDox("WordPress endpoint can't be accessed without JWT if whitelisted")]
/**
* @testdox WordPress endpoint can't be accessed without JWT if whitelisted
* @return void
*/
public function testEndpointCanNotBeAccessedWithoutJWT()
Expand All @@ -77,14 +78,14 @@ public function testEndpointCanNotBeAccessedWithoutJWT()
$this->generateErrorJson(
"You are not authorized to access this endpoint.",
403,
['type' => 'simple-jwt-login-route-protect'],
['type' => 'simple-jwt-login-route-protect']
),
$contentsArr,
$contentsArr
);
}

#[TestDox("WordPress endpoint can be accessed with JWT if whitelisted")]
/**
* @testdox WordPress endpoint can be accessed with JWT if whitelisted
* @return void
*/
public function testEndpointCanBeAccessedWithJWT()
Expand Down
Loading
Loading