redirect inside beforeExecuteRoute

Hi everyone,

I'm trying to redirect an user if he is not connected using this code:

public function beforeExecuteRoute()
    {
        $allowedNonConnectedUrls = ['user/login'];
        $currentURL = $this->dispatcher->getControllerName() . "/" . $this->dispatcher->getActionName();
        if (!$this->session->has("user") && !in_array($currentURL, $allowedNonConnectedUrls)) {
            $this->flashSession->error("You must be connected to access this page.");
            $this->dispatcher->setReturnedValue($this->response->redirect("user/login"));
            return false;
        }
        return true;
    }

Example: I'm a non-connected user, and I go to /backend/user/logout. As i'm not connected, I should be redirected to /backend/user/login.

The problem is that, sometimes, the URL is called 2 times before redirect properly:

192.168.99.1 - - [04/Feb/2017:17:07:20 +0000] "GET /backend/user/logout HTTP/1.1" 302 5 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
192.168.99.1 - - [04/Feb/2017:17:07:20 +0000] "GET /backend/user/logout HTTP/1.1" 302 5 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
192.168.99.1 - - [04/Feb/2017:17:07:20 +0000] "GET /backend/user/login HTTP/1.1" 200 751 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"

Sometimes the redirection works the first time, and sometimes up to 3 calls are made one my initial URL. As i'm using flashSession, the error messages are displayed multiple times as well...

I tried multiple things:

// not working
return $this->response->redirect("user/login");
// not working
$this->response->redirect("user/login");
$this->response->send();
// not working
$this->response->redirect("user/login");
$this->response->send();
return false;
// not working
$this->response->redirect("user/login");
return false;

Do you have an idea why it's doing this and how to correct it? (I prefer using redirect than forward BTW.)

Thank you for any help !

PS: Sorry any English mistakes.



30.0k
edited Feb '17

Hi,

check your $allowedNonConnectedUrls array.

Are "/backend/user/logout" or "/backend/user/login" in $allowedNonConnectedUrls array or not ?

edit: okay, it's shown in your code ! My mistake.

Strange, because

return $this->response->redirect("user/login");

should work