登录后Symfony重定向,并带有用户条件 [英] Symfony redirect after login with condition on user
问题描述
我的symfony3登录页面默认重定向到主目录,如我的security.yml
文件中所述.
My symfony3 login page redirects to home by default, as stated inside my security.yml
file.
但是,如果用户还没有完成,我希望它重定向到我的编辑个人资料"页面.以任何其他形式,我都会在控制器中进行此操作,但是由于登录表单中没有$form->handleRequest($user)
,因此我没有要测试的$user
变量.
However, I want it to redirect to my "Edit profile" page if the user didn't fulfil it yet. In any other form I would make this in the controller, but since there is no $form->handleRequest($user)
in the login form, I don't have a $user
variable to test on.
关于如何根据角色重定向用户有很多SO主题,并且 documentation 讲述了如何从表单的操作字段或在security.yml
内进行重定向,但我所寻找的并不是任何内容.
There is a lot of SO topics about how to redirect user based on roles, and the documentation tells about redirecting from the action field of the form or within security.yml
, but not any is what I'm looking for.
如何根据条件重定向?
注意:由于某些原因,我还不能使用FOSUserBundle:-(
NB : for some reasons, I cannot use FOSUserBundle yet :-(
推荐答案
我假设您使用的是Guard Authentication系统. ( http://symfony.com/doc/current/security/guard_authentication.html)
I assume you are using the Guard Authentication system. ( http://symfony.com/doc/current/security/guard_authentication.html )
然后,您应该有一个扩展AbstractGuardAuthenticator
类的类.
Then you should have a class extending the AbstractGuardAuthenticator
class.
在该类中,有一个名为onAuthenticationSuccess
的方法,在这里您可以放置一些用于重定向请求的逻辑.
如果您在此处返回null
,它将继续,并使用security.yml中配置的路由.
In that class, there is a method called onAuthenticationSuccess
, in here you can put some logic for redirecting the request.
If you return null
here, it will just continue, and use the route configured in your security.yml.
您将需要通过dependencyInjection将@router
服务传递给Authenticator类.
You will need to pass the @router
service to the Authenticator class through dependencyInjection.
假设您通过了路由器服务,那么您的方法将如下所示:
Assuming you passed the router service, your method will look something like this:
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
/** @var User $user */
$user = $token->getUser();
if ($user->hasCompleteProfile() == false) {
$url = $this->router->generate('edit_profile');
return new RedirectResponse($url);
}
// Continue with default behaviour
return null;
}
这篇关于登录后Symfony重定向,并带有用户条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!