Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user is redirected or not in symfony?

Tags:

php

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.

like image 799
Andreas Avatar asked Sep 01 '25 09:09

Andreas


2 Answers

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.

like image 179
hcoat Avatar answered Sep 03 '25 23:09

hcoat


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.

like image 37
Thomas Potaire Avatar answered Sep 03 '25 22:09

Thomas Potaire