Search code examples
grailshttpsession

Get session creation time in Grails + Apache Shiro


There's this text Last seen: field in my application that shows for how long the current user is logged on the system (e.g. 5 seconds ago, 4 hours ago, 3 days ago, etc.). Now for me to do this, I need to determine either:

  • the time Apache Shiro performs the login; or
  • the time the current Grails Session has been created.

Then subtract it to the current time. But how can I access the creation time of either of the two? Or are there any better ways to achieve this not using the mentioned above?


Solution

  • In your controller action you can write like this:

    class MyController {
    
        // Considering this action is secured for logged in user only
        def foo() {
            long currentMillis = new Date().getTime()
            long sessionCreationMillis = session.getCreationTime()
    
            long loggedInFor = currentMillis - sessionCreationMillis
            println "User has been logged in for $loggedInFor miliseconds"
        }
    }
    

    Now, you got how long the user has been logged in (in milliseconds). Further, you can use the TimeUnit library to convert your milliseconds to other values.

    Or, you can also use any Javascript library like this if you are planning to do it on client side.