Solo per seguire questo in CakePHP 2.4.1, stavo creando un front-end per un database legacy con password utente esistenti memorizzate come md5 (numero di account: statictext: password) e per consentire agli utenti di accedere di cui avevamo bisogno usare anche quel sistema di hashing.
La soluzione era:
Creare un file app/Controller/Component/Auth/CustomAuthenticate.php con:
<?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);
}
}
Il "si estende FormAuthenticate" significa che questo file assume la funzione _findUser ma rimanda a FormAuthenticate per tutte le altre funzioni normalmente. Questo viene poi attivato modificando AppController.php e aggiungendo alla classe AppController qualcosa di simile:
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'),
)
),
)
);
In particolare nota l'uso del tasto array associativo 'Custom'.
Infine è necessario hash della password quando si crea un nuovo utente, in modo da file del modello (nel mio caso Account.php) ho aggiunto:
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;
}
Il nome del file deve essere CustomFormAuthenticate.php - non CustomFormAuthentication .php –
Grazie, buona cattura – jesal
@jesal So che questo è un thread di 5 mesi ma sapresti come strutturare la classe CustomFormAuthenticate se ho bisogno di usare cryp con email come salt.Ovviamente, la posta elettronica non è accessibile a questo punto? Per favore aiuto! – rizalp1