1

I've written a custom module for Drupal 8 to monitor user device location frequently. If a user goes out of an allowed zone boundary, I need to force logging the user out of the website. I created following files in the module folder (gps_test):

  1. File gps_test.info.yml
  2. File gps.js: JavaScript program to monitor the user device's GPS location.
  3. File gps_test.libraries.yml: Contains the gps.js library.
  4. File gps_test.module: Implements a hook to attach the JavaScript library on every page load.
function gps_test_page_attachments(array &$page) {
  $page['#attached']['library'][] = 'gps_test/gps';
}

How can I force the user being logged out (or prevent the user from using the website) from the gps.js library?

1 Answer 1

4

As @Tushar mentioned it, you can use the user_logout() function.

Simplest way I see is to log your user out with an AJAX call when your JS detects that the user needs to be logged out. Here is a basic example of how it can be done.

In your JS, you need to add:

Drupal.behaviors.logout= {
  attach: function(context, settings) {
    if(yourConditionToLogOutUserisMet) {
      $.ajax({
        url: "/log-me-out", // custom route to log current user out
        success: function(data) {
          // do whatever you want on success of your ajax call
        }
      });
    }
  }
}

Then, create your custom route in gps_test.routing.yml

gps_test.my_custom_log_out:
  path: '/log-me-out'
  defaults:
    _controller: '\Drupal\gps_test\Controller\MyLogOutController::logUserOut'
  requirements:
    _permission: 'access content'

And finally, create the route controller:

namespace Drupal\gps_test\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;


class MyLogOutController extends ControllerBase {
  function logUserOut() {
    if ($this->currentUser()->isAuthenticated()) {
      user_logout();

      return new JsonResponse([
        'message' => "Current user session has ended.",
      ], 200);
    }
  }  
}
3
  • 1
    Drupal calls should be avoided in classes. Controllers have a currentUser method. if ($this->currentUser()->isAuthenticated()) {.
    – leymannx
    Dec 29, 2021 at 9:42
  • There's also no view published content permission - you probably meant access content
    – Clive
    Dec 29, 2021 at 13:04
  • 1
    You are both right. I edited my answer to take your comments into account.
    – misterdidi
    Dec 29, 2021 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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