Contao 4.8.7 Symfony login

I’ve created a checkout page where it is possible to login in Vue and during the login the credentials are sent to an API with axios.

How to get Symfony to recognize this login and also save it in the session/cookie.

I currently have the following code but I’m stuck as to where I should continue.
I was able to create an authenticatedToken and found that the GuardHandler should be able to login to the system but I’m clueless as how to progress this.

Code below:

<?php declare(strict_types=1);

namespace AppCommerceController;

use ContaoFrontendUser;
use ContaoMemberModel;
use ContaoSystem;
use ContaoVersions;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentRoutingRouter;
use SymfonyComponentSecurityCoreAuthenticationAuthenticationManagerInterface;
use SymfonyComponentSecurityCoreAuthenticationProviderDaoAuthenticationProvider;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use SymfonyComponentSecurityCoreEncoderBCryptPasswordEncoder;
use SymfonyComponentSecurityCoreEncoderEncoderFactory;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserInMemoryUserProvider;
use SymfonyComponentSecurityCoreUserUser;
use SymfonyComponentSecurityCoreUserUserChecker;
use SymfonyComponentSerializerEncoderJsonEncoder;
use function array_key_exists;

/**
 * Handles the FrontendUser routes.*
 * @Route("/api", defaults={"_scope" = "frontend", "_token_check" = false})
 */
class FrontendUserController extends ApiController
{
    /**
     * @var string Uniquely identifies the secured area
     */
    private $providerKey = 'secured_area';

    /**
     * @Route("/user/login/", name="userLogin")
     * @param Request $request
     * @return Response
     */
    public function loginAction(Request $request): Response
    {
        $parameters = null;
        $loggedIn = false;
        if ($content = $request->getContent()) {
            //$parameters = json_decode($content,false);
            $parameters = json_decode($content, true);

            if (count($parameters)) {
                $candidate = MemberModel::findByUsername($parameters['email']);

                if ($candidate) {
                    $loggedIn = password_verify($parameters['password'], $candidate->password);

                    if ($loggedIn) {

                        $unauthenticatedToken = new UsernamePasswordToken(
                            $parameters['email'],
                            $parameters['password'],
                            $this->providerKey
                        );

                        $userProvider = new InMemoryUserProvider(
                            [
                                '[email protected]' => [
                                    // password is "123456789"
                                    'password' => '$2y$10$5fBhOQZqBCqaR8YHPL7MCuBZHsS.9hr/.N9ZhPUXwtBVIAndHuBt6',
                                    'roles'    => ['ROLE_MEMBER'],
                                ],
                            ]
                        );

                        // for some extra checks: is account enabled, locked, expired, etc.
                        $userChecker = new UserChecker();

                        $defaultEncoder = new BCryptPasswordEncoder(13);

                        $encoders = [
                            User::class       => $defaultEncoder,
                            FrontendUser::class       => $defaultEncoder,
                        ];

                        // an array of password encoders (see below)
                        $encoderFactory = new EncoderFactory($encoders);

                        $daoProvider = new DaoAuthenticationProvider(
                            $userProvider,
                            $userChecker,
                            $this->providerKey,
                            $encoderFactory
                        );

                        $authenticatedToken = $daoProvider->authenticate($unauthenticatedToken);

                        var_dump($authenticatedToken);

                        $session = System::getContainer()->get('session');

                        $session->set('_security_'.$this->providerKey, serialize($authenticatedToken));
                        $session->save();


                        //$cookie = System::getContainer()->get('cookie');
                        //$cookie = new Cookie($session->getName(), $session->getId());


                        //print_r($daoProvider->authenticate($unauthenticatedToken));

//
//                        var_dump($this->getUser()); exit;
//

//                        $b = $guardHandler->authenticateUserAndHandleSuccess(
//                            $authenticatedToken->getUser(),          // the User object you just created
//                            $request,
//                            $daoProvider, // authenticator whose onAuthenticationSuccess you want to use
//                            'main'          // the name of your firewall in security.yaml
//                        );

                        //var_dump(System::getContainer()->get('security.authorization_checker'));

//                        var_dump($b);
                        #var_dump($authenticatedToken);

                        // var_dump(System::getContainer()->get('contao.security.token_checker')->hasFrontendUser());

                        $loggedIn = $candidate->id;
                    }
                }
            }
        }

        return new JsonResponse($loggedIn);
    }

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *