Symfony 5 / login-signin / Guard authentication

554 views Asked by At

I have to use LoginForm and RegistrationForm in the same page

I m using classic Guard Authentication provided by make:auth

Based on Symfony 5 - Multiples forms on same page, I have created LoginFormType and copy what I have in RegistrationController.

Both Login and Registration fails.

security.yaml :

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: true
        lazy: true
        provider: app_user_provider
        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
        logout:
            path: app_logout
            target: app_login

        remember_me:
            secret: '%kernel.secret%'
            lifetime: 604800 # 1 week in seconds
            path: /

Security/LoginFormAuthenticator.php

class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface{
use TargetPathTrait;

public const LOGIN_ROUTE = 'app_login';

/**
 * @var $entityManager EntityManagerInterface
 */
private $entityManager;

/**
 * @var UrlGeneratorInterface
 */
private $urlGenerator;

/**
 * @var $csrfTokenManager CsrfTokenManagerInterface
 */
private $csrfTokenManager;

/**
 * @var $passwordEncoder UserPasswordEncoderInterface
 */
private $passwordEncoder;

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

public function supports(Request $request)
{
    return self::LOGIN_ROUTE === $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(User::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']);
}

/**
 * Used to upgrade (rehash) the user's password automatically over time.
 */
public function getPassword($credentials): ?string
{
    return $credentials['password'];
}

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

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

protected function getLoginUrl()
{
    return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}

}

SecurityController login method

public function login(
    Request $request,
    AuthenticationUtils $authenticationUtils,
    GuardAuthenticatorHandler $guardAuthenticatorHandler,
    LoginFormAuthenticator $loginFormAuthenticator
): Response {
    if ($this->getUser()) {
        return $this->redirectToRoute('dashboard');
    }

    // LOGIN
    $userToLogIn = new User();
     $director = new Director();
    $loginForm = $this->createForm(LoginFormType::class, $userToLogIn);
     $registrationForm = $this->createForm(RegistrationFormType::class, $director);

    if ($request->isMethod(Request::METHOD_POST)) {
        $loginForm->handleRequest($request);
        $registrationForm->handleRequest($request);

        dump($request->get('signIn'));
        dd($request->get('signUp'));
    }

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig', [
        'last_username' => $lastUsername,
        'error' => $error,
        'loginForm' => $loginForm->createView(),
        'registrationForm' => $registrationForm->createView()
    ]);
}

I m using: Symfony 5.1.3 PHP 7.3.20 ( I m not upgraded to 7.4 yet for non compatibility of some vendors) I m using Symfony local server, no nginx or apache I don't have any .htaccess file

When I m googling that, I found that could be relative to session, that's why I added

framework.yaml :

framework:
//...

session:
    //...
    save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'

    

Login and registration worked before separately

But now when I just visit any page in my site I have this

errors before login or register

and This when I try to login

error after login

Any Help please ???

1

There are 1 answers

0
Ahmed Kallali On BEST ANSWER

I solved the problem by rendering the registration controller in the login template

login.html.twig

// login form
....
{{ render(controller('App\\Controller\\RegistrationController::register')) }}