Andreas
Andreas

Reputation: 1261

Check if user is redirected or not in symfony?

I have a route in my symfony project that is restricted, so if I try to go there without being logged on I'm redirected to the login page.

I'd like to distinguish between when I try to go to a restricted area without being logged on, and when I just go to the login page directly.

Any clues of how to do this in symfony?

Update By distinguish I mean some way to check if auser landed on the login page by going to that url directly, or if the user landed on the login page because he tried to access a restricted page.

Upvotes: 4

Views: 4757

Answers (3)

Albert221
Albert221

Reputation: 7182

In addition to hcoat answer, you can do this without creating new URL. You can use query parameter:

secured_area:
            pattern:    ^/
            form_login:
                check_path: /login_check
                login_path: /login?r

And then in your controller's action check for this parameter:

public function loginAction(Request $request)
{
    $redirected = $request->query->has('r');
    // ...
}

Upvotes: 1

hcoat
hcoat

Reputation: 2643

Thomas' solution is a good one. Here is an alternative.

Knowing that and you will only be redirected if not logged-in you can just have your security firewall redirect with an additional parameter.

security.yml

...
secured_area:
            pattern:    ^/
            form_login:
                check_path: /login_check
                login_path: /login/restricted
...

routing.yml

login:
    pattern:  /login
    defaults: { _controller: YourBundle:Default:login }

login:
    pattern:  /login/{restricted}
    defaults: { _controller: YourBundle:Default:login }

controller

public function loginAction($restricted = null)
{
...
Do something with $restricted
...

Now if someone goes to the login page:

yoursite.com/login

everything will be normal and $restricted = null so you know they came directly.

If someone goes to:

yoursite.com/admin

when they are not logged-in they will be redirected to:

yoursite.com/login/restricted

In your controller $restricted will be set and you will know they tried to access a restricted area without authentication.

Of course you can change restricted to what ever would make sense to you.

Upvotes: 6

Thomas Potaire
Thomas Potaire

Reputation: 6276

Did you try $this->get('request')->headers->get('referer') ?

get('referer') will only return an internal and relative path. If you are on test.com and click on a link going to your app get('referer') will return null. So if the user hits a redirect, the next request should have the proper URL.

Otherwise you could create a custom exception listener and catch any AccessDeniedException. When the code catches one you could use the FlashBag to pass values through the redirect.

Upvotes: 4

Related Questions