Coder Social home page Coder Social logo

redis-sessions's Introduction

Redis Sessions

Redis-Sessions

This is a Node.js module to keep sessions in a Redis datastore and add some useful methods.

The main purpose of this module is to generalize sessions across application server platforms. We use nginx reverse proxy to route parts of a website to a Node.js server and other parts could be Python, Ruby, .net, PHP, Coldfusion or Java servers. You can then use rest-sessions (incompatible with version 4.0.0) to access the same sessions on all app servers via a simple REST interface.

If you use Express check out Connect-Redis-Sessions (incompatible with version 4.0.0) for a ready to use middleware.

!!! BREAKING CHANGES VERSION 4.0 !!!

Due to a change from callbacks to async/await, version 4.0.0 is incompatible with version 3.x or lower.
Migration-Guide.

connect-redis-sessions and rest-sessions are both incompatible with version 4.0.0.

Installation

npm install redis-sessions

Basics

  • Every session belongs to an app (e.g. webapp, app_cust123).
  • create: A session is created by supplying the app and an id (usually the unique id of the user). A token will be returned.
  • get: A session is queried with the app and token. This will refresh the ttl (timeout) of a session.
  • set: Additional data (key/value) can be stored in the session.
  • kill: A session can be killed with the app and token.
  • killall: All sessions of an app can be killed.

Additional methods

  • activity: Get the amount of active sessions of an app within the last n seconds.
  • soid: Get all sessions of a single id.
  • killsoid: Kill all sessions that belong to a single id. E.g. log out user123 on all devices.
  • soapp: Get an array of all sessions of an app which were active within the last n seconds.
  • Automatic cleanup of old sessions.

Performance

With Redis running on the same machine as the test script (run via npm test) on a 2018 MacBook Pro:

  • Creates 1000 sessions in around 140ms.
  • Gets those 1000 sessions and validates them in around 90ms.
  • Removes those 1000 sessions in 15ms.

Cache (optional setting)

Modern apps might also use a lot of requests while a user is active. This results in a lot of Redis requests to look up sessions. What's faster than an in-memory cache in Redis? An in-memory cache right in your app! When you enable caching you can speed up session lookups by a lot. Consider the following before you enable it:

How does the cache work

  • The reply to the get() method will be cached for the time specified in the cachetime option.
  • Every set() or kill* method will flush the cache.
  • The idle and r keys that will be returned will not change for cached sessions.

What would be a good value for the cachetime option?

If your sessions last for 24h and the average user-session is 20m. You might as well set the cachetime to around 30m. Consider the size of your session object that has to be kept in memory. Setting the cachetime lower is ok. Because after all it just takes a quick Redis request to fill your cache again.

Use via REST (This is currently not compatible with the latest version)

See rest-sessions (incompatible with version 4.0.0).

Use in Node.js

Initialize redis-sessions

import RedisSessions from "redis-sessions"
//
// Parameters for RedisSession:
//
// e.g. rs = new RedisSession({host:"192.168.0.20"});
//
// `port`: *optional* Default: `6379`. The Redis port.
// `host`, *optional* Default: `127.0.0.1`. The Redis host.
// `options`, *optional* Default: {}. Additional options. See: https://github.com/redis/node-redis/blob/master/docs/client-configuration.md
// `namespace`: *optional* Default: `rs`. The namespace prefix for all Redis keys used by this module.
// `wipe`: *optional* Default: `600`. The interval in seconds after which expired sessions are wiped. Only values `0` or greater than `10` allowed. Set to `0` to disable.
// `cachemax` (Number) *optional* Default: `5000`. Maximum number of sessions stored in the cache.
rs = new RedisSessions<{
  foo: string;
  unread_msg?: number;
  last_action?: string;
  birthday?: string;
}>();

rsapp = "myapp";

Create a session

Parameters:

  • app (String) The app id (namespace) for this session.
  • id (String) The user id of this user. Note: There can be multiple sessions for the same user id. If the user uses multiple client devices.
  • ip (String) IP address of the user. This is used to show all ips from which the user is logged in.
  • ttl (Number) optional The "Time-To-Live" for the session in seconds. Default: 7200.
  • d (Object) optional Additional data to set for this sessions. (see the "set" method). Default: {}
  • no_resave (Boolean) optional If set to true the session will not be refreshed on session use. Instead it will run out exactly after the defined ttl. Default: false
// Set a session for `user1001`

const resp = await rs.create({
  app: rsapp,
  id: "user1001",
  ip: "192.168.22.58",
  ttl: 3600,
  d: { 
    foo: "bar",
    unread_msgs: 34
  }
  });
  // resp should be something like 
  // {token: "r30kKwv3sA6ExrJ9OmLSm4Wo3nt9MQA1yG94wn6ByFbNrVWhcwAyOM7Zhfxqh8fe"}

Notes:

  • You might want to store this token in a cookie / localStorage / sessionStorage.
  • If you use Express check out Connect-Redis-Sessions (Currently incompatible with version 4.0.0).
  • As long as the ttl isn't reached this token can be used to get the session object for this user.
  • Remember that a user (user1001 in this case) might have other sessions.
  • If you want to limit the number of sessions a user might have you can use the soid (sessions of id) method to find other sessions of this user or the killsoid (Kill sessions of id) method to kill his other sessions first.

Update and add some more data to an existing session

const resp = await rs.set({
  app: rsapp,
  token: "r30kKwv3sA6ExrJ9OmLSm4Wo3nt9MQA1yG94wn6ByFbNrVWhcwAyOM7Zhfxqh8fe",
  d: {
    unread_msgs: 12,
    last_action: "/read/news",
    birthday: "2013-08-13"
  }});
  /*
  resp contains the session with the new values:

  {
    "id":"user1001",
    "r": 1,
    "w": 2,
    "idle": 1,
    "ttl": 7200, 
    "d":{
      "foo": "bar",
      "unread_msgs": 12,
      "last_action": "/read/news",
      "birthday": "2013-08-13"
    }
  }
  */

Note: The key foo that we didn't supply in the set command will not be touched. See Set/Update/Delete details for details on how to remove keys.

Get a session for a token

const resp= await rs.get({
  app: rsapp,
  token: "r30kKwv3sA6ExrJ9OmLSm4Wo3nt9MQA1yG94wn6ByFbNrVWhcwAyOM7Zhfxqh8fe"});
  /*
  resp contains the session:

  {  
    "id":"user1001",
    "r": 2,  // The number of reads on this token
    "w": 2,  // The number of writes on this token
    "idle": 21,  // The idle time in seconds.
    "ttl": 7200, // Timeout after 7200 seconds idle time
    "d":{
      "foo": "bar",
      "unread_msgs": 12,
      "last_action": "/read/news",
      "birthday": "2013-08-13"
    }
  }

  */

Set/Update/Delete

Set/Update/Delete parameters by supplying app, token and some data d.
The d object contains a simple key/value list where values
can be string, number, boolean or null.
To remove keys set them to null, keys that are not supplied will not be touched.

const resp = await rs.set({
  app: rsapp,
  token: "r30kKwv3sA6ExrJ9OmLSm4Wo3nt9MQA1yG94wn6ByFbNrVWhcwAyOM7Zhfxqh8fe",
  d: {
      "unread_msgs": null
      "last_action": "/read/msg/2121"
  }});
  /*
  resp contains the session with modified values:

  {
    "id":"user1001",
    "r": 2,
    "w": 3,
    "idle": 1,
    "ttl": 7200, 
    "d":{
      "last_action": "/read/msg/2121",
      "birthday": "2013-08-13",
      "foo": "bar"
    }
  }
  */

Kill

Kill a single session by supplying app and token:

const resp = await rs.kill({
  app: rsapp,
  token: "r30kKwv3sA6ExrJ9OmLSm4Wo3nt9MQA1yG94wn6ByFbNrVWhcwAyOM7Zhfxqh8fe"});
  /*
  resp contains the result:

  {kill: 1}
  */

Note: If {kill: 0} is returned the session was not found.

Activity

Query the amount of active session within the last 10 minutes (600 seconds). Note: Multiple sessions from the same user id will be counted as one.

const resp = await rs.activity({
  app: rsapp,
  deltaTime: 600
  });
  /*
  resp contains the activity:

  {activity: 12}
  */

Sessions of App

Get all sessions of an app there were active within the last 10 minutes (600 seconds).

const resp = await rs.soapp({
  app: rsapp,
  deltaTime: 600
  });
  /*
  resp contains the sessions:

  {
    sessions: [
      {
        id: 'someuser123',
        r: 1,
        w: 1,
        ttl: 30,
        idle: 0,
        ip: '127.0.0.2'
      },
      {
        id: 'anotheruser456',
        r: 4,
        w: 2,
        ttl: 7200,
        idle: 24,
        ip: '127.0.0.1'
      }
    ]
  }
  */

Sessions of Id

Get all sessions within an app that belong to a single id. This would be all sessions of a single user in case he is logged in on different browsers / devices.

const resp = await rs.soid({
  app: rsapp,
  id: "bulkuser_999"
  });
  /*
  resp contains the sessions:

  {
    sessions: [
      {
        id: 'bulkuser_999',
        r: 1,
        w: 1,
        ttl: 30,
        idle: 0,
        ip: '127.0.0.2'
      },
      {
        id: 'bulkuser_999',
        r: 1,
        w: 1,
        ttl: 7200,
        idle: 0,
        ip: '127.0.0.1'
      }
    ]
  }
  */

Kill all sessions of an id

Kill all sessions of an id within an app:

const resp = rs.killsoid({app: rsapp, id: 'bulkuser_999'});
  /*
  resp contains the result:

  {kill: 2} // The amount of sessions that were killed
  */

Killall

Kill all sessions of an app:

const resp = await rs.killall({app: rsapp});
  /*
  resp contains the result:

  {kill: 12} // The amount of sessions that were killed
  */

Ping

Ping the redis server

const resp = await rs.ping();
  /*
  resp contains the result:

  "PONG"
  */

Tests

Before running Test you need to build the js files (npm run build) and have a redis server running.

Typescript Pitfalls !!!

  • If you do not specify a d object in create and only partially set it using the set function, be aware that get may return a session with a defined d object that is missing properties of the supplied type.
  • The set function only lets you delete optional keys.
  • If you use an Record<string,...> as the Generic Type you wont be able to delete properties with the set function. If you don`t have an more defined data type use the any type and cast your returned objects.
  • If you define your type as an empty object or only have optional parameters giving an empty object for d will still trow an error at runtime.

CHANGELOG

See CHANGELOG.md

More Node.js and Redis projects?

Check out my projects which are based on Node.js and Redis as a datastore:

If you run a Redis server and currently use Amazon SQS or a similar message queue you might as well use this fast little replacement. Using a shared Redis server multiple Node.js processes can send / receive messages.

  • Lightweight: Just Redis. Every client can send and receive messages via a shared Redis server.
  • Guaranteed delivery of a message to exactly one recipient within a messages visibility timeout.
  • No security: Like memcached. Only for internal use in trusted environments.
  • Similar to Amazon SQS (with some differences)
  • Optional RESTful interface via REST-rsmq
  • and more...

A Node.js helper library to make tagging of items in any legacy database (SQL or NoSQL) easy and fast. Redis is used to store tag-item associations and to allow fast queries and paging over large sets of tagged items.

  • Maintains order of tagged items
  • Unions and intersections while maintaining the order
  • Counters for each tag
  • Fast paging over results with limit and offset
  • Optional RESTful interface via REST-tagging
  • Read more...

The MIT License (MIT)

Copyright ยฉ 2013 Patrick Liess, http://www.tcs.de

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the โ€œSoftwareโ€), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED โ€œAS ISโ€, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

redis-sessions's People

Contributors

de3lo avatar smrchy avatar tomhaigh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

redis-sessions's Issues

Shutdown method needed.

Suggestion:

Capture the wipe interval id created during setInterval() and provide a quit(), shutdown(), stop() or similarly named method that clears the wipe interval using clearInterval(this.wipeIntervalId); and gracefully closes the Redis client using this.redis.quit().

Math.random() to create tokens

I was looking at the source code and noticed the use of Math.random to create tokens, I couldn't help but think that this could be a potential security issue, please correct me if I'm wrong.
Also, would you consider accepting a pull request where the token creation is refactored to use uid-safe?

Where does TTL get used?

Hello

I specify a TTL on the create() method, but I cannot see where it gets used within redis itself. All the keys that get created in redis have a TTL of "none".

image

redis-session::quit should clear the wipe interval too

Hi!

In quit function, redis.quit is called but if a wipe interval was set at the beginning, a clearInterval should be called also.

Not doing so, can lead to unexpected behaviors. In AWS lambda, for example, a still active interval cause the lambda to fail all the time (timeout). When you resolve a lambda, all interval and remaining connections must be put to an end.

When I call redis-session quit method, I expect all events, connections and intervals to be stopped or removed.

I solve my problem by setting wipe to 0. But it took my a while to find out what caused the timeout.

Have a good day!

how to connect using password

Hello,

I'm stuck for two days to solve this.
redis-sessions working fine with default redis configuration.

Then I have my redis "requirepass" active in my /etc/redis/redis.conf
now redis-sessions can't connect to redis server
Here is my example code:

var RedisSessions = require("redis-sessions");

var port = 6379,
    host = 'MY-HOST-IP',
    mypass = 'MY-PASSWORD';

var rs = new RedisSessions(port, host,{password:mypass});

and I tried so many ways but still can not connect. :(

Can someone guide me how to connect redis-sessions using password?

Thank you

Token invalidFormat: Invalid token format

Big fan btw ... great work!

I am trying to kill the session and token looks absolutely identical to the token created when establishing the session. The only difference in output is <64 character token> (without double marks) vs. "<64 charactoer token>" (with double marks) ... typeof for both is "string" so I assume this is not the problem. Here is the output:

Logon:
Type of token: string
Session token created: 57HHvT77x27odh3INVqdP87jOLf0uJkeKlpiMsEvh7eSSM8TAWQaTOgZidcxcajy

Logout:
Type of token: string
"57HHvT77x27odh3INVqdP87jOLf0uJkeKlpiMsEvh7eSSM8TAWQaTOgZidcxcajy"

Error: invalidFormat: Invalid token format

Any idea what this could be please?

Big thanks!

Function for auth is needed

In some case, the 'auth' function provided by the node_redis is needed to connect to the redis server. Please provide an API for doing that, thank you.
I think the code can be the following:

RedisSessions.prototype.auth = function(pass){
this.redis.auth(pass);
}
I tested this code and it's work for me

Allow any string as ID

currently an id cannot be an email. Only alphanumeric characters are allowed.

Change the validator to allow any string up to 128 (increase from 64 characters).

Doesn't support node 4.0 or greater

log:

npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No README data
/
> [email protected] install /Users/danillo/dev/sbs/sbs/ums/node_modules/redis-sessions/node_modules/hiredis
> node-gyp rebuild

  CC(target) Release/obj.target/hiredis-c/deps/hiredis/sds.o
  CC(target) Release/obj.target/hiredis-c/deps/hiredis/read.o
  LIBTOOL-STATIC Release/hiredis-c.a
  CXX(target) Release/obj.target/hiredis/src/hiredis.o
In file included from ../src/hiredis.cc:3:
In file included from ../src/reader.h:4:
In file included from ../node_modules/nan/nan.h:74:
In file included from ../node_modules/nan/nan_new.h:181:
../node_modules/nan/nan_implementation_12_inl.h:172:66: error: too many arguments to function
      call, expected at most 2, have 4
  return v8::Signature::New(v8::Isolate::GetCurrent(), receiver, argc, argv);
         ~~~~~~~~~~~~~~~~~~                                      ^~~~~~~~~~
/Users/danillo/.node-gyp/4.2.1/include/node/v8.h:4675:3: note: 'New' declared here
  static Local<Signature> New(
  ^
In file included from ../src/hiredis.cc:3:
In file included from ../src/reader.h:4:
../node_modules/nan/nan.h:165:25: error: redefinition of '_NanEnsureLocal'
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:160:25: note: previous definition is here
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Handle<T> val) {
                        ^
../node_modules/nan/nan.h:253:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent())));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure
      [with T = v8::Primitive]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:258:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(v8::Null(v8::Isolate::GetCurrent())));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure
      [with T = v8::Primitive]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:263:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent())));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure
      [with T = v8::Boolean]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:268:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(v8::False(v8::Isolate::GetCurrent())));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure
      [with T = v8::Boolean]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:500:13: error: no member named 'smalloc' in namespace 'node'
    , node::smalloc::FreeCallback callback
      ~~~~~~^
../node_modules/nan/nan.h:511:12: error: no matching function for call to 'New'
    return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
           ^~~~~~~~~~~~~~~~~
/Users/danillo/.node-gyp/4.2.1/include/node/node_buffer.h:31:40: note: candidate function not
      viable: no known conversion from 'uint32_t' (aka 'unsigned int') to 'enum encoding' for
      3rd argument
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/danillo/.node-gyp/4.2.1/include/node/node_buffer.h:43:40: note: candidate function not
      viable: 2nd argument ('const char *') would lose const qualifier
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/danillo/.node-gyp/4.2.1/include/node/node_buffer.h:28:40: note: candidate function not
      viable: requires 2 arguments, but 3 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate, size_t length);
                                       ^
/Users/danillo/.node-gyp/4.2.1/include/node/node_buffer.h:36:40: note: candidate function not
      viable: requires 5 arguments, but 3 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
In file included from ../src/hiredis.cc:3:
In file included from ../src/reader.h:4:
../node_modules/nan/nan.h:515:12: error: no viable conversion from
      'v8::MaybeLocal<v8::Object>' to 'v8::Local<v8::Object>'
    return node::Buffer::New(v8::Isolate::GetCurrent(), size);
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/danillo/.node-gyp/4.2.1/include/node/v8.h:210:7: note: candidate constructor (the
      implicit copy constructor) not viable: no known conversion from
      'v8::MaybeLocal<v8::Object>' to 'const v8::Local<v8::Object> &' for 1st argument
class Local {
      ^
/Users/danillo/.node-gyp/4.2.1/include/node/v8.h:210:7: note: candidate constructor (the
      implicit move constructor) not viable: no known conversion from
      'v8::MaybeLocal<v8::Object>' to 'v8::Local<v8::Object> &&' for 1st argument
class Local {
      ^
/Users/danillo/.node-gyp/4.2.1/include/node/v8.h:214:13: note: candidate template ignored:
      could not match 'Local' against 'MaybeLocal'
  V8_INLINE Local(Local<S> that)
            ^
/Users/danillo/.node-gyp/4.2.1/include/node/v8.h:326:13: note: candidate template ignored:
      could not match 'S *' against 'v8::MaybeLocal<v8::Object>'
  V8_INLINE Local(S* that)
            ^
In file included from ../src/hiredis.cc:3:
In file included from ../src/reader.h:4:
../node_modules/nan/nan.h:522:26: error: no member named 'Use' in namespace 'node::Buffer'
    return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
           ~~~~~~~~~~~~~~^
../node_modules/nan/nan.h:1339:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex)
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure
      [with T = v8::Function]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:1354:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(node::MakeCallback(
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure
      [with T = v8::Value]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:1427:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(handle->Get(NanNew(key)).As<v8::Object>());
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure
      [with T = v8::Object]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
13 errors generated.
make: *** [Release/obj.target/hiredis/src/hiredis.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/danillo/.nvm/versions/node/v4.2.1/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 15.0.0
gyp ERR! command "/Users/danillo/.nvm/versions/node/v4.2.1/bin/node" "/Users/danillo/.nvm/versions/node/v4.2.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/danillo/dev/sbs/sbs/ums/node_modules/redis-sessions/node_modules/hiredis
gyp ERR! node -v v4.2.1
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN optional dep failed, continuing [email protected]

IPv6 not compatible when creating a session

ip = req.headers['x-forwarded-for'] or req.connection.remoteAddress or req.socket.remoteAddress or req.connection.socket.remoteAddress

The IP I get is ::ffff:127.0.0.1

This causes an issue with the package saying it's not a valid IP format.

Is it possible to specify a timeout before failure?

In case the redis server cannot be reached, it would be useful to specify a timeout. Sessions being an important part of an application (prerequisite before processing a request), a short response time is crucial to a good user experience.

Being able to set a short timeout (e.g. a few seconds) would ensure an app's reactivity, instead of having to wait an undecided amount of time.

Feature: Optional caching of Redis replies

Some quick thoughts about a new possible feature:

In an environment with tens of thousand of simultaneous session requests per second it might be helpful to cache session replies for a short time.

For example an app could load the home screen and then issue 10 ajax requests to a single server. Each of those 10 requests would have to validate the session in Redis. Instead only the first session could be read from Redis. The other 10 would be served from in-memory cache in the Node app.

This has some consequences to the returned session data:

  • idle, and r keys will be the same for all cached replies. They won't be increased in Redis. So for short running sessions this could mean a valid session will be returned even if it has expired already. r will now reflect the real number of times a session was read from Redis.
  • Changes to the session (updating of session data d or killing of a session) should result in a cache expiry. This could be achieved with a pub/sub channel for all connected redis-session clients.

Those changes would make hundreds of thousands or possibly millions of sessions per second possible and reduce the load on a Redis server considerably.

Make `d` optional

Within connect-redis-sessions i create sessions by simply upgrade them with a user_id.
In this case i'll have no additional data to set as d.

So if i do not supply a d i'll get an [missingParameter: No d supplied] Error.
If i set d={} i'll get an [invalidValue: d must containt at least one key.] Error.

Support for sentinel

I tried the library and it worked as expected for storing sessions using a single instance of redis. But unfortunately, it does not support sentinel. Is it possible to add sentinel support to the library ?

Increase tokens ttl

Hello,
First, nice work for redis-session, it makes my day ;)
However, how can i do to increase session's TTL ? Or another way to extend user's sessions ?

Allow `d` in create method

When creating a new session the d parameter should be allowed. This makes it possible to set data when creating a session.

Data not deleting from redis

Even though my TTL time passed way my session data are not getting cleared and not getting removed from session.

Sessions are not deleted after expiration

I've set ttl for session 1000 seconds, after 1000 seconds session expired. when I make .get request to get session it returned an empty object. It is fine, but session is not deleted from redis server. Is it possible to set to delete sessions after expiration?

Does redis-sessions install correctly on Windows 7?

I get some big red errors when I run "npm install redis-sessions" on Windows. One problem is that I might need to install Redis on Windows first, and I didn't do that. I guess I don't understand why I would need to install locally, but that could be the problem...HOWEVER, if I do need to install Redis first, PLEASE indicate that on this GitHub page.

right now I am following these instructions to install Redis on Windows:
https://github.com/rgl/redis/downloads

In any case, as it stands now -
the errors I get in order of appearance are: C1083, C2054, C2085, C2143.

It says that it cannot open include file: 'sys/socket.h'

here is the output from the command line:

screenshot 2015-01-05 23 34 15

Retrieve all current active sessions

I want to retrieve all current sessions (that have not expired). I see we have the "soapp" but that has a "dt" parameter that implies a time period of activity? Perhaps I am misunderstanding what "dt" is for but it appears to be to allow you to filter sessions to get only those that have actually done something within a time period. I want all sessions - even those that have been idle for a long time (but have not expired). Is the answer just to put a very big number in "dt" ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.