gpt4 book ai didi

php - FOSUserBundle - 首次登录后强制更改密码

转载 作者:可可西里 更新时间:2023-11-01 13:47:09 26 4
gpt4 key购买 nike

在使用 FOSUserBundle 进行用户管理的 Symfony2 应用程序中,用户表已通过来自 csv 文件的导入脚本和由数据组合生成的密码填充。

我想强制用户在第一次登录时更改密码。

FOSUserEvents::SECURITY_IMPLICIT_LOGIN 事件发生时,如果字段 last_login 为 NULL,则重定向到路由 fos_user_change_password

我的想法是像这样重写 AGI\UserBundle\EventListener\LastLoginListener 类的方法 onImplicitLogin(UserEvent $event) 但类没有被覆盖:

public function onImplicitLogin(UserEvent $event) {
$user = $event->getUser ();

if ($user->getLastLogin () === null) {
$user->setLastLogin ( new \DateTime () );
$this->userManager->updateUser ( $user );
$response = new RedirectResponse ( $this->router->generate ( 'fos_user_change_password' ) );
$this->session->getFlashBag ()->add ( 'notice', 'Please change your password' );
$event->setResponse ( $response );
}
}

我已经有一个覆盖 FOSUserBundle 的包,它适用于 Controller 、表单等,但看起来这不是使用 eventListeners 的方法。

如何强制用户在首次登录后更改密码?

最佳答案

在@sjagr 提供的关于fos_user.security.implicit_login 的宝贵提示的帮助下,我转向了fos_user.security.implicit_login 和关于doing stuff right after login 的外部主题。 ,我得到了一个可行的解决方案。

AGI\UserBundle\Resources\config\services.yml

login_listener:
class: 'AGI\UserBundle\EventListener\LoginListener'
arguments: ['@security.context', '@router', '@event_dispatcher']
tags:
- { name: 'kernel.event_listener', event: 'security.interactive_login', method: onSecurityInteractiveLogin }

AGI\UserBundle\EventListener\LoginListener.php

<?php

namespace AGI\UserBundle\EventListener;

use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class LoginListener {

private $securityContext;
private $router;
private $dispatcher;

public function __construct(SecurityContext $securityContext, Router $router, EventDispatcherInterface $dispatcher) {
$this->securityContext = $securityContext;
$this->router = $router;
$this->dispatcher = $dispatcher;
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) {
if ($this->securityContext->isGranted ( 'IS_AUTHENTICATED_FULLY' )) {
$user = $event->getAuthenticationToken ()->getUser ();

if ($user->getLastLogin () === null) {
$this->dispatcher->addListener ( KernelEvents::RESPONSE, array (
$this,
'onKernelResponse'
) );
}
}
}
public function onKernelResponse(FilterResponseEvent $event) {
$response = new RedirectResponse ( $this->router->generate ( 'fos_user_change_password' ) );
$event->setResponse ( $response );
}
}

谢谢

关于php - FOSUserBundle - 首次登录后强制更改密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27279641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com