Skip to content

Commit

Permalink
minor #1404 cleanup: use roles constants (COil)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the main branch.

Discussion
----------

cleanup: use roles constants

Before we had to hard-code roles strings:

```
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

class PostController extends Controller
{
    /**
     * `@IsGranted`("ROLE_ADMIN")
     *
     * or use `@Security` for more flexibility:
     *
     * `@Security`("is_granted('ROLE_ADMIN') and is_granted('ROLE_FRIENDLY_USER')")
     */
    public function index()
    {
        // ...
    }
}
```

But with attributes, can use constants. I find this cleaner. I have already used this on several projects and I didn't find drawbacks.

Commits
-------

f057af8 cleanup: use roles constants
  • Loading branch information
javiereguiluz committed Mar 16, 2023
2 parents ee044c7 + f057af8 commit 04c1798
Show file tree
Hide file tree
Showing 7 changed files with 20 additions and 13 deletions.
12 changes: 6 additions & 6 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions config/packages/security.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ security:
# additional security lives in the controllers
- { path: '^/(%app_locales%)/admin', roles: ROLE_ADMIN }

# The ROLE_ADMIN role inherits from the ROLE_USER role
role_hierarchy:
ROLE_ADMIN: ROLE_USER

Expand Down
2 changes: 1 addition & 1 deletion src/Command/AddUserCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$user->setFullName($fullName);
$user->setUsername($username);
$user->setEmail($email);
$user->setRoles([$isAdmin ? 'ROLE_ADMIN' : 'ROLE_USER']);
$user->setRoles([$isAdmin ? User::ROLE_ADMIN : User::ROLE_USER]);

// See https://symfony.com/doc/5.4/security.html#registering-the-user-hashing-passwords
$hashedPassword = $this->passwordHasher->hashPassword($user, $plainPassword);
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/Admin/BlogController.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
#[Route('/admin/post')]
#[IsGranted('ROLE_ADMIN')]
#[IsGranted(User::ROLE_ADMIN)]
class BlogController extends AbstractController
{
/**
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
*
* @author Romain Monteil <monteil.romain@gmail.com>
*/
#[Route('/profile'), IsGranted('ROLE_USER')]
#[Route('/profile'), IsGranted(User::ROLE_USER)]
class UserController extends AbstractController
{
#[Route('/edit', name: 'user_edit', methods: ['GET', 'POST'])]
Expand Down
6 changes: 3 additions & 3 deletions src/DataFixtures/AppFixtures.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ private function getUserData(): array
{
return [
// $userData = [$fullname, $username, $password, $email, $roles];
['Jane Doe', 'jane_admin', 'kitten', 'jane_admin@symfony.com', ['ROLE_ADMIN']],
['Tom Doe', 'tom_admin', 'kitten', 'tom_admin@symfony.com', ['ROLE_ADMIN']],
['John Doe', 'john_user', 'kitten', 'john_user@symfony.com', ['ROLE_USER']],
['Jane Doe', 'jane_admin', 'kitten', 'jane_admin@symfony.com', [User::ROLE_ADMIN]],
['Tom Doe', 'tom_admin', 'kitten', 'tom_admin@symfony.com', [User::ROLE_ADMIN]],
['John Doe', 'john_user', 'kitten', 'john_user@symfony.com', [User::ROLE_USER]],
];
}

Expand Down
8 changes: 7 additions & 1 deletion src/Entity/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@
#[ORM\Table(name: 'symfony_demo_user')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
// We can use constants for roles to find usages all over the application rather
// than doing a full-text search on the "ROLE_" string.
// It also prevents from making typo errors.
final public const ROLE_USER = 'ROLE_USER';
final public const ROLE_ADMIN = 'ROLE_ADMIN';

#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: Types::INTEGER)]
Expand Down Expand Up @@ -118,7 +124,7 @@ public function getRoles(): array

// guarantees that a user always has at least one role for security
if (empty($roles)) {
$roles[] = 'ROLE_USER';
$roles[] = self::ROLE_USER;
}

return array_unique($roles);
Expand Down

0 comments on commit 04c1798

Please sign in to comment.