token-session

1.0.0 • Public • Published

token-session

Token-session is a node.js framework for managing sessions without cookies or other externals elements, specially designed for REST services, time limited code validations and others UID with expirations application, with or without data.

Session data is stored server-side.

Inspired by express-session, token-session is compatible with the session store implementations of express-session like connect-redis, connect-mongo, express-mysql-session, session-memory-store, etc.

session-memory-store is the default storage. Note that it can only be used in a single node of node.js, not being suitable for clusters.

If you do not know which storage to use, Redis can be a good alternative.

For a list of stores, see compatible session stores.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install token-session

API

var TokenSession = require('token-session');
var tokenSession = new TokenSession({options});

options

token-session accepts these properties in the options object.

genid

Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID. The function is given req as the first argument if you want to use some value attached to req when generating the ID.

The default value is a function which uses the uid-safe library to generate IDs.

NOTE be careful to generate unique IDs so your sessions do not conflict.

var tokenSession = new TokenSession({
  genid: function(req) {
    return genuuid() // use UUIDs for session IDs
  },
  ...
});

autoTouch

If true, TokenSession.touch () is automatically invoked when TokenSession.get () is invoked

The default value is true,

store

The session store instance. Defaults is instance of session-memory-store.

For a list of stores, see compatible session stores.

Example for connect-redis:

var tokenSession = new TokenSession({
  autoTouch: true,
  store: new RedisStore({
    host: '127.0.0.1',
    ttl: 60,
    logErrors: true,
    prefix: 'tokensess:',
    pass: 'if established'
  })
});
hackttl

here description

token-session Methods

TokenSession.new(data, callback)

Create a new session with the given data. The new session ID is obtained in the callback result object.
The callback should be called as callback(error, result), being result = {sid, data}

let sessionData = {
  name:'jhon', 
  count:0
};
 
tokenSession.new(sessionData, (err, result) => {
  if (!err) {
    //Get the session ID!
    let sid = result.sessionId;
    
    //Get stored data (matches sessionData.)
    let data = result.data;   
    ...
 
  } else {
    // Deal with the error
  }
});

TokenSession.get(sid, callback)

Fetch session data by the given sid.
The callback should be called as callback(err, data) once the session has been set in the store.

 
tokenSession.get(sid, (err, data) => {
  if (!err) {
    // Do something with data object
    // Following the above example:
    // data.name
    // data.count
 
  } else {
    // Deal with the error
    
  }
});

Notice that if option.autoTouch is true then session Id is also touched.

TokenSession.getNtouch(sid, callback)

Fetch session data by the given sid and touches it.
The callback should be called as callback(err, data) once the session has been set in the store.

Notice that if option.autoTouch is true get and getNtouch are the same.

 
tokenSession.getNtouch(sid, (err, data) => {
  if (!err) {
    // Do something with data object
    // Following the above example:
    // data.name
    // data.count
 
  } else {
    // Deal with the error
    
  }
});

TokenSession.set(sid, data, callback)

Update the stored session data associated with the given sid with the given data object.
The callback should be called as callback(error) once the data has been set in the store.

tokenSession.set(sid, data);

or

tokenSession.set(sid, data, (err) => {
    if (err) {
      ...
    } else {
      ...
    }
}); 

TokenSession.destroy(sid, callback)

Destroys the session and once complete, the callback will be invoked.

tokenSession.destroy(function(err) {
  // cannot access session here
})

TokenSession.regenerate(sid, session, callback)

To regenerate the session simply invoke the method. Once complete, a new SID and Session instance will be initialized and the callback will be invoked.

tokenSession.regenerate(function(err, newSid) {
  // will have a new session here
})

TokenSession.touch(sid, session, callback)

Update the session period by adding a option.ttl time.

Notice that set(...) and getNtouch(...) call automatically this method.

Also, if option.autoTouch is true (default value) then get(...) touch the sid too.

So, Typically is not necessary to call this method, except if some of the above methods are not invoked for a long time.

token-session Extended Methods

Since the session store implementation of Express does not support sessions with different ttl and the fact that being compatible with these implementations is one of the objectives of this module, token-session performs a hack in order to implement the following methods without having to modify those stores implementations.

Note: This hack and therefore the following methods were tested only with this stores: connect-redis, connect-mongo, express-mysql-session, session-memory-store

For other session store implementation you can provide your own hack function using option.hackttl when create the token-session object.

TokenSession.newWttl(data, ttl, callback)

Create a new session with the given data and specific ttl (time to live in seconds). The new session ID is obtained in the callback result object.

Sometimes it is necessary to create a sessions with different ttl depending on the data or the purpose.

The callback should be called as callback(error, result), being result = {sid, data}

let sessionData = {
  name:'jhon', 
  count:0
};
 
let ttl = 600; //10 minutes.
 
tokenSession.newWttl(sessionData, ttl, (err, result) => {
  if (!err) {
    //Get the session ID!
    let sid = result.sessionId;
    
    //Get stored data (matches sessionData.)
    let data = result.data;   
    ...
 
  } else {
    // Deal with the error
  }
});

TokenSession.setWttl(sid, session, ttl, callback)

Update the stored session data associated with the given sid, ttl (time to live in seconds) and data object.
The callback should be called as callback(error) once the data has been set in the store.

tokenSession.setWttl(sid, data);

or

tokenSession.setWttl(sid, data, (err) => {
    if (err) {
      ...
    } else {
      ...
    }
}); 

Session Store Implementation

Every session store must be an EventEmitter and implement specific methods. The following methods are the list of required, recommended, and optional.

  • Required methods are ones that this module will always call on the store.
  • Recommended methods are ones that this module will call on the store if available.
  • Optional methods are ones this module does not call at all, but helps present uniform stores to users.

For an example implementation view the connect-redis repo.

store.all(callback)

Optional

This optional method is used to get all sessions in the store as an array. The callback should be called as callback(error, sessions).

store.destroy(sid, callback)

Required

This required method is used to destroy/delete a session from the store given a session ID (sid). The callback should be called as callback(error) once the session is destroyed.

store.clear(callback)

Optional

This optional method is used to delete all sessions from the store. The callback should be called as callback(error) once the store is cleared.

store.length(callback)

Optional

This optional method is used to get the count of all sessions in the store. The callback should be called as callback(error, len).

store.get(sid, callback)

Required

This required method is used to get a session from the store given a session ID (sid). The callback should be called as callback(error, session).

The session argument should be a session if found, otherwise null or undefined if the session was not found (and there was no error). A special case is made when error.code === 'ENOENT' to act like callback(null, null).

store.set(sid, session, callback)

Required

This required method is used to upsert a session into the store given a session ID (sid) and session (session) object. The callback should be called as callback(error) once the session has been set in the store.

store.touch(sid, session, callback)

Recommended

This recommended method is used to "touch" a given session given a session ID (sid) and session (session) object. The callback should be called as callback(error) once the session has been touched.

This is primarily used when the store will automatically delete idle sessions and this method is used to signal to the store the given session is active, potentially resetting the idle timer.

Compatible Session Stores

The following modules implement a session store that is compatible with this module. Please make a PR to add additional modules :)

★ aerospike-session-store A session store using Aerospike.

★ cassandra-store An Apache Cassandra-based session store.

★ cluster-store A wrapper for using in-process / embedded stores - such as SQLite (via knex), leveldb, files, or memory - with node cluster (desirable for Raspberry Pi 2 and other multi-core embedded devices).

★ connect-azuretables An Azure Table Storage-based session store.

★ connect-cloudant-store An IBM Cloudant-based session store.

★ connect-couchbase A couchbase-based session store.

★ connect-datacache An IBM Bluemix Data Cache-based session store.

★ connect-db2 An IBM DB2-based session store built using ibm_db module.

★ connect-dynamodb A DynamoDB-based session store.

★ connect-loki A Loki.js-based session store.

★ connect-ml A MarkLogic Server-based session store.

★ connect-mssql A SQL Server-based session store.

★ connect-monetdb A MonetDB-based session store.

★ connect-mongo A MongoDB-based session store.

★ connect-mongodb-session Lightweight MongoDB-based session store built and maintained by MongoDB.

★ connect-pg-simple A PostgreSQL-based session store.

★ connect-redis A Redis-based session store.

★ connect-memcached A memcached-based session store.

★ connect-memjs A memcached-based session store using memjs as the memcached client.

★ connect-session-knex A session store using Knex.js, which is a SQL query builder for PostgreSQL, MySQL, MariaDB, SQLite3, and Oracle.

★ connect-session-sequelize A session store using Sequelize.js, which is a Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL.

★ express-mysql-session A session store using native MySQL via the node-mysql module.

★ express-oracle-session A session store using native oracle via the node-oracledb module.

★ express-sessions: A session store supporting both MongoDB and Redis.

★ connect-sqlite3 A SQLite3 session store modeled after the TJ's connect-redis store.

★ documentdb-session A session store for Microsoft Azure's DocumentDB NoSQL database service.

★ express-nedb-session A NeDB-based session store.

★ express-session-cache-manager A store that implements cache-manager, which supports a variety of storage types.

★ express-session-level A LevelDB based session store.

★ express-etcd An etcd based session store.

★ fortune-session A Fortune.js based session store. Supports all backends supported by Fortune (MongoDB, Redis, Postgres, NeDB).

★ hazelcast-store A Hazelcast-based session store built on the Hazelcast Node Client.

★ level-session-store A LevelDB-based session store.

★ medea-session-store A Medea-based session store.

★ mssql-session-store A SQL Server-based session store.

★ nedb-session-store An alternate NeDB-based (either in-memory or file-persisted) session store.

★ sequelstore-connect A session store using Sequelize.js.

★ session-file-store A file system-based session store.

★ session-rethinkdb A RethinkDB-based session store.

License

MIT

Package Sidebar

Install

npm i token-session

Weekly Downloads

0

Version

1.0.0

License

MIT

Last publish

Collaborators

  • gustter