Php Symfony检查用户是否';s的电子邮件在登录时已更改
我正在做一个测试项目,在那里我制作了一个简单的登录表单,配置Php Symfony检查用户是否';s的电子邮件在登录时已更改,php,symfony,Php,Symfony,我正在做一个测试项目,在那里我制作了一个简单的登录表单,配置security.yml。我了解到,序列化和取消序列化实体中的函数,从会话中加载并获取用户实例,并将id、用户名和密码与数据库中的数据进行比较。当其中一个参数不相等时,用户将注销 public function serialize() { return serialize(array( $this->id, $this->username, $this->pass
security.yml
。我了解到,序列化
和取消序列化
实体中的函数,从会话中加载并获取用户
实例,并将id、用户名和密码与数据库中的数据进行比较。当其中一个参数不相等时,用户将注销
public function serialize() {
return serialize(array(
$this->id,
$this->username,
$this->password
));
}
public function unserialize($serialized) {
list(
$this->id,
$this->username,
$this->password
) = unserialize($serialized);
}
现在,我甚至会在用户登录时检查电子邮件是否已更改,如果是,请注销。我试图将$this->email
添加到序列化
和取消序列化
函数中,但它并不在意。如何实现这一点?如果您已经创建了一个实现UserProviderInterface
的应用程序,并且需要比较存储在用户会话实例中的一些合理用户数据(从中存储在数据库中),最简单的方法是在用户
类中实现equalTableInterface
:
use Symfony\Component\Security\Core\User\EquatableInterface;
class User implements EquatableInterface
{
public function serialize() {
return serialize(array(
$this->id,
$this->username,
$this->password,
$this->email <--- add the email to serialized data
#$this->account->getEmail() <--- you can also add the email from an association
));
}
public function unserialize($serialized) {
list(
$this->id,
$this->username,
$this->password,
$this->email <--- add the email to unserialize method
) = unserialize($serialized);
}
/**
* @param \Symfony\Component\Security\Core\User\UserInterface $user
*
* @return bool
*/
public function isEqualTo(UserInterface $user):bool
{
if (!$user instanceof User) {
return false;
}
if ($this->username !== $user->getUsername()) {
return false;
}
if ($this->password !== $user->getPassword()) {
return false;
}
# here you make the email comparison
if ($this->email !== $user->getEmail()) {
return false;
}
return true;
}
}
@gp\u我已经读过关于
equalableinterface
的文章,但是如何比较数据库中的$user
电子邮件呢?我找不到从实体发送查询或使用其存储库的正确方法。我添加了一个答案。让我知道:-)。如此简单,如此强大。非常感谢你。你能解释一下在哪种情况下,$user instanceof user===false
?@DrKey我不确定你说的“在哪种情况下…”是什么意思,但很明显,你需要保持数据一致性,避免在直接使用该方法时传递一些“不受支持的”用户对象。
public function refreshUser(UserInterface $user)
{
if (!$user instanceof User) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $this->loadUserByUsername($user->getUsername());
}