Skip to content

Commit

Permalink
update to symfony 6 - WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
jwong-dayspring committed Feb 17, 2024
1 parent 7787bc8 commit 5e6767b
Show file tree
Hide file tree
Showing 9 changed files with 66 additions and 61 deletions.
38 changes: 18 additions & 20 deletions Controller/ForgotResetController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
use Dayspring\LoginBundle\Entity\ChangePasswordEntity;
use Dayspring\LoginBundle\Form\Type\ChangePasswordType;
use Dayspring\LoginBundle\Form\Type\ResetPasswordType;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
Expand All @@ -28,22 +28,22 @@ class ForgotResetController extends AbstractController
protected $authenticationManager;
protected $session;
protected $tokenStorage;
protected $userPasswordEncoder;
protected $userPasswordHasher;
protected $mailer;

public function __construct(
AuthenticationManagerInterface $authenticationManager,
// AuthenticationManagerInterface $authenticationManager,
UserProviderInterface $userProvider,
SessionInterface $session,
MailerInterface $mailer,
TokenStorageInterface $tokenStorage,
UserPasswordEncoderInterface $userPasswordEncoder
UserPasswordHasherInterface $userPasswordHasher
) {
$this->authenticationManager = $authenticationManager;
// $this->authenticationManager = $authenticationManager;
$this->mailer = $mailer;
$this->session = $session;
$this->tokenStorage = $tokenStorage;
$this->userPasswordEncoder = $userPasswordEncoder;
$this->userPasswordHasher = $userPasswordHasher;
$this->userProvider = $userProvider;
}

Expand Down Expand Up @@ -91,7 +91,7 @@ public function forgotPasswordAction(Request $request)

$this->mailer->send($message);
}
} catch (UsernameNotFoundException $e) {
} catch (UserNotFoundException $e) {
// do not throw an error for UsernameNotFoundException
}

Expand Down Expand Up @@ -119,8 +119,7 @@ public function resetPasswordAction(Request $request, $resetToken)
if ($form->isValid()) {
$data = $form->getData();

$encoded = $this->userPasswordEncoder->encodePassword($user, $data->getPassword());
// $encoded = $this->userPasswordEncoder->hashPassword($user, $data->getPassword());
$encoded = $this->userPasswordHasher->hashPassword($user, $data->getPassword());
$user->setPassword($encoded);
$user->save();

Expand Down Expand Up @@ -153,19 +152,18 @@ public function changePasswordAction(Request $request)
if ($form->isValid()) {
$data = $form->getData();

$encoded = $this->userPasswordEncoder->encodePassword($currentUser, $data->getNewPassword());
// $encoded = $this->userPasswordEncoder->hashPassword($currentUser, $data->getNewPassword());
$encoded = $this->userPasswordHasher->hashPassword($currentUser, $data->getNewPassword());
$currentUser->setPassword($encoded);
$currentUser->save();

$token = new UsernamePasswordToken(
$currentUser,
$data->getNewPassword(),
"secured_area",
$currentUser->getRoles()
);
$token = $this->authenticationManager->authenticate($token);
$this->tokenStorage->setToken($token);
// $token = new UsernamePasswordToken(
// $currentUser,
// $data->getNewPassword(),
// "secured_area",
// $currentUser->getRoles()
// );
// $token = $this->authenticationManager->authenticate($token);
// $this->tokenStorage->setToken($token);

$this->session->getFlashBag()->add('success', 'New password has been saved.');

Expand Down
9 changes: 5 additions & 4 deletions Model/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
use DateTime;
use Dayspring\LoginBundle\Model\om\BaseUser;
use PropelPDO;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

class User extends BaseUser implements UserInterface
class User extends BaseUser implements UserInterface, PasswordAuthenticatedUserInterface
{
/**
* User constructor.
Expand All @@ -29,7 +30,7 @@ public function getUsername()
return $this->getEmail();
}

public function getUserIdentifier()
public function getUserIdentifier(): string
{
return $this->getEmail();
}
Expand Down Expand Up @@ -71,9 +72,9 @@ public function getEmail()
* groups={"password"}
* )
*/
public function getPassword()
public function getPassword(): string
{
return parent::getPassword();
return parent::getPassword() ?? '';
}

public function generateResetToken()
Expand Down
3 changes: 2 additions & 1 deletion Security/AuthenticationSuccessHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Dayspring\LoginBundle\Model\User;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;

Expand All @@ -13,7 +14,7 @@ class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler
/**
* {@inheritdoc}
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
public function onAuthenticationSuccess(Request $request, TokenInterface $token): Response
{
/** @var User $user */
$user = $token->getUser();
Expand Down
12 changes: 6 additions & 6 deletions Security/User/DayspringUserProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use Dayspring\LoginBundle\Model\User;
use Dayspring\LoginBundle\Model\UserQuery;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

Expand All @@ -20,15 +20,15 @@ public function loadUserByUsername($username)
* @param $username
* @return User
*/
public function loadUserByIdentifier($username)
public function loadUserByIdentifier(string $identifier): UserInterface
{
$user = UserQuery::create()
->filterByEmail($username)
->filterByEmail($identifier)
->findOne();

if ($user == null) {
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
throw new UserNotFoundException(
sprintf('Username "%s" does not exist.', $identifier)
);
} else {
$user->reload();
Expand All @@ -41,7 +41,7 @@ public function loadUserByIdentifier($username)
* @param UserInterface $user
* @return User
*/
public function refreshUser(UserInterface $user): \Symfony\Component\Security\Core\User\UserInterface
public function refreshUser(UserInterface $user): UserInterface
{
if (!$user instanceof User) {
throw new UnsupportedUserException(
Expand Down
14 changes: 8 additions & 6 deletions Tests/Controller/ForgotResetControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
use Dayspring\LoginBundle\Model\UserQuery;
use Dayspring\LoginBundle\Tests\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use function var_dump;

class ForgotResetControllerTest extends WebTestCase
{
Expand Down Expand Up @@ -59,15 +61,15 @@ public function testForgotPassword()

public function testForgotPasswordDeactiveUser()
{
$encoder = static::$kernel->getContainer()->get('security.password_encoder');
$encoder = static::getContainer()->get(UserPasswordHasherInterface::class);

$user = new User();
$user
->setEmail("[email protected]")
->setPassword("password")
->setIsActive(false);

$encoded = $encoder->encodePassword($user, 'password');
$encoded = $encoder->hashPassword($user, 'password');
$user
->setPassword($encoded)
->save();
Expand Down Expand Up @@ -192,13 +194,13 @@ public function testChangePasswordNotLoggedIn()

public function testChangePassword()
{
$encoder = static::$kernel->getContainer()->get('security.password_encoder');
$encoder = static::getContainer()->get(UserPasswordHasherInterface::class);

$securityRole = new SecurityRole();
$securityRole->setRoleName('ROLE');

$user = new User();
$encoded = $encoder->encodePassword($user, 'password');
$encoded = $encoder->hashPassword($user, 'password');

$user
->addSecurityRole($securityRole)
Expand Down Expand Up @@ -240,13 +242,13 @@ public function testChangePassword()

public function testChangePasswordNoMatch()
{
$encoder = static::$kernel->getContainer()->get('security.password_encoder');
$encoder = static::getContainer()->get(UserPasswordHasherInterface::class);

$securityRole = new SecurityRole();
$securityRole->setRoleName('ROLE');

$user = new User();
$encoded = $encoder->encodePassword($user, 'password');
$encoded = $encoder->hashPassword($user, 'password');

$user
->addSecurityRole($securityRole)
Expand Down
15 changes: 8 additions & 7 deletions Tests/Controller/UserAccountControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class UserAccountControllerTest extends WebTestCase
{
Expand All @@ -23,7 +24,7 @@ protected function setUp(): void
parent::setUp();

$application = new Application(static::$kernel);
$application->add(new FixturesLoadCommand(static::$kernel->getContainer()));
$application->add(new FixturesLoadCommand(static::getContainer()));

$command = $application->find('propel:fixtures:load');
$commandTester = new CommandTester($command);
Expand All @@ -39,11 +40,11 @@ protected function setUp(): void

protected function createUserAndLogin()
{
$encoder = static::$kernel->getContainer()->get('security.password_encoder');
$encoder = static::getContainer()->get(UserPasswordHasherInterface::class);

$user = new User();
$user->setEmail(sprintf("test+%[email protected]", microtime()));
$encoded = $encoder->encodePassword($user, 'password');
$encoded = $encoder->hashPassword($user, 'password');
$user->setPassword($encoded);
$user->addSecurityRole(SecurityRoleQuery::create()->filterByRoleName("ROLE_User")->findOneOrCreate());
$user->save();
Expand All @@ -70,15 +71,15 @@ protected function loginAdminUser()

public function testInactiveUser()
{
$encoder = static::$kernel->getContainer()->get('security.password_encoder');
$encoder = static::getContainer()->get(UserPasswordHasherInterface::class);

$user = new User();
$user
->setEmail("[email protected]")
->setPassword("password")
->setIsActive(false);

$encoded = $encoder->encodePassword($user, 'password');
$encoded = $encoder->hashPassword($user, 'password');
$user
->setPassword($encoded)
->save();
Expand All @@ -99,11 +100,11 @@ public function testInactiveUser()

public function testLastLoginDate()
{
$encoder = static::$kernel->getContainer()->get('security.password_encoder');
$encoder = static::getContainer()->get(UserPasswordHasherInterface::class);

$user = new User();
$user->setEmail(sprintf("test+%[email protected]", microtime()));
$encoded = $encoder->encodePassword($user, 'password');
$encoded = $encoder->hashPassword($user, 'password');
$user->setPassword($encoded);
$user->addSecurityRole(SecurityRoleQuery::create()->filterByRoleName("ROLE_User")->findOneOrCreate());
$user->save();
Expand Down
7 changes: 4 additions & 3 deletions Tests/Resources/config/security.yml
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
enable_authenticator_manager: true

# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
dayspring:
id: dayspring_login.user_provider

# http://symfony.com/doc/current/book/security.html#encoding-the-user-s-password
encoders:
password_hashers:
Dayspring\LoginBundle\Model\User:
algorithm: bcrypt
cost: 12
Expand All @@ -35,8 +36,8 @@ security:
logout:
path: _logout
target: /
anonymous: ~
# anonymous: ~

main:
anonymous: ~
# anonymous: ~
#logout_on_user_change: true
6 changes: 3 additions & 3 deletions Tests/Security/User/DayspringUserProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;

class DayspringUserProviderTest extends WebTestCase
Expand Down Expand Up @@ -70,7 +70,7 @@ public function testSupportsClass()

public function testLoadUserByUsernameFailure()
{
$this->expectException(UsernameNotFoundException::class);
$this->expectException(UserNotFoundException::class);
$this->userProvider->loadUserByIdentifier('[email protected]');
}

Expand Down Expand Up @@ -104,7 +104,7 @@ public function getSalt()
{
}

public function getUserIdentifier()
public function getUserIdentifier(): string
{
}

Expand Down
23 changes: 12 additions & 11 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@
],
"require": {
"php": ">=7.4",
"symfony/framework-bundle": "^4.4.23|^5.0",
"symfony/mailer": "^4.0|^5.0",
"symfony/security-bundle": "^4.0|^5.0",
"symfony/twig-bundle": "^4.4.19|^5.0",
"symfony/yaml": "^4.0|^5.0",
"symfony/form": "^4.0|^5.0",
"symfony/validator": "^4.0|^5.0",
"symfony/console": "^4.0|^5.0",
"symfony/routing": "^4.0|^5.0",
"symfony/asset": "^4.0|^5.0",
"symfony/expression-language": "^4.0|^5.0",
"symfony/framework-bundle": "^4.4.23|^5.0|^6.0",
"symfony/mailer": "^4.0|^5.0|^6.0",
"symfony/security-bundle": "^5.3|^6.0",
"symfony/twig-bundle": "^4.4.19|^5.0|^6.0",
"symfony/yaml": "^4.0|^5.0|^6.0",
"symfony/form": "^4.0|^5.0|^6.0",
"symfony/validator": "^4.0|^5.0|^6.0",
"symfony/console": "^4.0|^5.0|^6.0",
"symfony/routing": "^4.0|^5.0|^6.0",
"symfony/asset": "^4.0|^5.0|^6.0",
"symfony/expression-language": "^4.0|^5.0|^6.0",
"symfony/monolog-bundle": "^3.6.0",
"sensio/framework-extra-bundle": "^5.0.1",
"dayspring-tech/propel-bundle": "^1.8.6",
Expand All @@ -48,6 +48,7 @@
"doctrine/annotations": "^1.12.1"
},
"require-dev": {
"symfony/framework-bundle": "^5.3|^6.0",
"symfony/phpunit-bridge": "^5.0|^6.0",
"phpunit/phpunit": "^8.5.23|^9.0",
"symfony/browser-kit": "^4.0|^5.0",
Expand Down

0 comments on commit 5e6767b

Please sign in to comment.