PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

[FIXED] How to login a user from the Controller in cakephp4? Using the authentication plugin

 March 11, 2022     authentication, cakephp, controller     No comments   

Issue

I build a application, that has a normal login with the Authentication plugin, and other form of login that happens in the controller. In cakephp3 we can do that with $this->Auth()->login , $this->Auth()->setUser, etc. But in cakephp4 the Authentication plugin doesn't have a $this->Authentication->login/setUser. The questions is how do i do that?.

I obtaing the user in the controller and i don't have any way to login that user.

I'm wondering if any of you have encounter this problem

This is my authentication service:

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
    {
        $service = new AuthenticationService();

        // Define where users should be redirected to when they are not authenticated
        $service->setConfig([
            'unauthenticatedRedirect' => Router::url([
                'prefix' => false,
                'plugin' => null,
                'controller' => 'Users',
                'action' => 'login',
            ]),
            'queryParam' => 'redirect',
        ]);

        $fields = [
            IdentifierInterface::CREDENTIAL_USERNAME => 'email',
            IdentifierInterface::CREDENTIAL_PASSWORD => 'password'
        ];
        // Load the authenticators. Session should be first.
        $service->loadAuthenticator('Authentication.Session');
        if ($request->getParam('action') == 'googleLogin') {
            $service->loadAuthenticator('Authentication.Form', [
                'fields' => $fields,
                'loginUrl' => Router::url([
                    'prefix' => false,
                    'plugin' => null,
                    'controller' => 'Users',
                    'action' => 'googleLogin',
                ]),
            ]);
        } else {
            $service->loadAuthenticator('Authentication.Form', [
                'fields' => $fields,
                'loginUrl' => Router::url([
                    'prefix' => false,
                    'plugin' => null,
                    'controller' => 'Users',
                    'action' => 'login',
                ]),
            ]);
        }
        // Load identifiers
        $service->loadIdentifier('Authentication.Password', compact('fields'));

        return $service;
    }

and this is the controller

$this->Authorization->skipAuthorization();

        $data = $this->request->getData();
        $email = $data['email'];

        $repository = new UserRepository($this->Users);
        $user = $repository->findUserByEmail($email);

        $response = $this->response;

        if (!empty($user)) {
            $response->withStatus(201);
            return $response;
        } else {
            $user = $this->Users->newEmptyEntity();
            $dataUser['username'] = $email;
            $dataUser['email'] = $email;
            $dataUser['password'] = 'esquemaPerfecto';
            $dataUser['role'] = 'cliente';
            $user = $this->Users->patchEntity($user, $dataUser);
            if ($this->Users->save($user)) {
                $this->Authentication->setUser($user);
                $sendEmail = new EmailHelper($dataUser['email'], 'Vehiculos de Primera mano Registro', 'Usted se ha registrado con exito en la pagina de Vehiculos de Primera Mano y su contraseƱa es ' . $dataUser['passwords']);
                $sendEmail->send();

                $response->withStatus(200);
                return $response;
            }
        }

        $response->withStatus(400);
        return $response;
    }

All ideas are welcome


Solution

According to Migration from the AuthComponent docs section

Any place you were calling AuthComponent::setUser(), you should now use setIdentity():

// Assume you need to read a user by access token
$user = $this->Users->find('byToken', ['token' => $token])->first();

// Persist the user into configured authenticators.
$this->Authentication->setIdentity($user);


Answered By - Yaroslav
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing