2

This question already has an answer here:

i'm trying to build a Headless Drupal app with symfony, i'm stuck with login, i build a custom module for drupal 8 with four functions, (login,logout,register,login_status):

<?php

/**
 * @file
 * Contains \Drupal\remoteuser\Controller\RemoteUserController
 */

 namespace Drupal\remoteuser\Controller;

 use Drupal\Core\Controller\ControllerBase;
 use Drupal\Core\Form\FormState;
 use Drupal\Core\Entity;
 use Drupal\user\Controller;
 use Symfony\Component\HttpFoundation\JsonResponse;

class RemoteUserController extends ControllerBase
{
  public function login() {
    $form_state = (new FormState())->setValues($_POST);
    \Drupal::formBuilder()->submitForm('\Drupal\user\Form\UserLoginForm', $form_state);

    // Check for errors from the from
    if ($errors = $form_state->getErrors()) {
      // Return errors to notify the client.
      return new JsonResponse( array( 'error' => $errors ) );
    }
    else {
      // Return new user session to client.
      $uid = \Drupal::service('user.auth')->authenticate($_POST['name'], $_POST['pass']);
      $session_manager = \Drupal::service('session_manager');
      $session_id = $session_manager->getId();
      return new JsonResponse( array( 'uid' => $uid, 'session_id' => $session_id ) );
    }
  }

  public function register() {
    // Validate the e-mail address first.
    if (!\Drupal::service('email.validator')->isValid($_POST['mail'])) {
      return new JsonResponse( array( 'error' => 'Invalid e-mail address' ) );
    }

    // Create password if it was not provided.
    $password = $_POST['pass'] ? $_POST['pass'] : user_password();

    /** @var \Drupal\user\Entity\User $user */
    $user = entity_create('user', array(
      'name' => $_POST['name'],
      'mail' => $_POST['mail'],
      'pass' => $password,
    ));

    // Validate the object.
    $errors = $user->validate();

    if ($errors->count() > 0) {
      // Return errors to notify the client.
      return new JsonResponse( array( 'error' => $errors->__toString() ) );
    } else {
      // Save new user
      $user->save();
      // Return new user credentials
      return new JsonResponse( array( 'user' => $user->toArray() ) );
    }
  }

  public function logout() {
    $result = user_logout();

    return new JsonResponse($result);
  }

  public function login_status() {
    $uid = \Drupal::currentUser()->id();

    $session_manager = \Drupal::service('session_manager');
    $session_id = $session_manager->getId();

    return new JsonResponse( array( 'uid' => $uid, 'session_id' => $session_id ) );
  }
}

all working great except for login !, it authenticate and returns successfully the user, but when i check with login_status, it returns an anonymous user !!. but the magic is that when i test with Postman google chrome plugin, login_status returns successfully the logged in user !!, maybe the cookies are not handled correctly in symfony !! i tried also with Drupal 7 Rest services, same problem, the user is not logged in !!

marked as duplicate by Shawn Conn, Adrian Cid Almaguer, Scott Joudry, Krishna Mohan, No Sssweat Apr 6 '16 at 8:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • "Login" is not a REST operation. This is a Web Services operation. Anyway I have had trouble in the past trying to fake out the form builder service in PHPUnit tests. Every time I've tried form state is always reset. You're probably best off bypassing the Form and looking at what validateForm does on the user form these days. – mradcliffe Mar 30 '16 at 22:39
  • than why it's working with PostMan plugin ? – Fariss Abdo Mar 31 '16 at 9:59
2

Finally, it works :D, I'll just put this answer here to help how still don't know how to login user via my custom Web Services API, i had to manage the cookies from the frontend, I use symfony, after sending a POST request to /{endpoint}/user/login, and receive the response that will look like this:

{
    "sessid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
    "session_name": "SESS948facaca231cedd9a2a526239dcb6dc",
    "token": "icfD3CNT4r4QAlEGiYmqzez0MVmsPbAowVR8HtfaD4Y",
    "user": {
        "uid": "1",
        "name": "admin",
        "mail": "contact@headless.com",
        "theme": "",
        "signature": "",
        "signature_format": null,
        "created": "1459037019",
        "access": "1459439836",
        "login": 1459440402,
        "status": "1",
        "timezone": "Europe/Paris",
        "language": "",
        "picture": "0",
        "init": "contact@headless.com",
        "data": false,
        "roles": {
            "2": "authenticated user"
        }
    }
}

i create a cookie with (any name) and the value will be "session_name=sessid", don't forget the "=". and finally to see if the user is logged in, you need the token and the cookie that you created, send a POST request to {endpoint}/system/connect WITH this HEADERS:

X-CSRF-Token: token from the login response
Cookie: SESS948facaca231cedd9a2a526239dcb6dc=ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q (session_name=sessid)

and voila :D, you get a response like this:

{
    "sessid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
    "session_name": "SESS948facaca231cedd9a2a526239dcb6dc",
    "user": {
        "uid": "1",
        "name": "admin",
        "mail": "contact@headless.com",
        "theme": "",
        "signature": "",
        "signature_format": null,
        "created": "1459037019",
        "access": "1459440402",
        "login": "1459440402",
        "status": "1",
        "timezone": "Europe/Paris",
        "language": "",
        "picture": "0",
        "init": "contact@headless.com",
        "data": false,
        "sid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
        "ssid": "",
        "hostname": "127.0.0.1",
        "timestamp": "1459440402",
        "cache": "0",
        "session": "",
        "roles": {
            "2": "authenticated user"
        }
    }
}

i hope my answer help any one how is looking for how to login users via Drupal Services.

  • Hi Fariss..May you please add you full module code in git repo.. – vijay Feb 22 '17 at 14:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.