Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to control multiple type of user access?

In the past, I simply create a BaseController and check the session to control user to access for some pages

class BaseController extends Phalcon\Mvc\Controller
{
        public function beforeExecuteRoute()
        {
            if(!$this->session->get("user"))
            {
                $this->dispatcher->forward(array(
                    'controller' => 'login',
                    'action' => 'index'
                ));
            }
        }
}

But now the system has many types of users

for example

if $this->session->get("user")->type=='admin'

Then this user can access AdminController

while $this->session->get("user")->type=='manager'

then this user can access ManagerController

I can create many BaseController for different user types, but I think this is not a good solution, can I solve it by using one base controller?



16.9k
Accepted
answer

You don't use a controller to see if an user has access to certain controllers/actions, you use an ACL http://docs.phalconphp.com/en/latest/reference/tutorial-invo.html#providing-an-acl-list

edited Sep '14

My solution to control admin user access is like below.

  • Edit route.php and config.php.
  • Create controllers/admin folder and a new ControllerBase.php.
  • Create views/admin folder and some .volt files.

route.php

...
$router->add('/admin/', [
    'namespace' => $config->namespace->controllersAdmin,
    'controller' => 'index',
    'action' = 'index',
]);

$router->add('/admin/:controller', [
    'namespace' => $config->namespace->controllersAdmin,
    'controller' => 1,
    'action' => 'index',
]);

$router->add('/admin/:controller/:action', [
    'namespace' => $config->namespace->controllersAdmin,
    'controller' => 1,
    'action' => 2,
]);
...

config.php

return new \Phalcon\Config([
    'application' => [
        'controllersDir'        => __DIR__ . '/../../app/controllers/',
        'controllersAdminDir'   => __DIR__ . '/../../app/controllers/admin/',
        ...
        'baseUri'               => '/base/',
        'baseUriAdmin'          => '/base/admin/',
    ],
    ...

app/controllers/admin/ControllerBase.php

<?php

namespace My\Namespace\Controllers\Admin;

...

class ControllerBase extends Controller
{

    public function beforeExecuteRoute($dispatcher)
    {
        $this->view->setViewsDir($this->view->getViewsDir() .'admin');
        $this->url->setBaseUri($this->config->application->baseUriAdmin);

        // Check IP address, ACL or session here.
        ...
    }
    ...
}

app/controllers/admin/MyController.php

namespace My\Namespace\Controllers\Admin;

...

class MyController extends ControllerBase
{
    ...
}