Domanda

Ho un database esistente Sto cercando di mettere un app torta in cima. La vecchia applicazione utilizzata crypt () in Perl per hash delle password. Ho bisogno di fare lo stesso in app PHP.

Dove è il posto giusto per fare questo cambiamento in un CakePHP app norma? E cosa sarebbe un tale cambiamento simile?

È stato utile?

Soluzione

I got it lavoro ...

qui è la mia AppController:

class AppController extends Controller {
    var $components = array('Auth');

    function beforeFilter() {
        // this is part of cake that serves up static pages, it should be authorized by default
        $this->Auth->allow('display');
        // tell cake to look on the user model itself for the password hashing function
        $this->Auth->authenticate = ClassRegistry::init('User');
        // tell cake where our credentials are on the User entity
        $this->Auth->fields = array(
           'username' => 'user',
           'password' => 'pass',
        );
        // this is where we want to go after a login... we'll want to make this dynamic at some point
        $this->Auth->loginRedirect = array('controller'=>'users', 'action'=>'index');
    }
}

Poi ecco l'utente:

<?php
class User extends AppModel {
    var $name = 'User';

    // this is used by the auth component to turn the password into its hash before comparing with the DB
    function hashPasswords($data) {
         $data['User']['pass'] = crypt($data['User']['pass'], substr($data['User']['user'], 0, 2));
         return $data;
    }
}
?>

Tutto il resto è normale, credo.

Ecco una buona risorsa: http : //teknoid.wordpress.com/2008/10/08/demystifying-auth-features-in-cakephp-12/

Altri suggerimenti

In realtà il metodo sopra descritto da DANB non ha funzionato per me in CakePHP 2.x Invece ho finito per creare un componente di autenticazione personalizzato per bypassare l'algoritmo di hash standard:

/app/Controller/Component/Auth/CustomFormAuthenticate.php

<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');

class CustomFormAuthenticate extends FormAuthenticate {

    protected function _password($password) {
        return self::hash($password);
    }

    public static function hash($password) {
        // Manipulate $password, hash, custom hash, whatever
        return $password;
    }
}

... e quindi utilizzare tale nel mio controller ...

public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'CustomForm' => array(
                'userModel' => 'Admin'
            )
        )
    )
);

Questo ultimo blocco può anche essere messo all'interno del beforeFilter il metodo del AppController . Nel mio caso ho solo scelto di metterlo in particolare in un controller in cui stavo per utilizzare l'autenticazione personalizzato con un modello di utente diverso.

Basta seguire questo in CakePHP 2.4.1, stavo costruendo un front-end per un database legacy che aveva le password degli utenti esistenti memorizzati come md5 (accountNumber: StaticText: password), e per consentire agli utenti di accedere avevamo bisogno di utilizzare tale sistema di hashing pure.

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 rimette alla FormAuthenticate per tutte le altre funzioni come normale. 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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top