Chỉ cần làm theo điều này trong CakePHP 2.4.1, tôi đã xây dựng giao diện người dùng cho cơ sở dữ liệu cũ có mật khẩu người dùng hiện có được lưu trữ dưới dạng md5 (accountnumber: statictext: password) và cho phép người dùng đăng nhập để sử dụng hệ thống băm đó.
Giải pháp là:
Tạo một ứng dụng tập tin/Controller/Component/Auth/CustomAuthenticate.php với:
<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class CustomAuthenticate extends FormAuthenticate {
protected function _findUser($username, $password = null) {
$userModel = $this->settings['userModel'];
list(, $model) = pluginSplit($userModel);
$fields = $this->settings['fields'];
if (is_array($username)) {
$conditions = $username;
} else {
$conditions = array(
$model . '.' . $fields['username'] => $username
);
}
if (!empty($this->settings['scope'])) {
$conditions = array_merge($conditions, $this->settings['scope']);
}
$result = ClassRegistry::init($userModel)->find('first', array(
'conditions' => $conditions,
'recursive' => $this->settings['recursive'],
'contain' => $this->settings['contain'],
));
if (empty($result[$model])) {
return false;
}
$user = $result[$model];
if ($password) {
if (!(md5($username.":statictext:".$password) === $user[$fields['password']])) {
return false;
}
unset($user[$fields['password']]);
}
unset($result[$model]);
return array_merge($user, $result);
}
}
Các "kéo dài FormAuthenticate" có nghĩa là tập tin này tiếp quản chức năng _findUser nhưng defers để FormAuthenticate cho tất cả các chức năng khác như bình thường. Điều này sau đó được kích hoạt bằng cách chỉnh sửa AppController.php và thêm vào lớp AppController như sau:
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array('controller' => 'accounts', 'action' => 'login'),
'loginRedirect' => array('controller' => 'accounts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
'authenticate' => array (
'Custom' => array(
'userModel' => 'Account',
'fields' => array('username' => 'number'),
)
),
)
);
Đặc biệt lưu ý việc sử dụng khóa mảng liên kết 'Tùy chỉnh'.
Cuối cùng nó là cần thiết để băm mật khẩu khi tạo một người dùng mới, vì vậy với mô hình tập tin (trong trường hợp của tôi Account.php) Tôi nói thêm:
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = md5($this->data[$this->alias]['number'].":statictext:".$this->data[$this->alias]['password']);
}
return true;
}
Các tên tập tin cần phải được CustomFormAuthenticate.php - không CustomFormAuthentication .php –
Cảm ơn, tốt bắt – jesal
@ jesal Tôi biết đây là một chủ đề cũ 5 tháng nhưng bạn sẽ biết cách cấu trúc lớp CustomFormAuthenticate nếu tôi cần sử dụng cryp với email là muối.Rõ ràng, email không thể truy cập tại thời điểm này? Hãy giúp tôi! – rizalp1