2011-08-09 39 views
1

我在最簡單的事情上壓抑着我的大腦。將輸入爲sha1()的密碼保存到db與symfony中

我有一個symfony生成的窗體與一些自定義。除了「密碼」字段以正常格式寫入密碼(如預期的那樣)之外,我的表單保存得很好。

如何在數據庫輸入和sha1()之前攔截此值,然後寫入?

代碼基本上是:

$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(); 
} 

編輯: 問題解決了。

/lib/model/User.php

類用戶擴展BaseUser {

public function save(PropelPDO $con = null) 
{ 

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

    return parent::save($con); 
} 

}

這是相當明顯的,但不是像一個noob我。希望這可以幫助別人。如果有更好的方法來做到這一點,而不必擴展save()函數,讓我知道?

資源:http://www.symfony-project.org/jobeet/1_4/Propel/en/10(參見:保護工作形成一個令牌

編輯#2:更好的方式來做到這一點(按以下梯度的建議)

在用戶模式

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

回答

4

在您的User型號上重寫setPassword()函數會更好。

是這樣的:

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); 
} 

這種方式,你可以設置來自世界各地的密碼(當前解決方案僅適用於新用戶)。

(而且,在一個側面說明:不要忘了鹽密碼:-))。

+0

奇格勒嗨!謝謝你。非常明顯!不過,我已經稍微更新了你的功能,似乎是一個更好的主意(是的,功能非常鹹!);)...看到原來的帖子! – David

+0

如果您還將鹽保存到數據庫並使其對每個用戶都是動態的,那麼您可以使其更加鹹味;-)。 (看我更新的代碼) –

+0

哈哈!太多鹽對你的健康有害,你知道......嘿嘿! :) – David