Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this community
Anybody can ask a question
Anybody can answer
The best answers are voted up and rise to the top
Asked
Viewed
12 times
i have an app that sends username and password to a php script. This script checks that a user exists on Drupal 8 with username and password entered but does not log the user. I need the user to log in. Can someone help me? thanks
Follows script code
use DrupaluserUserAuthInterface;
use DrupalCoreDrupalKernel;
use SymfonyComponentHttpFoundationRequest;
// Boot Drupal.
$autoloader = require __DIR__ . '/autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
$kernel->boot();
// Recupero Nome utente e password
$nome_ut = $_POST('nome');
$pass_ut = $_POST('pwd');
// effettuo il controllo
$user_auth = Drupal::service('user.auth');
$user_storage = Drupal::entityTypeManager()->getStorage('user');
$accounts = $user_storage->loadByProperties(('name' => $nome_ut, 'status' => 1));
$account = reset($accounts);
if ($account) {
if ($user_auth->authenticate($nome_ut, $pass_ut))
{
// The credentials are correct.
$id = $user_auth->authenticate($nome_ut, $pass_ut);
print ("Accesso riuscito!");
// Force session start if we don't already have a session.
$session = Drupal::service('session');
if (!$session->isStarted()) {
$session->migrate();
}
if (Drupal::currentUser()->isAuthenticated()) {
// This user is logged in.
print ("Utente Loggato");
} else {
// This user is not logged in.
print ("Utente non Loggato");
}
}
}
Could you use a rest endpoint? Because this is already handled by drupal core. See for example this or this
Otherwise I think you’re just missing user_login_finalize
after your check if the user is logged in.
user_login_finalize($user);
//Eventually redirect the user somewhere
$user_destination = Drupal::destination()->get();
$response = new RedirectResponse($user_destination);
$response->send();
Not the answer you’re looking for? Browse other questions tagged 8 or ask your own question.
default
