Search code examples
phpzend-frameworkzend-framework2zfcuser

how to exclude some routes when user is not logged in zfcuser?


So, i am new in Zend Framework, i installed ZfcUser and i want when the user is not logged to didn't access to some routes for example : /blog/article/add,

actually i use <?php if($this->zfcUserIdentity()) :?> to check if the user is logged but how can i redirect the user to my login route/user if is try to access to /blog/article/add, so plz if someone has any idea i will be very appreciative :)


Solution

  • Simple Way:

    in controller:

    if (!$this->zfcUserAuthentication()->hasIdentity()) {
        return $this->redirect()->toRoute('route_to_login',array('param' => $param));
    }
    

    Some more: (after auth zfcuset will redirect you to previous controller)

    in module.config.php

    'controllers' => array(
        'invokables' => array(
            'zfcuser' => 'Application\Controller\UserController',
        ),
    ...
    ),
    

    next copy file vendor\zf-commons\zfc-user\src\ZfcUser\Controller\UserController.php to module Application (same folder as in module.config.php)

    delete all function except authenticateAction add: use Zend\Session\Container; and change return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute()); to

    $redirect_session = new Container('redirect');
            $redirect = $redirect_session->redirect;
            if($redirect!='')
            {
                unset($_SESSION['redirect']);
                return $this->redirect()->toRoute($redirect, array('lang' => $lang));
            }
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute(),array('param' => $param));
    

    and at last add in controller

    use Zend\Session\Container;
    ...
    if (!$this->zfcUserAuthentication()->hasIdentity()) {
                $redirect_session = new Container('redirect');
                $redirect_session->redirect = 'route_to_this_controller_action';
                return $this->redirect()->toRoute('route_to_login',array('param' => $param));
            }