• Stars
    star
    557
  • Rank 79,968 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Track user connection state and inactivity in Meteor.

user-status

Build Status Total alerts Language grade: JavaScript Project Dependencies devDependencies 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.

User online states

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 user
  • lastLogin: information about the most recent login of the user, with the fields date, ipAddr, and userAgent.
  • 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 #80.

To make this available on the client, use a reactive cursor, such as by creating a publication on the server:

Meteor.publish("userStatus", function() {
  return Meteor.users.find({ "status.online": true }, { fields: { ... } });
});

or you can use this to do certain actions when users go online and offline.

Meteor.users.find({ "status.online": true }).observe({
  added: function(id) {
    // id just came online
  },
  removed: function(id) {
    // id just went offline
  }
});

You can use a reactive cursor to select online users in a client-side template helper:

Template.foo.usersOnline = function() {
  return Meteor.users.find({ "status.online": true })
};

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>
Template.userPill.labelClass = function() {
  if (this.status.idle)
    return "label-warning"
  else if (this.status.online)
    return "label-success"
  else
    return "label-default"
};

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 fields threshold (the amount of time before a user is counted as idle), interval (how often to check if a client has gone idle), and idleOnBlur (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.

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:

import SimpleSchema from 'simpl-schema';

const userSchema = new SimpleSchema({
    status: {
        type: Object,
        optional: true,
    },
    'status.lastLogin': {
        type: Object,
        optional: true,
    },
    'status.lastLogin.date': {
        type: Date,
        optional: true,
    },
    'status.lastLogin.ipAddr': {
        type: String,
        optional: true,
    },
    'status.lastLogin.userAgent': {
        type: String,
        optional: true,
    },
    'status.idle': {
        type: Boolean,
        optional: true,
    },
    'status.lastActivity': {
        type: Date,
        optional: true,
    },
    'status.online': {
        type: Boolean,
        optional: true,
    },
});

// attaching the Schema to Meteor.users will extend it
Meteor.users.attachSchema(userSchema);

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.

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.

More Repositories

1

meteor-autoform

AutoForm is a Meteor package that adds UI components and helpers to easily create basic forms with automatic insert and update events, and automatic reactive validation.
JavaScript
1,439
star
2

Meteor-CollectionFS

Reactive file manager for Meteor
JavaScript
1,051
star
3

meteor-collection2

A Meteor package that extends Mongo.Collection to provide support for specifying a schema and then validating against that schema when inserting and updating.
JavaScript
1,024
star
4

meteor-roles

Authorization package for Meteor, compatible with built-in accounts packages
JavaScript
920
star
5

meteor-simple-schema

Meteor integration package for simpl-schema
JavaScript
920
star
6

meteor-collection-hooks

Meteor Collection Hooks
JavaScript
657
star
7

ground-db

GroundDB is a thin layer providing Meteor offline database and methods
JavaScript
569
star
8

meteor-publish-composite

Meteor.publishComposite provides a flexible way to publish a set of related documents from various collections using a reactive join
JavaScript
553
star
9

raix-push

DEPRECATED: Push notifications for cordova (ios, android) browser (Chrome, Safari, Firefox)
JavaScript
515
star
10

meteor-tabular

Reactive datatables for large or small datasets
JavaScript
363
star
11

meteor-autocomplete

Client/server autocompletion designed for Meteor's collections and reactivity.
CoffeeScript
350
star
12

meteor-scss

Node-sass wrapped to work with meteor.
JavaScript
311
star
13

meteor-partitioner

Transparently divide a single meteor app into several different instances shared between different groups of users.
CoffeeScript
152
star
14

meteor-timesync

NTP-style time synchronization between server and client, and facilities to use server time reactively in Meteor applications.
JavaScript
118
star
15

meteor-link-accounts

Meteor link account package. based on this PR https://github.com/meteor/meteor/pull/1133
JavaScript
116
star
16

mongo-collection-instances

🗂 Meteor package allowing Mongo Collection instance lookup by collection name
JavaScript
73
star
17

Meteor-EventEmitter

Client and server event emitter
JavaScript
72
star
18

meteor-postcss

PostCSS for Meteor
JavaScript
68
star
19

meteor-mocha

A Mocha test driver package for Meteor 1.3+. This package reports server AND client test results in the server console and can be used for running tests on a CI server or locally.
JavaScript
67
star
20

meteor-elastic-apm

Meteor Elastic APM integration
JavaScript
57
star
21

organization

Discussions on organization of the organization 🎩
41
star
22

meteor-schema-index

Control some MongoDB indexing with schema options
JavaScript
38
star
23

meteor-publication-collector

Test a Meteor publication by collecting its output.
JavaScript
33
star
24

meteor-collection-extensions

Safely and easily extend the (Meteor/Mongo).Collection constructor with custom functionality.
JavaScript
31
star
25

stratosphere

Meteor private package server
JavaScript
28
star
26

meteor-method-hooks

JavaScript
26
star
27

meteor-autoform-select2

Custom select2 input type for AutoForm
JavaScript
25
star
28

meteor-autoform-bs-datepicker

Custom "bootstrap-datepicker" input type for AutoForm
JavaScript
25
star
29

react-router-ssr

Simple isomorphic React SSR for Meteor with subscribed data re-hydration
JavaScript
24
star
30

denormalize

Simple denormalization for Meteor
JavaScript
20
star
31

meteor-autoform-bs-datetimepicker

Custom bootstrap-datetimepicker input type with timezone support for AutoForm
JavaScript
17
star
32

meteor-packages

Client for Meteor Package Server API
JavaScript
14
star
33

Packosphere

A Meteor package explorer for you, and if you are so inclined to help build it, by you.
TypeScript
13
star
34

meteor-schema-deny

Deny inserting or updating certain properties through schema options
JavaScript
12
star
35

check-npm-versions

Enforces "peer" npm dependencies in Meteor 1.3+ Atmosphere packages.
TypeScript
11
star
36

meteor-browser-tests

A helper package for Meteor test driver packages. Runs client tests in a headless browser.
JavaScript
11
star
37

template-package

Template package with CI and everything else to get started quickly with creating a new FOSS Meteor package.
JavaScript
10
star
38

meteor-stylus

A fork of meteor:stylus with mquandalle:stylus plugins
JavaScript
8
star
39

meteor-minifiers-autoprefix

JavaScript
6
star
40

meteor-autoform-bs-button-group-input

A Bootstrap button group theme for the "select-checkbox" and "select-radio" AutoForm input types
JavaScript
6
star
41

ground-minimax

Minimax is a thin layer for Meteor providing EJSON.minify and EJSON.maxify
JavaScript
6
star
42

meteor-typescript

Typescript compiler package
TypeScript
5
star
43

meteor-api-untethered

A collection of packages to make Meteor available to other environments.
JavaScript
5
star
44

awesome-meteor

Curated list of awesome Meteor.js things.
5
star
45

Meteor-EventState

DEPRECATED: Evented state
JavaScript
4
star
46

meteor-autoform-themes

Officially supported themes for aldeed:autoform
JavaScript
3
star
47

push

JavaScript
2
star