假设如下:
可以App/Controller/Component/Auth/MyAuthenticate.php
下创建新Authenticate
组件:
<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class MyAuthenticate extends FormAuthenticate {
public function authenticate(CakeRequest $request, CakeResponse $response) {
$username = $request->data['login'] ;
$password = $request->data['password'] ;
App::import('Model', 'User') ;
$userModel = new User() ;
/* Try to authenticate as a user... */
$user = $userModel->find('first', array(
'conditions' => array(
'idcard' => $username,
'password' => User::hashPassword($password) ;
)
)) ;
if ($user) {
$user = $user['User'] ; // Get only useful info
$user['type'] = 'user'; // Save user type
return $user ;
}
/* Same thing for admin. */
App::import('Model', 'Admin') ;
$adminModel = new Admin() ;
$user = $adminModel->find('first', array(
'conditions' => array(
'login' => $username,
'password' => Admin::hashPassword($password) ;
)
)) ;
if ($user) {
$user = $user['Admin'] ; // Get only useful info
$user['type'] = 'admin'; // Save user type
return $user ;
}
return null ;
}
};
你只需要确保,一个管理员不能被认证为用户,并扭转。
在你AppController
:
public $components = array(
'Auth' => array(
'authenticate' => array('My'), // The prefix in front of your component
'loginAction' => array(/* ... */),
'loginRedirect' => array(/* ... */),
'logoutRedirect' => array(/* ... */),
'authError' => "...",
'authorize' => 'Controller'
)
) ;
你的登录操作是一样的,对正常表:
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
else {
$this->request->data['password'] = "" ;
$this->Session->setFlash('Invalid login/id or password.');
}
}
}
然后,在beforeFilter
或isAuthorized
您可以检查$this->Auth->user('type');
。例如,在AppController中:
public function isAuthorized() {
/* Assuming you keep CakePHP convention where action starting with admin_ set admin params. */
if(isset($this->params['admin'])) {
return $this->Auth->user('type') == 'admin' ;
}
return true ;
}
或者,如果您希望禁用非管理员用户访问在AdminController
所有行动,使用beforeFilter
:
class AdminController extends AppController {
public function beforeFilter() {
if (!$this->Auth->loggedIn()) {
$this->Session->setFlash('You need to be logged to access this page.');
$this->redirect(/* Login url. */) ;
return ;
}
if ($this->Auth->user('type') != 'admin') {
$this->Session->setFlash('You need to be admin to access this page.');
$this->redirect(/* Somewhere... */) ;
return ;
}
return parent::beforeFilter() ;
}
}
这通常是已经被设计失败。尝试将所有用户保留在同一个表中 - 并通过角色区分它们。 而且应该总是只有一个登录页面。 保持简单。 – mark
由于外键约束,我无法将所有用户保留在同一张桌子上,例如: 员工属于某个部门,而管理员不属于任何位置。当然,用户表将会有一个指向部门表的外键。如果我想创建一个管理员帐户,我不能只在department_id上放置任何内容或为null。这只是其中一个例子。我认为设计不失败! – codeless
@codeless为什么不把null放在department_id上?此外,还有其他一些方法可以设计数据库,例如为所有用户共用的数据(例如,登录名和密码)提供用户表,然后拥有与您关联的管理表和常规用户表用户表中包含管理员或常规用户唯一的字段。 – Kai