We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Session Redirect

How can I properly redirect to my login page from base controller if there is no session set?

This is what I have now in my Base.php file and I get too many redirects error.

My PHP v7.3.10 and Phalcon v4.0.0-RC1

function initialize() {
  if (!$this->session->has('auth')) {
    $this->response->redirect('/login');
  }
}
edited Oct '19

Hi there,

So if the user tried to access a protected controller it WILL redirect to login controller...

so far so good...

when the request is to access the login controller, since it does not has 'auth' it will redirect again!

    if (!$this->session->has('auth') && strtolower($dispatcher->getControllerName()) != 'login') {
                $this->response->redirect("/login");
                return false;
     }

verify it it does not have 'auth' and the "current" controller is not the login controller

Cheers,



9.3k
Accepted
answer

Because I check my sesson inside Base controller's initialize, I needed to use getActionName instead of getControllerName but it worked. Thank you! Now if users are not logged in, they are redirected to login back by default.

  $name = $this->dispatcher->getActionName();
  if (!$this->session->has('auth') AND $name !== 'login') {
    $this->response->redirect('/login');
  }
edited Oct '19

Is there anything else I need here, to make sure its properly secured, maybe something like view->disable()?

Also I've seen others do return $this->response->redirect why use return for redirects? Thanks!

https://docs.phalcon.io/3.4/en/views#disabling-the-view

Is there anything else I need here, to make sure its properly secured, maybe something like view->disable()?

Also I've seen others do return $this->response->redirect why use return for redirects? Thanks!