user-status
What's this do?
Keeps track of user connection data, such as IP addresses, user agents, and
client-side activity, and tracks this information in Meteor.users
as well as
some other objects. This allows you to easily see users that are online, for
applications such as rendering the users box below showing online users in green
and idle users in orange.
For a complete example of what can be tracked, including inactivity, IP addresses, and user agents, check out a demo app at http://user-status.meteor.com, or its source.
Install
Install using Meteor:
$ meteor add mizzao:user-status
Additionally, note that to read client IP addresses properly, you must set the
HTTP_FORWARDED_COUNT
environment variable for your app, and make sure that IP
address headers are forwarded for any reverse proxy installed in front of the
app. See the Meteor docs on this
for more details.
Basic Usage - Online State
This package maintains two types of status: a general user online flag in Meteor.users
, and some additional data for each session. It uses timesync to maintain the server's time across all clients, regardless of whether they have the correct time.
Meteor.users
receives a status
field will be updated automatically if the user logs in or logs out, closes their browser, or otherwise disconnects. A user is online if at least one connection with that userId
is logged in. It contains the following fields:
online
:true
if there is at least one connection online for this userlastLogin
: information about the most recent login of the user, with the fieldsdate
,ipAddr
, anduserAgent
.idle
:true
if all connections for this user are idle. Requires idle tracking to be turned on for all connections, as below.lastActivity
: if the user was idle, the last time an action was observed. This field is only available when the user is online and idle. It does not maintain the user's last activity in real time or a stored value indefinitely -lastLogin
is a coarse approximation to that. For more information, see https://github.com/Meteor-Community-Packages/meteor-user-status/issues/80.
To make this available on the client, use a reactive cursor, such as by creating a publication on the server:
1Meteor.publish("userStatus", function() { 2 return Meteor.users.find({ "status.online": true }, { fields: { ... } }); 3});
or you can use this to do certain actions when users go online and offline.
1Meteor.users.find({ "status.online": true }).observe({ 2 added: function(id) { 3 // id just came online 4 }, 5 removed: function(id) { 6 // id just went offline 7 } 8});
You can use a reactive cursor to select online users in a client-side template helper:
1Template.foo.usersOnline = function() { 2 return Meteor.users.find({ "status.online": true }) 3};
Making this directly available on the client allows for useful template renderings of user state. For example, with something like the following you get the picture above (using bootstrap classes).
<template name="userPill"> <span class="label {{labelClass}}">{{username}}</span> </template>
1Template.userPill.labelClass = function() { 2 if (this.status.idle) 3 return "label-warning" 4 else if (this.status.online) 5 return "label-success" 6 else 7 return "label-default" 8};
Advanced Usage and Idle Tracking
Client API
On the client, the UserStatus
object provides for seamless automatic monitoring of a client's idle state. By default, it will listen for all clicks and keypresses in window
as signals of a user's action. It has the following functions:
startMonitor
: a function taking an object with fieldsthreshold
(the amount of time before a user is counted as idle),interval
(how often to check if a client has gone idle), andidleOnBlur
(whether to count a window blur as a user going idle.) This function enables idle tracking on the client.stopMonitor
: stops the running monitor.pingMonitor
: if the automatic event handlers aren't catching what you need, you can manually ping the monitor to signal that a user is doing something and reset the idle monitor.isIdle
: a reactive variable signifying whether the user is currently idle or not.isMonitoring
: a reactive variable for whether the monitor is running.lastActivity
: a reactive variable for the last action recorded by the user (according to server time). Since this variable will be invalidated a lot and cause many recomputations, it's best only used for debugging or diagnostics (as in the demo).
For an example of how the above functions are used, see the demo.
Server API
The UserStatus.connections
(in-memory) collection contains information for all connections on the server, in the following fields:
_id
: the connection id.userId
: the user id, if the connection is authenticated.ipAddr
: the remote address of the connection. A user logged in from different places will have one document per connection.userAgent
: the user agent of the connection.loginTime
: if authenticated, when the user logged in with this connection.idle
:true
if idle monitoring is enabled on this connection and the client has gone idle.
startupQuerySelector (Optional)
On startup meteor-user-status
automatically resets all users to offline
and then marks each online
as connections are reestablished.
To customize this functionality you can use the startupQuerySelector
Meteor package option like this:
1 "packages": { 2 "mizzao:user-status": { 3 "startupQuerySelector": { "$or": [{ "status.online": true }, { "status.idle": { "$exists": true } }, { "status.lastActivity": { "$exists": true } }] } 4 } 5 }
The above example reduces server/database load during startup if you have a large number of users.
Usage with collection2
If your project is using aldeed:collection2
with a schema attached to Meteor.users
, you need to add the following items to the schema to allow modifications of the status:
1import SimpleSchema from 'simpl-schema'; 2 3const userSchema = new SimpleSchema({ 4 status: { 5 type: Object, 6 optional: true, 7 }, 8 'status.lastLogin': { 9 type: Object, 10 optional: true, 11 }, 12 'status.lastLogin.date': { 13 type: Date, 14 optional: true, 15 }, 16 'status.lastLogin.ipAddr': { 17 type: String, 18 optional: true, 19 }, 20 'status.lastLogin.userAgent': { 21 type: String, 22 optional: true, 23 }, 24 'status.idle': { 25 type: Boolean, 26 optional: true, 27 }, 28 'status.lastActivity': { 29 type: Date, 30 optional: true, 31 }, 32 'status.online': { 33 type: Boolean, 34 optional: true, 35 }, 36}); 37 38// attaching the Schema to Meteor.users will extend it 39Meteor.users.attachSchema(userSchema); 40
Events
The UserStatus.events
object is an EventEmitter
on which you can listen for connections logging in and out. Logging out includes closing the browser; reopening the browser will trigger a new login event. The following events are supported:
UserStatus.events.on("connectionLogin", function(fields) { ... })
fields
contains userId
, connectionId
, ipAddr
, userAgent
, and loginTime
.
UserStatus.events.on("connectionLogout", function(fields) { ... })
fields
contains userId
, connectionId
, lastActivity
, and logoutTime
.
UserStatus.events.on("connectionIdle", function(fields) { ... })
fields
contains userId
, connectionId
, and lastActivity
.
UserStatus.events.on("connectionActive", function(fields) { ... })
fields
contains userId
, connectionId
, and lastActivity
.
Check out https://github.com/mizzao/meteor-accounts-testing for a simple accounts drop-in that you can use to test your app - this is also used in the demo.
Startup selector
By default, the startup selector for resetting user status is {}
.
If you want to change that you can set the default selector in your settings.json file:
1{ 2 "packages": { 3 "mizzao:user-status": { 4 "startupQuerySelector": { 5 // your selector here, for example: 6 "profile.name": "admin" 7 } 8 } 9 } 10}
Testing
There are some Tinytest
unit tests that are used to test the logic in this package, but general testing with many users and connections is hard. Hence, we have set up a demo app (http://user-status.meteor.com) for testing that is also hosted as a proof of concept. If you think you've found a bug in the package, try to replicate it on the demo app and post an issue with steps to reproduce.
Contributing
See Contributing.md.