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

Improve compatibility with Symfony 6.x #1950

Merged
merged 3 commits into from
Aug 26, 2023
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
8 changes: 2 additions & 6 deletions src/Security/Core/User/OAuthUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,12 @@ public function getUsername(): string
return $this->getUserIdentifier();
}

public function eraseCredentials(): bool
public function eraseCredentials(): void
{
return true;
}

public function equals(UserInterface $user): bool
{
// @phpstan-ignore-next-line Symfony <5.4 BC layer
$username = method_exists($user, 'getUserIdentifier') ? $user->getUserIdentifier() : $user->getUsername();

return $username === $this->username;
return $user->getUserIdentifier() === $this->username;
}
}
37 changes: 6 additions & 31 deletions tests/App/AppKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Controller\UserValueResolver;

final class AppKernel extends Kernel
{
Expand Down Expand Up @@ -58,35 +56,12 @@ public function prepareContainer(ContainerBuilder $container): void
{
parent::prepareContainer($container);

// With Symfony 5.3+, session settings were changed
if (Kernel::VERSION_ID >= 50300) {
$container->prependExtensionConfig('framework', [
'session' => [
'enabled' => true,
'storage_factory_id' => 'session.storage.factory.mock_file',
],
]);
} else {
$container->prependExtensionConfig('framework', [
'session' => [
'enabled' => true,
'storage_id' => 'session.storage.mock_file',
],
]);
}

if (method_exists(Security::class, 'getUser') && !class_exists(UserValueResolver::class)) {
$container->loadFromExtension('security', [
'firewalls' => [
'login_area' => [
'logout_on_user_change' => true,
],
'main' => [
'logout_on_user_change' => true,
],
],
]);
}
$container->prependExtensionConfig('framework', [
'session' => [
'enabled' => true,
'storage_factory_id' => 'session.storage.factory.mock_file',
],
]);
}

public function getCacheDir(): string
Expand Down
16 changes: 11 additions & 5 deletions tests/Controller/LoginControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
Expand All @@ -23,7 +24,7 @@
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Security as DeprecatedSecurity;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Twig\Environment;

Expand Down Expand Up @@ -119,7 +120,7 @@ public function testRegistrationRedirect(): void
{
$this->request->attributes = new ParameterBag(
[
Security::AUTHENTICATION_ERROR => new AccountNotLinkedException(),
$this->getSecurityErrorKey() => new AccountNotLinkedException(),
]
);

Expand All @@ -144,7 +145,7 @@ public function testRequestError(): void

$this->request->attributes = new ParameterBag(
[
Security::AUTHENTICATION_ERROR => $authenticationException,
$this->getSecurityErrorKey() => $authenticationException,
]
);

Expand All @@ -164,15 +165,15 @@ public function testSessionError(): void

$this->session->expects($this->once())
->method('has')
->with(Security::AUTHENTICATION_ERROR)
->with($this->getSecurityErrorKey())
->willReturn(true)
;

$authenticationException = new AuthenticationException();

$this->session->expects($this->once())
->method('get')
->with(Security::AUTHENTICATION_ERROR)
->with($this->getSecurityErrorKey())
->willReturn($authenticationException)
;

Expand Down Expand Up @@ -207,4 +208,9 @@ private function createController(): LoginController
'IS_AUTHENTICATED_REMEMBERED'
);
}

private function getSecurityErrorKey(): string
{
return class_exists(Security::class) ? Security::AUTHENTICATION_ERROR : DeprecatedSecurity::AUTHENTICATION_ERROR;
}
}
18 changes: 7 additions & 11 deletions tests/Functional/Controller/LoginControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException;
use HWI\Bundle\OAuthBundle\Tests\Functional\AuthenticationHelperTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Security as DeprecatedSecurity;
use Symfony\Contracts\HttpClient\HttpClientInterface;

final class LoginControllerTest extends WebTestCase
Expand Down Expand Up @@ -48,7 +48,7 @@ public function testRedirectingToRegistrationFormWithError(): void
$client = self::createClient();

$session = $this->getSession($client);
$session->set(Security::AUTHENTICATION_ERROR, new AccountNotLinkedException());
$session->set($this->getSecurityErrorKey(), new AccountNotLinkedException());

$this->saveSession($client, $session);

Expand All @@ -67,10 +67,10 @@ public function testLoginPageWithError(): void
$client = self::createClient();
$client->getContainer()->set('hwi_oauth.http_client', $httpClient);

$exception = $this->createUserNotFoundException();
$exception = new UserNotFoundException();

$session = $this->getSession($client);
$session->set(Security::AUTHENTICATION_ERROR, $exception);
$session->set($this->getSecurityErrorKey(), $exception);

$this->logIn($client, $session);

Expand All @@ -82,12 +82,8 @@ public function testLoginPageWithError(): void
$this->assertSame($exception->getMessageKey(), $crawler->filter('span')->text(), $response->getContent());
}

private function createUserNotFoundException()
private function getSecurityErrorKey(): string
{
if (class_exists(UserNotFoundException::class)) {
return new UserNotFoundException();
}

return new UsernameNotFoundException();
return class_exists(Security::class) ? Security::AUTHENTICATION_ERROR : DeprecatedSecurity::AUTHENTICATION_ERROR;
}
}
10 changes: 0 additions & 10 deletions tests/Security/Core/Authentication/Provider/OAuthProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,6 @@ public function testAuthenticatesToken(): void
$this->assertNotNull($token->getUser());
$this->assertInstanceOf(OAuthToken::class, $token);

// @deprecated since Symfony 5.4
if (method_exists($token, 'isAuthenticated')) {
$this->assertTrue($token->isAuthenticated());
}

$this->assertEquals($expectedToken, $token->getRawToken());
$this->assertEquals($expectedToken['access_token'], $token->getAccessToken());
$this->assertEquals($expectedToken['refresh_token'], $token->getRefreshToken());
Expand Down Expand Up @@ -255,11 +250,6 @@ public function testTokenRefreshesWhenExpired(bool $authenticated, bool $userKno

$this->assertInstanceOf(OAuthToken::class, $token);

// @deprecated since Symfony 5.4
if (method_exists($token, 'isAuthenticated')) {
$this->assertTrue($token->isAuthenticated());
}

$this->assertEquals($refreshedToken, $token->getRawToken());
$this->assertEquals($refreshedToken['access_token'], $token->getAccessToken());
$this->assertEquals($refreshedToken['refresh_token'], $token->getRefreshToken());
Expand Down
44 changes: 18 additions & 26 deletions tests/Security/Core/User/OAuthUserProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\User;

final class OAuthUserProviderTest extends TestCase
{
Expand All @@ -28,20 +27,23 @@ protected function setUp(): void
$this->provider = new OAuthUserProvider();
}

/**
* @group legacy
*/
public function testLoadUserByUsername(): void
{
$user = $this->provider->loadUserByUsername('asm89');

$this->assertInstanceOf(OAuthUser::class, $user);
$this->assertEquals('asm89', $user->getUserIdentifier());
}

public function testLoadUserByUsernameOrIdentifier(): void
{
if (method_exists($this->provider, 'loadUserByUsername')) {
$user = $this->provider->loadUserByUsername('asm89');

$this->assertInstanceOf(OAuthUser::class, $user);
// @phpstan-ignore-next-line Symfony < 5.4 BC layer
$this->assertEquals('asm89', $user->getUsername());
} else {
$user = $this->provider->loadUserByIdentifier('asm89');

$this->assertInstanceOf(OAuthUser::class, $user);
$this->assertEquals('asm89', $user->getUserIdentifier());
}
$user = $this->provider->loadUserByIdentifier('asm89');

$this->assertInstanceOf(OAuthUser::class, $user);
$this->assertEquals('asm89', $user->getUserIdentifier());
}

public function testRefreshUser(): void
Expand All @@ -54,13 +56,8 @@ public function testRefreshUser(): void

public function testRefreshUserUnsupportedClass(): void
{
if (class_exists(User::class)) {
$user = new User('asm89', 'foo');
$message = 'Unsupported user class "Symfony\\Component\\Security\\Core\\User\\User"';
} else {
$user = new InMemoryUser('asm89', 'foo');
$message = 'Unsupported user class "Symfony\\Component\\Security\\Core\\User\\InMemoryUser"';
}
$user = new InMemoryUser('asm89', 'foo');
$message = 'Unsupported user class "Symfony\\Component\\Security\\Core\\User\\InMemoryUser"';

$this->expectException(UnsupportedUserException::class);
$this->expectExceptionMessage($message);
Expand Down Expand Up @@ -89,11 +86,6 @@ public function testLoadUserByOAuthUserResponse(): void
$user = $this->provider->loadUserByOAuthUserResponse($responseMock);
$this->assertInstanceOf(OAuthUser::class, $user);

if (method_exists($this->provider, 'loadUserByUsername')) {
// @phpstan-ignore-next-line Symfony < 5.4 BC layer
$this->assertEquals('asm89', $user->getUsername());
} else {
$this->assertEquals('asm89', $user->getUserIdentifier());
}
$this->assertEquals('asm89', $user->getUserIdentifier());
}
}
5 changes: 0 additions & 5 deletions tests/Security/Core/User/OAuthUserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,6 @@ public function testGetUsername(): void
$this->assertEquals('other', $user->getUsername());
}

public function testEraseCredentials(): void
{
$this->assertTrue($this->user->eraseCredentials());
}

public function testEquals(): void
{
$otherUser = new OAuthUser('other');
Expand Down
11 changes: 0 additions & 11 deletions tests/Security/Http/Authenticator/OAuthAuthenticatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
Expand Down Expand Up @@ -168,11 +167,6 @@ public function testAuthenticate(): void
$this->assertEquals($resourceOwnerName, $token->getResourceOwnerName());
$this->assertEquals($user, $token->getUser());
$this->assertEquals('refresh_token', $token->getRefreshToken());

// required for compatibility with Symfony 5.4
if (method_exists($token, 'isAuthenticated')) {
$this->assertTrue($token->isAuthenticated());
}
}

public function testOnAuthenticationSuccess(): void
Expand Down Expand Up @@ -418,11 +412,6 @@ private function getUserResponseMock(): UserResponseInterface

private function createUser(): UserInterface
{
if (class_exists(User::class)) {
// @phpstan-ignore-next-line Symfony < 5.4 BC layer
return new User('asm89', 'foo', ['ROLE_USER']);
}

return new InMemoryUser('asm89', 'foo', ['ROLE_USER']);
}

Expand Down