Вход в Symfony не выполняется - PullRequest
0 голосов
/ 12 марта 2019

Здравствуйте, мой логин не совпадает, и я понятия не имею, почему кто-то может мне помочь, пожалуйста, когда я пытаюсь подключиться, ничего не происходит, у меня нет ошибок, просто ничего не происходит,

adminlogin.html.twig

    {% extends 'base.html.twig' %}

{% block title %}Connexion Admin!{% endblock %}

{% block body %}

    {% if error %}
        <div class="alert alert-danger">
            {{ error.messageKey }}
        </div>
    {% endif %}

<div class="example-wrapper">

    <div class="row">


            <div class="form">

                <form class="login-form">
                    <img src="{{ asset('./../build/img/logo.png') }}" alt="Logo">
                    <h3>Connexion</h3>
                    <input type="text" placeholder="email" value="{{ last_email }}"/>
                    <input type="password" placeholder="mot de passe"/>
                    <input type="hidden" name="_csrf_token"
                           value="{{ csrf_token('authenticate') }}">
                    <button>Connexion</button>
                    <p class="message">Pas de compte? <a href="{{ path('add_register') }}">Créer un compte</a></p>

                </form>
            </div>
        </div>

    </div>
   {% block javascripts %}{% endblock %}
{% endblock %}

LoginFomAuthenticator.php

namespace App\Security;

    use App\Entity\Admin;
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
    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\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;

    class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
    {
        use TargetPathTrait;

        private $entityManager;
        private $router;
        private $csrfTokenManager;
        private $passwordEncoder;

        public function __construct(EntityManagerInterface $entityManager, RouterInterface $router, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
        {
            $this->entityManager = $entityManager;
            $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(Admin::class)->findOneBy(['email' => $credentials['email']]);

            if (!$user) {
                // fail authentication with a custom error
                throw new CustomUserMessageAuthenticationException('Email could not be found.');
            }

            return $user;
        }

        public function checkCredentials($credentials, UserInterface $user)
        {
            return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
        }

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

            // For example : return new RedirectResponse($this->router->generate('some_route'));
            throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
        }

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

AdminController.php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class AdminController extends AbstractController
{
    /**
     * @Route("/admin/login", name="adminlogin", methods={"GET", "POST"})
     */
    public function adminLoginRoute(AuthenticationUtils $authenticationUtils) : Response
    {
        $error = $authenticationUtils->getLastAuthenticationError();

        $lastEmail = $authenticationUtils->getLastUsername();

        dump($error);
        dump($lastEmail);

        return $this->render('adminlogin.html.twig', [
            'controller_name' => 'Connexion Admin',
            'last_email' => $lastEmail,
            'error' => $error,
        ]);
    }
}

Admin.php "Сущность"

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\AdminRepository")
 */
class Admin implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $firstname;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $pwd;

    /**
     * @ORM\Column(type="array")
     */
    private $role;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\City", cascade={"persist", "remove"})
     */
    private $city;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getFirstname(): ?string
    {
        return $this->firstname;
    }

    public function setFirstname(string $firstname): self
    {
        $this->firstname = $firstname;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getPwd()
    {
        return $this->pwd;
    }

    /**
     * @param mixed $pwd
     */
    public function setPwd($pwd): void
    {
        $this->pwd = $pwd;
    }

    public function getRoles(): ?array
    {
        return $this->role;
    }

    public function setRoles(array $role): self
    {
        $this->role = $role;

        return $this;
    }

    public function getCity(): ?City
    {
        return $this->city;
    }

    //Fonction UserInterface


    public function getPassword(): ?string
    {
        return $this->pwd;
    }

    public function setPassword(string $pwd): self
    {
        $this->pwd = $pwd;

        return $this;
    }

    public function setCity(?City $city): self
    {
        $this->city = $city;

        return $this;
    }

    public function getSalt()
    {
        return null;
    }
    public function eraseCredentials()
    {
        return null;
    }

    public function getUsername()
    {
        $this->getName();
    }

}

реестр работает, и у меня есть мои данные в моей БД, база данных типа SQLite

и security.yaml

security:
    encoders:
        App\Entity\Admin: bcrypt
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory: { memory: ~ }
        admin_provider:
            entity:
                class: App\Entity\Admin
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: ~
            form_login:
                login_path: adminlogin
                check_path: adminlogin
                always_use_default_target_path: true

            http_basic: ~
            provider: admin_provider

            logout:
                path: /logout
                target: /home

            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator

    role_hierarchy:
        ROLE_ADMIN: ROLE_ADMIN
        ROLE_SUPER_ADMIN: ROLE_SUPER_ADMIN

            # activate different ways to authenticate

            # http_basic: true
            # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: true
            # https://symfony.com/doc/current/security/form_login_setup.html

    # 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: ^/admin, roles: ROLE_ADMIN }
        # - { path: ^/profile, roles: ROLE_USER }

thx для вашей помощи

1 Ответ

0 голосов
/ 28 июня 2019
<form class="login-form">
    <img src="{{ asset('./../build/img/logo.png') }}" alt="Logo">
    <h3>Connexion</h3>
    <input type="text" name="_email" placeholder="email" value="{{ last_email }}"/>
    <input type="password" name="_password" placeholder="mot de passe"/>
    <input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}">
    <button>Connexion</button>
    <p class="message">Pas de compte? <a href="{{ path('add_register') }}">Créer un compte</a></p>    

Может быть, вам не хватает атрибута name=""

Я редактировал ваши <form> с _email и _password

РЕДАКТИРОВАТЬ: Не видел, что было опубликовано в марте ¯ \ _ (ツ) _ / ¯

...