2

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?

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Gideon
  • 1,469
  • 2
  • 26
  • 57

2 Answers2

3

I have no idea about Apache Shiro but I can tell you how to get the session creation time.

It's pretty simple actually, there is a method called getCreationTime() in HttpSession. Here is the doc

You can invoke this method on the session attribute available in controllers. This will return the time in milliseconds as long.

Ashraf Purno
  • 1,065
  • 6
  • 11
3

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.

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121