Git Product home page Git Product logo

connect-mysql's Introduction

connect-mysql

This is a simple MySQL backed session store for connect.

It uses the node-mysql module already installed in your project to establish and pool connections.

Upgrading

Changes introduced in v2.2 mean sessions stored in earlier versions are not backwards compatible with v2.2. It it recommended that you clear the session table; alternately sessions will be discarded with a warning message.

Options

  • table: the name of the database table that should be used for storing sessions. Defaults to 'sessions'
  • pool: a node-mysql connection pool or true if the store should instantiate its own pool
  • config: the configuration that will be passed to createConnection() or createPool() if pool is true
  • retries: how many times to retry connecting to the database before failing. Defaults to 3
  • keepalive: keep pooled connections open by periodically pinging them. Set to true to use the default interval of 30000 ms or provide a positive number to set your own. Defaults to true.
  • cleanup: a boolean specifying whether to enable the cleanup events. note that if this is disabled, cleanup will not take place at all and should be done externally. Sessions with an expiration time of 0 will always be ignored and should also be cleaned up externally.
  • secret: key that will be used to encrypt session data. If this option is not provided then data will be stored in plain text

Examples

Here are some example use cases to get your application up and running.

Default use case

Simple use case using the express framework & connect-session middleware with connect-mysql as the data store.

var express = require('express'), // express framework
    session = require('express-session'), // session middleware
    cookieParser = require('cookie-parser'), // cookie middleware
    MySQLStore = require('connect-mysql')(session), // mysql session store
    options = {
      config: {
        user: 'username', 
        password: 'password',
        database: 'databasename' 
      }
    },
    app = express();

app.use(cookieParser());

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: {
    httpOnly: false,
    secure: false,
    maxAge: 1000 * 60 * 60 * 24 * 3,
    expires: 1000 * 60 * 60 * 24 * 3
  },
  store: new MySQLStore(options) // Change the express session store
}));

app.get('/', function (req, res) {
  if (req.session.views) {
    req.session.views++
  } else {
    req.session.views = 1;
  }

  res.send('Hello world! '+req.session.views);
});
 
app.listen(3000, 'localhost');

Connection pooling example

For those MySQL installations that make use of pools the following examples are available.

  var mysql = require('mysql'),
      options = {
        pool: mysql.createPool({
          user: 'dbuser',
          password: 'dbpassword',
          database: 'db'
        })
      };

Or

var options = {
      pool: true,
      config: {
        user: 'dbuser', 
        password: 'dbpassword', 
        database: 'db' 
      }
    };

Ssession encryption example

This option enables transparent session encryption assisting

var options = {
      secret: 'thesessionsecret',
      config: {
        user: 'dbuser', 
        password: 'dbpassword', 
        database: 'db' 
      }
   };

contributing

Contributions are welcome & appreciated. Refer to the contributing document to help facilitate pull requests.

license

This software is licensed under the MIT License.

Nathan LaFreniere, Copyright (c) 2012 &Yet

connect-mysql's People

Contributors

danielsharvey avatar draconisnoctis avatar jas- avatar jeremiahlee avatar meefik avatar mjeffery avatar mobilesam avatar mscdex avatar nlf avatar paulomcnally avatar scottgonzalez 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

connect-mysql's Issues

Requires SUPER permissions

Apparently this requires SUPER permission on the mysql host as line 22 of connect-mysql.js has connection.query('SET GLOBAL event_scheduler = 1'); which doesn't work for a non-SUPER user.

Call for new maintainer

I don't use this module any more, so it's grown quite stale.. I've tried to continue merging pull requests, but I haven't really been paying any attention to it.

Anyone that would like to take over as the maintainer, let me know here and I'd be happy to add you to the repo and on npm.

Pooling

If I create a patch to take advantage of connection pooling will you merge it?

delete sessions - modify to support safe mode in mysql

Hi,

We should update the DELETE sessions query so that it works for mysql when set it to safe mode.
This is just an fyi for those folks running in to a similar problem...
something like this would do it:

'DELETE FROM `' + TableName + '` WHERE `sid` != 0 and `expires` > 0 and `expires` < UNIX_TIMESTAMP()';

Thanks,
Jatin

JSON.parse() exceptions with existing session data (pre v2.2)

When the sessions table contains sessions data saved prior to the update, the JSON.parse() throws an exception which breaks sessions restoration.

I suggest these exceptions should be caught and the session 'reset', perhaps with a warning.

This specific occurrence is a transitional issue but the exception should be handled in some manner.

Thoughts?

great start point but get / set is called too often

Great starting point, but when I put a simple console in the get / set functions its
called very often, even on a simple login page... Imaging if there would be 100 users..
Is this normal behavior?

connect mysql GET: ChZVe-srbodUH1s7xrjAFu1I
start login...
connect mysql SET: ChZVe-srbodUH1s7xrjAFu1I
session.js_unmodified session
connect mysql GET: ChZVe-srbodUH1s7xrjAFu1I
connect mysql GET: ChZVe-srbodUH1s7xrjAFu1I
connect mysql SET: ChZVe-srbodUH1s7xrjAFu1I
connect mysql GET: ChZVe-srbodUH1s7xrjAFu1I
connect mysql SET: ChZVe-srbodUH1s7xrjAFu1I
connect mysql SET: ChZVe-srbodUH1s7xrjAFu1I
session.js
_unmodified session
*session.js
_unmodified session
session.js
_unmodified session
connect mysql GET: ChZVe-srbodUH1s7xrjAFu1I
connect mysql SET: ChZVe-srbodUH1s7xrjAFu1I
*session.js
***unmodified session

Incompatible encrypted sessions with update

It seems the format of the encrypted session has changed since the last update, causing an error to be thrown if when the 'old' JSON formatted session is decrypted.

Since this is a breaking change, can we call this update version 3.0.0 instead of 2.1.3?

Error in cleanup query

I was finding that pooled session queries were being lost from the session pool.

It turns out that the cleanup query is wrong (has been wrong for a while :)) but the error was not reported due to the way the scheduling occurred.

The cleanup query references the field id whereas it should reference sid.

The error is:

error { Error: ER_BAD_FIELD_ERROR: Unknown column 'id' in 'field list'
    at Query.Sequence._packetToError (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/sequences/Sequence.js:47:14)
    at Query.ErrorPacket (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)
    at Protocol._parsePacket (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/Protocol.js:278:23)
    at Parser.write (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/Parser.js:76:12)
    at Protocol.write (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/Protocol.js:38:16)
    at Socket.<anonymous> (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/Connection.js:91:28)
    at Socket.<anonymous> (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/Connection.js:502:10)
    at Socket.emit (events.js:197:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:145:17)
    --------------------
    at Protocol._enqueue (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/Protocol.js:144:48)
    at PoolConnection.query (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/Connection.js:200:25)
    at /home/ovmp/apps/ov-manufacture-planning/node_modules/connect-mysql/lib/connect-mysql.js:216:20
    at execute (/home/ovmp/apps/ov-manufacture-planning/node_modules/connect-mysql/lib/connect-mysql.js:320:11)
    at /home/ovmp/apps/ov-manufacture-planning/node_modules/connect-mysql/lib/connect-mysql.js:334:22
    at Ping.onOperationComplete (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/Pool.js:111:5)
    at Ping.<anonymous> (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/Connection.js:502:10)
    at Ping._callback (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/Connection.js:468:16)
    at Ping.Sequence.end (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
    at Ping.Sequence.OkPacket (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/sequences/Sequence.js:92:8)
    at Protocol._parsePacket (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/Protocol.js:278:23)
    at Parser.write (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/Parser.js:76:12)
    at Protocol.write (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/protocol/Protocol.js:38:16)
    at Socket.<anonymous> (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/Connection.js:91:28)
    at Socket.<anonymous> (/home/ovmp/apps/ov-manufacture-planning/node_modules/mysql/lib/Connection.js:502:10)
    at Socket.emit (events.js:197:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:145:17)
  code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sqlMessage: "Unknown column 'id' in 'field list'",
  sqlState: '42S22',
  index: 0,
  sql:
   'DELETE FROM `sessions` WHERE id IN (SELECT temp.id FROM (SELECT `id` FROM `sessions` WHERE `expires` > 0 AND `expires` < UNIX_TIMESTAMP()) AS temp);' }

PR to follow.

Losing sessions prematurely?

I just switched over to connect-mysql (~0.4.0) from connect-mongo and noticed that I was getting logged out unpredictably.

Did some investigation and it looked like rows in the sessions table were disappearing. Looking at it a bit more it looks like the 'expires' column is being set to 0 and then I found this in connect-mysql:

var cleanupQuery = 'DELETE FROM `' + TableName + '` WHERE `expires` < UNIX_TIMESTAMP()';

I haven't had a chance to fully debug this but if I'm not mistaken it looks like maybe the cleanup query run every 15 minutes may be removing my sessions?

I'm using express v3.4.0. I know I can disable cleanup but I was wondering if there is something else going on here? Perhaps you're not expecting the expires column to be 0 ?

Anyway, I hope that's helpful. Let me know if you want me to provide more info.

Express 4.x compatible

hi , I tried to use your module with "express": "~4.0.0" , it gave the following error and crashed , works fine with express 3.x .

Error: Most middleware (like session) is no longer bundled with Express and must
 be installed separately. Please see https://github.com/senchalabs/connect#middleware.
    at Function.Object.defineProperty.get (C:\w\zbigo\node_modules\express\lib\express.js:89:13)
    at module.exports (C:\w\zbigo\node_modules\connect-mysql\lib\connect-mysql.js:19:24)
    at Object.<anonymous> (C:\w\zbigo\nsc.js:22:44)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\w\zbigo\https.js:20:11)
DEBUG: Program node https.js exited with code 8

the code used :

var express = require('express')            //http://expressjs.com
,app = express()
, _e_cookieParser=require('cookie-parser')    //https://github.com/expressjs/cookie-parser
, _e_expressSession=require('express-session')  //https://github.com/expressjs/session
, _e_expressSStore=require('connect-mysql')(express) //https://github.com/nlf/connect-mysql
, mysql = require('mysql')                      //https://github.com/felixge/node-mysql
, pool  = mysql.createPool(conf.db)
app.use(_e_cookieParser());
app.use(_e_expressSession({secret:'--mysecret--',store:new _e_expressSStore({pool:mspool})}));

relys on events

Many installations of MySQL distributed databases turn off events. As such, you cannot run the command in line 10:

CREATE EVENT IF NOT EXISTS sess_cleanup ON SCHEDULE EVERY 15 MINUTE DO DELETE FROM sessions WHERE expires < UNIX_TIMESTAMP()

Cipheriv warning in Node 8

When using connect-mysql in Node 8.9.3 I see following warning in the console:

(node:15214) Warning: Use Cipheriv for counter mode of aes-256-ctr

connect-mysql and sailsjs

By default sailsjs has options to store sessions in mongodb, redis or memory. But since I'm using MySQL I wanted to store the session also in MySQL.

I tried connect-mysql and in the end I managed to do it, but I had to make some little changes to the code.

First MySQLStore.prototype.query has this.config and this.mysql available at the top of the function, but not inside retry so I did what is also done with pool and initialized config and mysql as variables after pool = this pool.

When trying to log out my server crashed saying undefined is not a function. The culprit is also in MySQLStore.prototype.query, callback(null, value);. To fix that I wrapped it in an if (isFunction(callback)){}

I also have a patch and I hope I can attach it to a comment cause I can't now.

Does this work with Express 4?

I've been having trouble getting this to work with Express 4.12.3, and then I noticed there hasn't been any updates in over a year. Which got me thinking, does this library support Express 4?

Sequelize

I'm passing the Sequelize object to the client option. The queries works but the Sequelize uses a different event handler ( with success and error chained ). Do you plan to support it?

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.