Skip to main content
5 of 8
more details
Yuseferi
  • 22.2k
  • 22
  • 118
  • 218

How to login user programmatically

I want to login user programmatically with custom controller. I want pass my data with $_POST to route (you suppose I pass data from mobile application) , then I want if user and pass is correct return true and else return false.

My Router

tcdev.login:
  path: '/tclogin'
  defaults:
    _controller: 'Drupal\tcdev\Controller\MYCenterController::login'
    _title: 'Login call back'
  requirements:
    _permission: 'access content'

my Controller

namespace  Drupal\tcdev\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyController extends ControllerBase{

    /**
     * \Drupal\user\UserAuth definition.
     *
     * @var \Drupal\user\UserAuth
     */
    protected $userAuth;

    /**
     * {@inheritdoc}
     */
    public function __construct(UserAuth $user_auth) {
        $this_>userAuth = $user_auth;
    }

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static(
            $container_>get('user.auth')
        );
    }



    }

    public function login(){
        $uid = $this_>userAuth_>authenticate($-POST['user'],$_POST['pass']);
        $acc = User::load($uid);

        //return new Response('Hi ' . $uid);
    }

}

but it return me TypeError: Argument 1 passed to Drupal\tcdev\Controller\MyController::__construct() must be an instance of Drupal\tcdev\Controller\UserAuth, instance of Drupal\user\UserAuth given, called in /Users/yms/Sites/devdesktop/gttc/modules/tcdev/src/Controller/MyController.php on line 32 in Drupal\tcdev\Controller\MyController_>__construct() (line 23 of modules/tcdev/src/Controller/MyController.php

where is my mistake?

Yuseferi
  • 22.2k
  • 22
  • 118
  • 218