Developer DevOps System Administrator Jahia 8

How to invalidate a user session

Question

How a user session can be invalidated, for example when a password is being reset?

Answer

The module distributed-sessions, freely available in Jahia 8, introduces some new possibilities.

Here is a sample Groovy script to invalidate a user session depending on a specific attribute:

def templateManagerService = org.jahia.osgi.BundleUtils.getOsgiService(org.jahia.services.templates.JahiaTemplateManagerService.class, null);
def jahiaModule = templateManagerService.getTemplatePackageById("distributed-sessions");
def instanceBean = jahiaModule.getContext().getBean("jahiaHazelcastInstanceBean");
def sessionsRepository = jahiaModule.getContext().getBean("sessionRepository");
def sessions = instanceBean.getInstance().getMap("spring:session:sessions")
for(def sessionTmp : sessions){
  log.info("test:"+sessionTmp);
  for(def attribute : sessionTmp.getValue().getAttributeNames()){
    log.info("  session:"+attribute);
  }
  def sessionValue = sessionTmp.getValue();
  def isImpersonating = sessionValue.getAttribute("impersonating_user")!=null;
  if(isImpersonating){
    sessionsRepository.delete(sessionTmp.getKey());
  }
}