Reputation: 209
I am trying to detect a period of user inactivity in my EmberJS application so that, after a certain duration I can call a session.inValidate
method and revoke their authentication.
The only resource I have been able to find is an article here which I was advised in an original question is out of date and doesn't use current Ember concepts.
The out-of-date article suggested adding a property to the App
object and updating the property on certain events like mousemove
but I was unable to find a location to set this property correctly in either app.js
or the config environment.
ember-concurrency was recommended but after looking at some of the documentation I still don't understand where such code fits in an EmberJS application structure.
Unfortunately I'm stuck at a point before I can give a code sample. Any advice is appreciated.
Edit: As per @hernanvicente excellent question, I am defining inactivity as 'no user input'. So no mousemove
or key press
events within X period
Upvotes: 3
Views: 524
Reputation: 18240
The hard question here is what activity actually means. Generally I would advise against your idea. There is no way to know if the user is actually still looking on your page.
However if you really want to do something after the user hasn't done something for some amount of time the interesting question is where to place your code.
You have multiple options here, but probably not the worst option would be to use the application controller. You could also use a service, but then you need to use that service somewhere to initialize it. You could also just use a component.
If you want to couple this to authentication you could consider to use the existing session
service.
However everything else is not really ember specific. You can just place some code in the application controllers init
hook and access document.addEventListener()
. Then you could just save a timestamp away and act accordingly.
To have a bit a nicer API for waiting you can utilize ember-concurrency
with a restartable
task:
didSomething: task(function * () {
yield timeout(1000); // number of miliseconds to wait
logout();
}).restartable(),
here logout()
will be called, after the task hasn't been called for 1 second. A nice visual demonstration about task concurrency and restarable
can be found here.
Here is an ember-twiddle showing a complete example.
Upvotes: 3