0
votes

I want to make an aplication where users can login normally and back-end where admins can login.

So far I created this:

routes.php

$prefix = 'admin';

Router::connect(
    "/{$prefix}/:plugin/:controller",
    array('action' => 'index', 'prefix' => $prefix, $prefix => true)
);
Router::connect(
    "/{$prefix}/:plugin/:controller/:action/*",
    array('prefix' => $prefix, $prefix => true)
);
Router::connect(
    "/{$prefix}/:controller",
    array('action' => 'index', 'prefix' => $prefix, $prefix => true)
);
Router::connect(
    "/{$prefix}/:controller/:action/*",
    array('prefix' => $prefix, $prefix => true)
);

AppController:

public $components = array(
    'DebugKit.Toolbar',
    'Session',
    'Auth' => array(
        'loginRedirect' => array(
            'controller' => 'pages',
            'action' => 'display'
        ),
        'logoutRedirect' => array(
            'controller' => 'pages',
            'action' => 'display',
            'home'
        ),
        'authorize' => 'Controller',
        'authError' => 'Access denied! Did you really think that you can access that?'
    )
);

public function isAuthorized($user) {
    // Admin can access every action
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }

    // Default deny
    return false;
}

public function beforeFilter() {
    $this->Auth->allow('display');
    //$this->recordActivity();
    if($this->request->prefix == 'admin'){
        $this->layout = 'admin';
    }   
}

With this when I try to access pages on front-end that needs auth it gives me login() action but when a try to access /admin it redirects me to /users/login.

I want to have two separate login systems with diferrent layouts. One for normal users and one for admin users.

Can anybody help please?

1

1 Answers

2
votes

I don't recommend two login() actions just for the sake of a different view. You can move the if statement from your beforeFilter() to UsersController::login() to set the layout correctly. However, if you do want to proceed with separate actions, set the AuthComponent::loginAction property in AppController::beforeFilter() like:

if($this->request->prefix == 'admin'){
    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'admin_login', 'plugin' => false);
}

where admin_login will be another action that you create in UsersController.

On a side note, I recommend using cake's default prefix routing as mentioned in the book. It is very similar to what you have done but you won't have to manually create the routes. Also, as mentioned in there, to access /admin you will need to define a route like:

Router::connect(
    '/admin',
    array('controller' => 'pages', 'action' => 'index', 'admin' => true)
);