如何解决Symfony2 security.interactive_login无法正确获取passwordUpdatedAt的值显示Flash msg密码即将过期
获取一个用户变量的正确值时遇到问题。
我创建了PasswordExpirationListener
:
-
PasswordExpirationListener::onCheckExpiration()
要在过期后强制用户更改密码:此侦听器可以正常工作。 -
PasswordExpirationListener::onCheckExpirationSoon()
当用户登录时检查PWD的有效性是否少于7天并显示flash msg:当我获得登录用户时,变量$use->getPasswordUpdatedAt
的值始终为NULL
这是非常奇怪的情况,因为我可以拥有所有其他用户变量(例如firstname
的正确值,但不能拥有passwordUpdatedAt
的值
<?php
namespace UserBundle\Listener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use BeSimple\I18nRoutingBundle\Routing\Router;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use UserBundle\Entity\User;
/**
* Listener responsible to change the redirection at the end of the password change
*/
class PasswordExpirationListener
{
/** @var TokenStorage */
private $context;
/** @var UrlGeneratorInterface */
private $router;
/** @var Session */
private $session;
/** @var AuthorizationCheckerInterface */
private $authorizationChecker;
public function __construct(Router $router,TokenStorage $context,Session $session,AuthorizationCheckerInterface $authorizationChecker
){
$this->context = $context;
$this->router = $router;
$this->session = $session;
$this->authorizationChecker = $authorizationChecker;
}
public function onCheckExpiration(GetResponseEvent $event)
{
if ($this->context->getToken() && $this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
if ($event->getRequest()->get('_route') != 'employe_change_password') {
/** @var User $user */
$user = $this->context->getToken()->getUser();
if ($user->getPasswordValidityPeriod() <= 0) {
// Display alert
$this->session->getFlashBag()->add('danger','Your password hash expired. Please change it');
// Redirect to change password
$url = $this->router->generate('employe_change_password',['user' => $user->getId()]);
$event->setResponse(new RedirectResponse($url));
}
}
}
}
public function onCheckExpirationSoon(InteractiveLoginEvent $event)
{
// writeLog('onCheckExpirationSoon');
if ($this->context->getToken() && $this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
/** @var User $user */
$user = $event->getAuthenticationToken()->getUser();
writeLog('getFirstname: ' . $user->getFirstname());
writeLog('getPasswordUpdatedAt: ');
writeLog($user->getPasswordUpdatedAt());
if ($user->getPasswordValidityPeriod() <= 7) {
// how many days before expiration
$dayBeforeExpiration = 180 - $user->passwordUpdateSince();
$route = $this->router->generate('employe_change_password',['user' => $user->getId()]);
$msg = "Your password will expire in $dayBeforeExpiration days. " .
"<a href='$route'>Please click here to change it </a>";
$this->session->getFlashBag()->add('warning',$msg);
}
}
}
}
# UserBundle/Resources/config/services.yml
user.password_expiration:
class: UserBundle\Listener\PasswordExpirationListener
arguments:
- @router
- @security.token_storage
- @session
- @security.authorization_checker
tags:
- { name: kernel.event_listener,event: kernel.request,method: onCheckExpiration }
- { name: kernel.event_listener,event: security.interactive_login,method: onCheckExpirationSoon }
// UserBundle\Entity\User.php
use FOS\UserBundle\Model\User as BaseUser;
class user extend BaseUser
{
/**
* @var \DateTime
*
* @Gedmo\Versioned
* @ORM\Column(name="password_updated_at",type="datetime")
*/
protected $passwordUpdatedAt;
/**
* Set created
*
* @param \DateTime $passwordUpdatedAt
* @return User
*/
public function setPasswordUpdatedAt($passwordUpdatedAt)
{
$this->passwordUpdatedAt = $passwordUpdatedAt;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getPasswordUpdatedAt()
{
return $this->passwordUpdatedAt;
}
/**
* After 120 days the password expired.check
* @return bool
*/
public function getPasswordValidityPeriod ()
{
return ( 120 - (!($this->passwordUpdatedAt instanceof \DateTime)? 0 :
((int) $this->passwordUpdatedAt
->diff((new \DateTime()))
->format('%a')))
);
}
}
还有其他空的用户变量,例如gender,ip,cid
,但是它们在数据库中都有一个值。我不知道为什么它不能填充BD中的所有变量
src/UserBundle/Listener/PasswordExpirationListener.php:104:
object(UserBundle\Entity\User)[571]
protected 'id' => int 289226
protected 'username' => string 'ayoub.e@balabala.com' (length=23)
protected 'usernameCanonical' => string 'ayoub.e@balabala.com' (length=23)
protected 'email' => string 'ayoub.e@balabala.com' (length=23)
protected 'emailCanonical' => string 'ayoub.e@balabala.com' (length=23)
protected 'enabled' => boolean true
protected 'salt' => string 'yK0MFvfHbalabalapZzLzpHTbalabaladq1Q' (length=43)
protected 'password' => string 'cX6TbalabalaQbalababalabalalbVowAhnfbalabalawlv3g==' (length=88)
protected 'plainPassword' => null
protected 'lastLogin' =>
object(DateTime)[70]
public 'date' => string '2020-08-20 08:23:49.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Toronto' (length=15)
protected 'confirmationToken' => null
protected 'passwordRequestedAt' => null
protected 'groups' =>
object(Doctrine\Common\Collections\ArrayCollection)[97]
private 'elements' =>
array (size=0)
empty
protected 'roles' =>
array (size=1)
0 => string 'ROLE_SUPER_ADMIN' (length=16)
protected 'created' =>
object(DateTime)[576]
public 'date' => string '2019-04-29 19:43:31.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Toronto' (length=15)
protected 'locale' => string 'fr' (length=2)
protected 'firstname' => string 'Qyokhpppppppppppppg' (length=19)
protected 'lastname' => string 'Etters' (length=6)
protected 'passwordUpdatedAt' => null
private 'gender' => null
protected 'ip' => null
protected 'cid' => null
private 'newsLetter' => boolean true
protected 'verified' => boolean true
protected 'lastActivity' =>
object(DateTime)[574]
public 'date' => string '2020-08-20 08:23:55.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Toronto' (length=15)
protected 'pi_adwords_q' => null
private 'website' =>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。