Symfony 8.2 New Published on

Validating according to the user's permissions

is_granted() and current_user() in the When and Expression constraints: the rules that depend on the logged-in user leave the controller.

Topics covered: ValidatorSecurity

New in Symfony 8.2 (in development). The security functions of the expression language (is_granted(), is_authenticated(), is_fully_authenticated(), is_remember_me()) are now available in the Validator's When and Expression constraints. A new function joins them: current_user(), which returns the logged-in user, or null.

Until now, a validation rule that depended on the logged-in user ended up in a custom validator or, more often, in the controller.

Before

if ($form->isSubmitted()) {
    if (!$this->isGranted('ROLE_EDITOR') && mb_strlen((string) $invitation->message) > 280) {
        $form->get('message')->addError(new FormError('This message is too long: 280 characters at most.'));
    }
}

Since Symfony 8.2

#[Assert\When(
    expression: 'not is_granted("ROLE_EDITOR")',
    constraints: [new Assert\Length(max: 280)],
)]
public ?string $message = null;

The rule lives on the DTO: another form or an API that validates the same Invitation applies it too.

Beware outside a request

These functions read the user of the current request. Validate the same object from a console command or a Messenger worker and they throw an exception rather than answer "nobody is logged in". That's on purpose: otherwise a constraint guarded by When would be skipped silently. So keep them for rules tied to the user, and keep business invariants in constraints that hold everywhere.

Your task

In this back office, InvitationController applies two rules by hand:

  • the welcome message must fit within 280 characters, except for editors (ROLE_EDITOR);
  • you can't invite yourself.

Move them to the Invitation DTO, with #[Assert\When] and is_granted() for the first, #[Assert\Expression] and current_user() for the second, keeping the two error messages shown today. Then slim down the controller.

To try it in the preview, log in with ada@example.com / lovelace, then with the editor grace@example.com / hopper.

Where the feature comes from: the original pull request.