Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @file
- * Contains DrupalremoteuserControllerRemoteUserController
- */
- namespace DrupalremoteuserController;
- use DrupalCoreControllerControllerBase;
- use DrupalCoreFormFormState;
- use DrupalCoreEntity;
- use DrupaluserController;
- use SymfonyComponentHttpFoundationJsonResponse;
- class RemoteUserController extends ControllerBase
- {
- public function login() {
- $form_state = (new FormState())->setValues($_POST);
- Drupal::formBuilder()->submitForm('DrupaluserFormUserLoginForm', $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 DrupaluserEntityUser $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 ) );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement