How to check for session in each controller. I want to check session on controller level not in the functions inside the controller. If session is not set, it will redirect to login page.
|
Mar '14 |
5 |
2535 |
0 |
Hi, if you want to check session for every controllers you can do that in ControllerBase initialize() function (assuming that all of your controllers extends from ControllerBase). Otherwise, for each controller in wich you want a session check, put that in each controller initialize() function.
use Phalcon\Mvc\Controller;
class ControllerBase extends Controller
{
protected function initialize()
{
if(!$session->has('auth')) {
// assuming that auth param is initialized after login
$this->flash->error('Please login into the application');
// then redirect to your login page
}
}
For automatic process like ACL check I prefer to use beforeExecuteRoute instead of initialize
public function beforeExecuteRoute(Dispatcher $dispatcher)
{
// ACL check or ...
}
@a6oozar +1
Here is my implementation in simple app without ACL:
abstract class SecureController extends Controller
{
public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher)
{
if (false === $this->auth->isLogged()) {
if ($this->auth->hasRememberMe()) {
$this->auth->loginWithRememberMe();
} else {
throw new AccessDeniedException();
}
}
}
}
you can change throw exception to redirect to login page
You should add Session Adapter to your applicaion DI for example for File adapter: otherwise it can`t be accessible in your MVC controllers by default.
// Session
$di->setShared('session', function() {
$session = new Phalcon\Session\Adapter\Files();
$session->start();
return $session;
});