我的观察者功能之一出现问题。 由于某种原因,我无法加载客户信息以进行进一步操作
$user = $observer->getEvent()->getCustomer();
$usertemp = Mage::getModel('customer/customer')->load($user->getId());
我查了一下,$user->getId()实际上携带了id;然而,当我尝试时,例如:
$password = $usertemp->getPassword();
设置了一个空值而不是用户的密码。
最佳答案
首先 - 如果您已经有 $observer->getEvent()->getCustomer()
中的对象,为什么还要加载 customer
对象呢?这个操作在这里是多余的,只会增加资源和时间消耗。
第二 - 出于安全考虑,Magento 不会以解密形式存储用户密码。如果您想获取用户密码,请尝试以下代码:
$passwHash = $customer->getPasswordHash();
$password = Mage::helper('core')->decrypt($passwHash); // this will not work
更新:Mage::helper('core')->decrypt
不会解密密码哈希,因为它是用md5哈希函数哈希的,所以有一个检查密码是否相同的方法(Mage::helper('core')->validateHash
),但无法找回原始密码。
更新 2:提问者有一些有趣的问题,他在评论中提供了这些问题,我将在这里解决这些问题:
为什么 123456 的哈希值是
0f474c41fd20617eb8f1a0cb9b08f3aa:Uh
,而在 md5 中它应该是e10adc3949ba59abbe56e057f20f883e
。答案是 - 因为hash
方法不仅对传入的密码进行哈希处理,而且还对随机生成的盐进行哈希处理。看看这个方法:public function getHash($password, $salt = false) { if (is_integer($salt)) { $salt = $this->_helper->getRandomString($salt); } return $salt === false ? $this->hash($password) : $this->hash($salt . $password) . ':' . $salt; }
以及
Customer
模型中的这两个方法:public function setPassword($password) { $this->setData('password', $password); $this->setPasswordHash($this->hashPassword($password)); return $this; } public function hashPassword($password, $salt = null) { return Mage::helper('core')->getHash($password, !is_null($salt) ? $salt : 2); }
因此,由于
$salt
参数是整数 (2),因此实际的盐是随机生成的字符串。这就是为什么您的输出哈希值与简单的md5($passw)
不同。Also I was working directly with the getPassword() because it was working on user register
这样比较容易一些。在
注册
过程中,您将获得带有原始密码的$_POST
数据。在$customer->setPassword($passw)
的帮助下,您将其设置为$customer
模型。如果您查看上面的此函数,您会发现在此操作期间设置了password
和password
哈希属性。唯一的区别是:password
实际上并不是一个现有的属性,这意味着它不会存储在数据库或其他任何地方,并且一旦$customer它就会丢失
对象从内存中清除。
Magento 中无法获取用户密码。您唯一能做的就是将给定密码与现有的 password_hash
进行比较(正如我之前提到的):Mage_Core_Helper_Data::validateHash
public function validateHash($password, $hash)
{
$hashArr = explode(':', $hash);
switch (count($hashArr)) {
case 1:
return $this->hash($password) === $hash;
case 2:
return $this->hash($hashArr[1] . $password) === $hashArr[0];
}
Mage::throwException('Invalid hash.');
}
关于Magento 加载客户数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12923641/