Форма входа в Symfony 4 с последующим вводом неверного пароля -> без ошибок, сбой сервера - PullRequest
0 голосов
/ 17 октября 2019

У меня проблема с формой входа в Symfony 4.3.
Я создал форму входа (и всю логику) с помощью make: auth. Также я сделал несколько фиктивных пользователей с приспособлениями.
Итак, проблема в том, что - когда я ввожу неправильный пароль - Symfony вылетает. Единственное, что помогает - команда cache: очистить и очистить кеш в браузере .

Код здесь:

PersonalAccountAuthentificator.php:

<?php

namespace App\Security;

use App\Entity\Users;
use Doctrine\ORM\EntityManagerInterface;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

//use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
//use Symfony\Component\HttpFoundation\JsonResponse;
//use Symfony\Component\HttpFoundation\Response;
//use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
//use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
//use Symfony\Component\Security\Core\Exception\AuthenticationException;
//use Symfony\Component\Security\Core\Exception\BadCredentialsException;

class PersonalAccountAuthenticator extends AbstractFormLoginAuthenticator
{
    use TargetPathTrait;

    private $entityManager;
//    private $urlGenerator;
    private $router;
    private $csrfTokenManager;
    private $passwordEncoder;

//    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
    public function __construct(EntityManagerInterface $entityManager, RouterInterface $router, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->entityManager = $entityManager;
//        $this->urlGenerator = $urlGenerator;
        $this->router = $router;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;
    }

    public function supports(Request $request)
    {
        return 'app_login' === $request->attributes->get('_route')
            && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'email' => $request->request->get('email'),
            'password' => $request->request->get('password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['email']
        );
        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        $user = $this->entityManager->getRepository(Users::class)->findOneBy(['email' => $credentials['email']]);

        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('NO Email!');
//            throw new BadCredentialsException('Почат отсутствует в базе!');
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
//        $plainPassword = $credentials['password'];
//        if ($this->passwordEncoder->isPasswordValid($user, $plainPassword)) {
//            return true;
//        }
//
//        throw new CustomUserMessageAuthenticationException('Неправильный пароль!');
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

//         return new RedirectResponse($this->urlGenerator->generate('dashboard'));
         return new RedirectResponse($this->router->generate('dashboard'));
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
//        $data = [
//            'message' => strtr($exception->getMessageKey(), $exception->getMessageData())." [onAuthenticationFailure]"
//        ];
//
//        return new JsonResponse($this->router->generate('dashboard'));
        return new RedirectResponse($this->router->generate('app_login'));
    }
//
//    /**
//     * Called when authentication is needed, but it's not sent
//     */
//    public function start(Request $request, AuthenticationException $authException = null)
//    {
//        $data = [
//            'message' => 'Authentication Required [start]'
//        ];
//
//        return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
//    }

    protected function getLoginUrl()
    {
//        return $this->urlGenerator->generate('app_login');
        return $this->router->generate('app_login');
    }
}

PersonalAccountController.php:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
//use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class PersonalAccountController extends AbstractController
{
    /**
     * @Route("/login", name="app_login")
     */
//    public function login(Request $request, AuthenticationUtils $authenticationUtils): Response
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/personal_account.html.twig', [
            'last_username' => $lastUsername,
            'error' => $error,
            'controller_name' => 'Авторизация',
        ]);
    }

    /**
     * @Route("/logout", name="logout")
     */
    public function logout()
    {
        throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
    }
}

personal_account.html.twig:

{#{% extends 'personal_account_base.html.twig' %}#}
{% extends 'base.html.twig' %}
{% block stylesheets %}
    {{ parent() }}

    <link rel="stylesheet" href="{{ preload(asset('/css/personal_acc.css'), { as:'style' }) }}">
{% endblock %}
{% block title %}{{ controller_name }}{% endblock %}

{% block body %}
{#    <p class="tip">Click on button in image container</p>#}
    <div class="cont">
        <div class="form sign-in">
            <form method="post" name="signInForm" action="{{ path('app_login') }}">

                {% if error %}
                    <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
                {% endif %}

                <h2>Авторизация</h2>
                <label for="inputEmail" class="sr-only">Электронная почта</label>
                    <input type="email" value="{{ last_username }}" name="email" id="inputEmail" class="form-control" placeholder="Введите почту" required autofocus>
                <label for="inputPassword" class="sr-only">Пароль</label>
                    <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Введите пароль" required>

                <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">

                <button type="submit" class="submit">Авторизироваться</button>
            </form>

        </div>

        <div class="sub-cont">
            <div class="img">
                <div class="img__text m--up">
                    <h2>Регистрация</h2>
                    <p>Узнайте о возможностях, которые доступны только зарегистрированным пользователям!</p>
                </div>
                <div class="img__text m--in">
                    <h2>Вы уже зарегистрированы?</h2>
                    <p>Если Вы уже зарегистрированы, нажмите на кнопку "Перейти к авторизации"</p>
                </div>
                <div class="img__btn">
                    <span class="m--up">Перейти к регистрации</span>
                    <span class="m--in">Перейти к авторизации</span>
                </div>
            </div>
            <div class="form sign-up">
                <h2>Возможности, доступные зарегистрированным пользователям:</h2>
                <ul class="square--list">
                    <li>"Избранные" парковки</li>
                    <li>Отслеживание проведенных оплат</li>
                    <li>Обзор карт с предоплатой</li>
                </ul>
                <button class="submit"><a href="{{ path('register') }}">Зарегистрироваться</a></button>
                {#                <button type="button" class="fb-btn">Join with <span>facebook</span></button>#}
            </div>
        </div>
    </div>
    {{ dump(app) }}
{% endblock %}

{% block javascripts %}
    {{ parent() }}
{#    <script src="{{ asset('/js/validation.js') }}"></script>#}
{#    <script src="{{ asset('/js/pa.js') }}"></script>#}
    <script src="{{ asset('/js/personal_acc.js') }}"></script>
{% endblock %}

DashboardController.php (перенаправление здесь, если авторизация успешна):

<?php

namespace App\Controller;

use App\Entity\Users;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

class DashboardController extends AbstractController
{
    /**
     * @Route("/dashboard", name="dashboard")
     */
    public function dashboard()
    {
        /** @var Users $user */

        $user = $this->getUser();

//        if(!$user){
//            throw new AccessDeniedHttpException();
//        }

        $user_id = $user->getId();

        $get_roles_array = $user->getRoles();
        $role = substr(strtolower(current($get_roles_array)), 5) . 's';

        return $this->redirectToRoute('user_dashboard', [
            'user_id' => $user_id,
            'role' => $role
        ]);
    }

    /**
     * @Route("/dashboard/{role}/{user_id}", name="user_dashboard")
     * @IsGranted("ROLE_USER", statusCode=401)
     */
    public function userDashboard(string $role, string $user_id)
    {
        /** @var Users $user */
        $user = $this->getUser();

        $get_roles_array = $user->getRoles();

        $this->denyAccessUnlessGranted($user->getRoles());

        list($user_role,) = $get_roles_array;
//        $user_role = implode($get_roles_array);

        $login = $user->getLogin();
        return $this->render('admin_dashboard/adminDashboard.html.twig', [
            'controller_name' => $login,
            'user_role' =>$user_role
        ]);
    }
}

security.yaml:

security:
    encoders:
        App\Entity\Users:
            algorithm: auto


    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\Users
                property: email
        # used to reload user from session & other features (e.g. switch_user)
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
#            anonymous: true
            anonymous: ~
            provider:
                app_user_provider
            guard:
                authenticators:
                    - App\Security\PersonalAccountAuthenticator
                entry_point: App\Security\PersonalAccountAuthenticator
            logout:
                path: logout
                # where to redirect after logout
                # target: app_any_route

            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#firewalls-authentication

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        # - { path: ^/admin, roles: ROLE_ADMIN }
        # - { path: ^/profile, roles: ROLE_USER }

dev.log (после ввода неверного пароля):

[2019-10-17 12:43:17] request.INFO: Matched route "app_login". {"route":"app_login","route_parameters":{"_route":"app_login","_controller":"App\\Controller\\PersonalAccountController::login"},"request_uri":"http://127.0.0.1:8001/login","method":"POST"} []
[2019-10-17 12:43:17] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} []
[2019-10-17 12:43:17] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\\Security\\PersonalAccountAuthenticator"} []
[2019-10-17 12:43:17] security.DEBUG: Calling getCredentials() on guard authenticator. {"firewall_key":"main","authenticator":"App\\Security\\PersonalAccountAuthenticator"} []
[2019-10-17 12:43:17] security.DEBUG: Passing guard token information to the GuardAuthenticationProvider {"firewall_key":"main","authenticator":"App\\Security\\PersonalAccountAuthenticator"} []
[2019-10-17 12:43:17] doctrine.DEBUG: SELECT t0.id AS id_1, t0.login AS login_2, t0.password AS password_3, t0.email AS email_4, t0.phone AS phone_5, t0.roles AS roles_6 FROM users t0 WHERE t0.email = ? LIMIT 1 ["test_email2@yahoo.com"] []
[2019-10-17 12:43:20] security.INFO: Guard authentication failed. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\BadCredentialsException(code: 0): Authentication failed because App\\Security\\PersonalAccountAuthenticator::checkCredentials() did not return true. at D:\\OpenServer\\OSPanel\\domains\\ParkingApp_Symfony\\vendor\\symfony\\security-guard\\Provider\\GuardAuthenticationProvider.php:113)","authenticator":"App\\Security\\PersonalAccountAuthenticator"} []
[2019-10-17 12:43:20] security.DEBUG: The "App\Security\PersonalAccountAuthenticator" authenticator set the response. Any later authenticator will not be called {"authenticator":"App\\Security\\PersonalAccountAuthenticator"} []
[2019-10-17 12:43:22] request.INFO: Matched route "app_login". {"route":"app_login","route_parameters":{"_route":"app_login","_controller":"App\\Controller\\PersonalAccountController::login"},"request_uri":"http://127.0.0.1:8001/login","method":"GET"} []
[2019-10-17 12:43:22] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} []
[2019-10-17 12:43:22] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\\Security\\PersonalAccountAuthenticator"} []
[2019-10-17 12:43:22] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\\Security\\PersonalAccountAuthenticator"} []
[2019-10-17 12:43:22] security.INFO: Populated the TokenStorage with an anonymous Token. [] []

Может быть, кто-то знает Symfony так хорошо, чтобы помочь мне и указать на части, которые не работают правильно? Спасибо за чтение.

...