Search code examples
formssymfony1savesha1

save password input as sha1() into db with symfony


I'm wracking my brain on the most simple of things.

I have a symfony-generated form with some customisation. I have the form saving just fine, except that the 'password' field writes the password (as expected) in normal format.

How can I intercept this value before database-entry and sha1() it before writing?

Code is essentially:

$this->dialog = $request->getParameter('dialog');
$this->form = new UserForm();

if ($this->getRequest()->getMethod() == "POST") {
    $this->form->bind($request->getParameter('user'));
    // intercept here, I suspect
    $user = $this->form->save();
}

EDIT: Problem solved.

in /lib/model/User.php

class User extends BaseUser {

public function save(PropelPDO $con = null)
{

  if ($this->getPassword() != '')
  {
    $this->setPassword(sha1($this->getPassword()));
  }

  return parent::save($con);
}

}

It's fairly obvious, but not for a noob like myself. hopefully this helps someone else. If there's a better way to do this without having to extend the save() function, let me know?

Resource: http://www.symfony-project.org/jobeet/1_4/Propel/en/10 (See: Protecting the Job Form with a Token)

EDIT #2: Better way to do this (as per Grad's suggestion below)

In User model

public function setPassword($rawPassword) 
{ 
    $salt = "fgv932g2e9dshdfkdjgf927gf8hlz082";
    $password = sha1($salt . $rawPassword); 
    parent::setPassword($password);
}

Solution

  • It's 'better' do override the setPassword() function on your User Model.

    something like this:

    public function setPassword($rawPassword, $algo = 'sha1', $salt = null) {
      if ($salt === null) {
         $salt = sha1(time().rand().$this->id.$this->username);
      }
      $password = hash($algo, $rawPassword.$salt);
      $this->_set('password', $password);
      $this->_set('password_algo', $algo);
      $this->_set('password_salt', $salt);
    }
    

    This way you can set the password from everywhere (your current solution only works for new users).

    (And, on a side note: don't forget to salt your password. :-) )