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);
}
}
}