Search code examples
passwordscakephp-3.0transplant

How to migrate my cakephp2 project to cakephp3?


I want to migrate my cakephp2 project to cakephp3. I must retain the user's information. How to make them have the same way of generating a password? Here's how I generate passwords in cakephp2.

App::uses('AuthComponent', 'Controller/Component');
....
public function beforeSave($options = array()) {
      $this->data['User']['password'] = AuthComponent::password(
      $this->data['User']['password']
    );
    return true;
}

This is the way cakephp3 document generates passwords:

namespace App\Model\Entity;

use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;

/**
 * User Entity.
 */
class User extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * @var array
     */
    protected $_accessible = [
        'email' => true,
        'password' => true,
        'bookmarks' => true,
    ];

    protected function _setPassword($value)
    {
        $hasher = new DefaultPasswordHasher();
        return $hasher->hash($value);
    }

}

They are not the same plaintext generate the same ciphertext. So, I can not retain cakephp2 user information. Could you tell me how to set up a successful migration project?


Solution

  • From the CakePHP 3 migration guide:

    • Default is now the default password hasher used by authentication classes. It uses exclusively the bcrypt hashing algorithm. If you want to continue using SHA1 hashing used in 2.x use 'passwordHasher' => 'Weak' in your authenticator configuration.
    • A new FallbackPasswordHasher was added to help users migrate old passwords from one algorithm to another. Check AuthComponent’s documentation for more info.

    Reading the AuthComponent documentation shows an example similar to this:

    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'passwordHasher' => [
                    'className' => 'Fallback',
                    'hashers' => ['Default', 'Weak']
                ]
            ]
        ]
    ]);
    

    When a user logs in the AuthComponent will use the Fallback password hasher class, that will first try the Default hashing method (used in your code above) and then the Weak hasher.

    The documentation also goes on showing you how to update users passwords on login to use the more secure Default hasher.