從Cake 2.2開始,您可以將contain
鍵添加到您的身份驗證選項以提取相關數據。由於contain
鍵接受fields
鍵,就可以有限制的領域:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'contain' => array(
'Profile' => array(
'fields' => array('name', 'birthdate')
)
)
)
)
)
);
如果你想改變字段的用戶模型搜索,您可以擴展您使用的認證對象。用戶表通常包含最少量的信息,所以通常不需要這樣做。
不過,我會舉一個例子。我們將在這裏使用FormAuthenticate對象,並使用BaseAuthenticate類中的大部分_findUser
方法代碼。這是Cake的認證系統用來識別用戶的功能。
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class MyFormAuthenticate extends FormAuthenticate {
// overrides BaseAuthenticate::_findUser()
protected function _findUser($username, $password) {
$userModel = $this->settings['userModel'];
list($plugin, $model) = pluginSplit($userModel);
$fields = $this->settings['fields'];
$conditions = array(
$model . '.' . $fields['username'] => $username,
$model . '.' . $fields['password'] => $this->_password($password),
);
if (!empty($this->settings['scope'])) {
$conditions = array_merge($conditions, $this->settings['scope']);
}
$result = ClassRegistry::init($userModel)->find('first', array(
// below is the only line added
'fields' => $this->settings['findFields'],
'conditions' => $conditions,
'recursive' => (int)$this->settings['recursive']
));
if (empty($result) || empty($result[$model])) {
return false;
}
unset($result[$model][$fields['password']]);
return $result[$model];
}
}
然後使用該認證,並通過我們的新的設置:
public $components = array(
'Auth' => array(
'authenticate' => array(
'MyForm' => array(
'findFields' => array('username', 'email'),
'contain' => array(
'Profile' => array(
'fields' => array('name', 'birthdate')
)
)
)
)
)
);
您正在使用什麼版本的蛋糕? – jeremyharris
最新版本,2.2.3。 –