代码之家  ›  专栏  ›  技术社区  ›  Miro Lehtonen

如何使异常消息在symfony 4用户检查器中可翻译?

  •  2
  • Miro Lehtonen  · 技术社区  · 6 年前

    我正在检查是否允许用户登录,如果不允许,则向他们显示一条使用其区域语言的错误消息。这是一个symfony 4.2应用程序。这是我的用户检查程序(可以工作):

    <?php
    namespace App\Security;
    
    use App\Entity\User as AppUser;
    use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
    use Symfony\Component\Security\Core\User\UserCheckerInterface;
    use Symfony\Component\Security\Core\User\UserInterface;
    
    class UserChecker implements UserCheckerInterface {
        public function checkPreAuth(UserInterface $user)
        {
            if (!$user instanceof AppUser) {
                return;
            }
        }
    
        public function checkPostAuth(UserInterface $user)
        {
        /* Make the message translatable */
            if (!$user->isEnabled()) {
                throw new CustomUserMessageAuthenticationException(
                    'This account has not been activated.'
                );
            }
        }
    }
    

    通常在symfony 4中转换字符串的方法需要更改签名:

    public function checkPostAuth(UserInterface $user, TranslatorInterface $translator)
    

    这在我在控制器中定义的函数中有效,但此用户检查器注册为防火墙中使用的服务,因此我们得到一个错误:

    FatalErrorException
    Compile Error: Declaration of App\Security\UserChecker::checkPostAuth(Symfony\Component\Security\Core\User\UserInterface $user, App\Security\TranslatorInterface $translator) must be compatible with Symfony\Component\Security\Core\User\UserCheckerInterface::checkPostAuth(Symfony\Component\Security\Core\User\UserInterface $user)
    

    我也找不到与symfony 4一起工作的任何其他方式的文档。

    1 回复  |  直到 6 年前
        1
  •  3
  •   dbrumann    6 年前

    symfony这样做的方式是,仅当在呈现模板(例如在 login form 你有这个:

    {% if error %}
        <div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}
    

    另一种方法可能是钩住symfony的事件系统,并在捕获 AuthenticationFailureEvent 通过聆听 AuthenticationEvents::AUTHENTICATION_FAILURE .