Gildas
Gildas

Reputation: 1158

Symfony2: How to redirect on a specific page when user is not allowed to access a url pattern

I'm trying to figure out how to redirect to a certain page (which in my case is the payment page) a user that hasn't a valid subscription running.

I know I could do that by putting a isGranted check in all my actions, but I don't like this solution as it seems to be a big waste of time given the amount of actions I have.

I've looked on the firewall.access_denied_url parameters, but I don't want to link AccessDenied to the payment page because, for example, admin page access is denied to any user that hasn't the ROLE_ADMIN, and being redirected to the payment page doesn't make any sense.

I already have a voter that check if a user is either valid or not and grant access in that case, but how could I manage to use this voter when a user tries to reach a certain pattern and redirect him/her when the access is denied?

Thanks in advance!

Upvotes: 6

Views: 4900

Answers (2)

dilionnele
dilionnele

Reputation: 61

In app/config/security.yml add under security:

access_denied_url: /foo/error403

Symfony will then redirect all pages which user cannot access to /foo/error403 page.

Upvotes: 6

Hakan Deryal
Hakan Deryal

Reputation: 2903

You can use JMSAopBundle.

From documentation:

This bundle adds AOP capabilities to Symfony2.

If you haven't heard of AOP yet, it basically allows you to separate a cross-cutting concern (for example, security checks) into a dedicated class, and not having to repeat that code in all places where it is needed.

In other words, this allows you to execute custom code before, and after the invocation of certain methods in your service layer, or your controllers. You can also choose to skip the invocation of the original method, or throw exceptions.

Upvotes: 1

Related Questions