Generate user password for CakePHP Auth
Main Thread • 1 min read
The other day I imported some existing user accounts into my CakePHP project. The project was using CakePHP's Auth Component. By default, CakePHP Auth uses its own hashing to encrypt the password. So I needed to hash the password for the existing user accounts.
I vaguely remembered a script in the CakePHP Book, but couldn't find it. I figured I could have searched for one or write one. In typical developer fashion, I chose the latter.
1public function generate_passwords() { 2 // get the users that need their password hashed 3 $results = $this->User->find('all', array('recursive' => -1, 'fields' => array('User.id', 'User.passwd'), 'conditions' => array('User.email LIKE' => '%@example.com', 'NOT' => array('User.passwd' => null)))); 4 5 $count = count($results); 6 foreach ($results as $result) { 7 $result['User']['passwd'] = $this->Auth->password($result['User']['passwd']); 8 9 if (!$this->User->save($result)) {10 echo 'Could not update account for User.id = ', $result['User']['id'], PHP_EOL;11 --$count;12 }13 }14 15 echo 'Updated ', $count, ($count == 1 ? ' record.', 'records.'), PHP_EOL;16 exit;17}
Paste this code into any controller that has access to the Auth component and your Auth User model. Then visit the URL. In this case /users/generate_passwords. Only run this once. Otherwise, it will double hash your passwords.
You should only need to adjust the conditions
option for the find()
method so that it only returns the user accounts that need their passwords hashed. Also note that this code is built for CakePHP 1.3. However, it should port pretty easily to 2.0. If you do so please let me know.
Find this interesting? Let's continue the conversation on Twitter.