2014-02-12 33 views
0

我想做一个应用程序,用户可以正常登录和管理员可以登录的后端。Cakephp管理员和用户登录单独

到目前为止,我创造了这个:

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'; 
    } 
} 

有了这个,当我尝试AUTH它使访问在前端需要的网页我登录()的行动,但当试图访问/管理它重定向到/用户/登录。

我想拥有两个不同布局的独立登录系统。一个用于普通用户,另一个用于管理员用户。

任何人都可以帮忙吗?

回答

2

我不建议两个login()行动只是为了不同的看法。您可以将if语句从beforeFilter()移至UsersController::login()以正确设置布局。但是,如果你想用不同的动作来进行,在AppController::beforeFilter()像设置AuthComponent::loginAction属性:

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

其中admin_login将是您在UsersController创建另一个动作。

在附注中,我建议使用在book中提到的cake的默认前缀路由。这与您所做的非常相似,但您不必手动创建路线。另外,正如在那里提到的,要访问/管理员,您需要定义一条路线,如:

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