Advertisement
Guest User

Untitled

a guest
Mar 30th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * @file
  5. * Contains DrupalremoteuserControllerRemoteUserController
  6. */
  7.  
  8. namespace DrupalremoteuserController;
  9.  
  10. use DrupalCoreControllerControllerBase;
  11. use DrupalCoreFormFormState;
  12. use DrupalCoreEntity;
  13. use DrupaluserController;
  14. use SymfonyComponentHttpFoundationJsonResponse;
  15.  
  16. class RemoteUserController extends ControllerBase
  17. {
  18. public function login() {
  19. $form_state = (new FormState())->setValues($_POST);
  20. Drupal::formBuilder()->submitForm('DrupaluserFormUserLoginForm', $form_state);
  21.  
  22. // Check for errors from the from
  23. if ($errors = $form_state->getErrors()) {
  24. // Return errors to notify the client.
  25. return new JsonResponse( array( 'error' => $errors ) );
  26. }
  27. else {
  28. // Return new user session to client.
  29. $uid = Drupal::service('user.auth')->authenticate($_POST['name'], $_POST['pass']);
  30. $session_manager = Drupal::service('session_manager');
  31. $session_id = $session_manager->getId();
  32. return new JsonResponse( array( 'uid' => $uid, 'session_id' => $session_id ) );
  33. }
  34. }
  35.  
  36. public function register() {
  37. // Validate the e-mail address first.
  38. if (!Drupal::service('email.validator')->isValid($_POST['mail'])) {
  39. return new JsonResponse( array( 'error' => 'Invalid e-mail address' ) );
  40. }
  41.  
  42. // Create password if it was not provided.
  43. $password = $_POST['pass'] ? $_POST['pass'] : user_password();
  44.  
  45. /** @var DrupaluserEntityUser $user */
  46. $user = entity_create('user', array(
  47. 'name' => $_POST['name'],
  48. 'mail' => $_POST['mail'],
  49. 'pass' => $password,
  50. ));
  51.  
  52. // Validate the object.
  53. $errors = $user->validate();
  54.  
  55. if ($errors->count() > 0) {
  56. // Return errors to notify the client.
  57. return new JsonResponse( array( 'error' => $errors->__toString() ) );
  58. } else {
  59. // Save new user
  60. $user->save();
  61. // Return new user credentials
  62. return new JsonResponse( array( 'user' => $user->toArray() ) );
  63. }
  64. }
  65.  
  66. public function logout() {
  67. $result = user_logout();
  68.  
  69. return new JsonResponse($result);
  70. }
  71.  
  72. public function login_status() {
  73. $uid = Drupal::currentUser()->id();
  74.  
  75. $session_manager = Drupal::service('session_manager');
  76. $session_id = $session_manager->getId();
  77.  
  78. return new JsonResponse( array( 'uid' => $uid, 'session_id' => $session_id ) );
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement