gpt4 book ai didi

symfony - 在 FOSUserBundle 中登录后的自定义错误消息

转载 作者:行者123 更新时间:2023-12-03 22:17:41 27 4
gpt4 key购买 nike

我正在使用 FOSUserBundle 和 Symfony 3.4 来登录我的用户。当他们输入错误的密码时,会显示以下消息:
enter image description here
我要添加 检查用户类型并添加自定义错误消息,例如:“您必须是客户才能登录。”。
我实现了一个用户检查器来完成这个任务,但它没有按预期工作:

class CustomerUserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user)
{
// nothing to do here
return;
}

public function checkPostAuth(UserInterface $user)
{
if (!$user instanceof CustomerUser) {
throw new AuthenticationException('You must be a customer in order to login');
}

return;
}
}
我收到此错误:
enter image description here
如何在文本中添加新错误?

最佳答案

我能够使用自定义异常实现我的目标:

<?php

namespace AppBundle\Security;

use Symfony\Component\Security\Core\Exception\AccountStatusException;

class CustomerUserException extends AccountStatusException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'You must be a customer in order to login.';
}
}

用户检查器现在是这样的:
<?php

namespace AppBundle\Security;

use Application\Sonata\UserBundle\Entity\CustomerUser;
use Application\Sonata\UserBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class CustomerUserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user)
{
// nothing to do here
return;
}

public function checkPostAuth(UserInterface $user)
{
if (!$user instanceof User) {
return;
}

if (!$user instanceof CustomerUser) {
throw new CustomerUserException();
}
}
}

[可选] 我在 app/Resources/translations/security.en.xlf 中创建了一个新的翻译文件:
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="You must be a customer in order to login.">
<source>You must be a customer in order to login.</source>
<target>You must be a customer in order to login.</target>
</trans-unit>
</body>
</file>
</xliff>

并且消息正确显示:

enter image description here

关于symfony - 在 FOSUserBundle 中登录后的自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49031659/

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