Symfony2 security.interactive_login无法正确获取passwordUpdatedAt的值显示Flash msg密码即将过期

如何解决Symfony2 security.interactive_login无法正确获取passwordUpdatedAt的值显示Flash msg密码即将过期

获取一个用户变量的正确值时遇到问题。

我创建了PasswordExpirationListener

  1. PasswordExpirationListener::onCheckExpiration()要在过期后强制用户更改密码:此侦听器可以正常工作。

  2. 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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-