CakePHP3でユーザーデータ新規作成時にパスワードを自動的にハッシュ化する方法。
● 使用例のテーブル定義(usersテーブル)
1 2 3 4 5 6 7 8 9 10 | // ユーザーテーブル // status 0:仮登録 1:本登録 2:退会 CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `status` char(1) DEFAULT 0, `created` DATETIME DEFAULT NULL, `modified` DATETIME DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
◯「src/Model/Entity/User.php(bakeで生成したファイル)」
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | # bin/cake bake model users # cat src/Model/Entity/User.php <?php namespace App\Model\Entity; use Cake\ORM\Entity; /** * User Entity * * @property int $id * @property string $email * @property string $password * @property string $status * @property \Cake\I18n\FrozenTime $created * @property \Cake\I18n\FrozenTime $modified */ class User extends Entity { /** * Fields that can be mass assigned using newEntity() or patchEntity(). * * Note that when '*' is set to true, this allows all unspecified fields to * be mass assigned. For security purposes, it is advised to set '*' to false * (or remove it), and explicitly make individual fields accessible as needed. * * @var array */ protected $_accessible = [ 'email' => true, 'password' => true, 'status' => true, 'created' => true, 'modified' => true ]; /** * Fields that are excluded from JSON versions of the entity. * * @var array */ protected $_hidden = [ 'password' ]; } |
◯「src/Model/Entity/User.php」に自動パスワードハッシュ化処理を追記する
1 2 3 4 5 6 7 8 | use Cake\Auth\DefaultPasswordHasher; // DefaultPasswordHasherクラスも追記 protected function _setPassword($password) { if (strlen($password) > 0) { return (new DefaultPasswordHasher)->hash($password); } } |
上記設定により、『$this->Users->save($user);』時に自動的にパスワードがハッシュ化される。