├── .npmignore ├── .npmrc ├── .istanbul.yml ├── .travis.yml ├── HEADER.md ├── .gitignore ├── package.json ├── .github └── workflows │ └── test.yml ├── History.md ├── README.md ├── test ├── examples.test.js └── unit.test.js ├── index.js └── LICENSE /.npmignore: -------------------------------------------------------------------------------- 1 | vendor 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.istanbul.yml: -------------------------------------------------------------------------------- 1 | instrumentation: 2 | excludes: ['**/vendor/**'] 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "4" 4 | - "5" 5 | - "6" 6 | - "7" 7 | - "8" 8 | - "9" 9 | - "10" 10 | services: 11 | - "mongodb" 12 | script: "npm run-script test-travis" 13 | after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls" 14 | -------------------------------------------------------------------------------- /HEADER.md: -------------------------------------------------------------------------------- 1 | # connect-mongodb-session 2 | 3 | [MongoDB](http://mongodb.com)-backed session storage for [connect](https://www.npmjs.org/package/connect) and [Express](http://www.expressjs.com). Meant to be a well-maintained and fully-featured replacement for modules like [connect-mongo](https://www.npmjs.org/package/connect-mongo) 4 | 5 | [![Build Status](https://travis-ci.org/mongodb-js/connect-mongodb-session.svg?branch=master)](https://travis-ci.org/mongodb-js/connect-mongodb-session) [![Coverage Status](https://coveralls.io/repos/mongodb-js/connect-mongodb-session/badge.svg?branch=master)](https://coveralls.io/r/mongodb-js/connect-mongodb-session?branch=master) 6 | 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | 22 | # Dependency directory 23 | # Commenting this out is preferred by some people, see 24 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 25 | node_modules 26 | 27 | # Users Environment Variables 28 | .lock-wscript 29 | 30 | vendor 31 | 32 | package-lock.json 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "connect-mongodb-session", 3 | "version": "5.0.0", 4 | "description": "MongoDB session store for connect/express built by MongoDB", 5 | "keywords": [ 6 | "connect", 7 | "mongo", 8 | "mongodb", 9 | "session", 10 | "express" 11 | ], 12 | "author": "Valeri Karpov ", 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/mongodb-js/connect-mongodb-session.git" 16 | }, 17 | "dependencies": { 18 | "archetype": "0.13.x", 19 | "mongodb": "5.x || 6.x" 20 | }, 21 | "devDependencies": { 22 | "acquit": "1.0.5", 23 | "acquit-ignore": "0.1.0", 24 | "acquit-markdown": "0.1.0", 25 | "cookie": "0.3.1", 26 | "express": "4.17.0", 27 | "express-session": "1.17.0", 28 | "istanbul": "0.4.5", 29 | "mocha": "3.1.2", 30 | "sinon": "17.0.1", 31 | "strawman": "0.0.1", 32 | "superagent": "3.x" 33 | }, 34 | "main": "index.js", 35 | "scripts": { 36 | "docs": "acquit-markdown -r acquit-ignore -p './test/examples.test.js' -h './HEADER.md' > README.md", 37 | "test": "env NODE_PATH=../ ./node_modules/mocha/bin/mocha ./test/*.test.js", 38 | "test-travis": "env NODE_PATH=../ ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/*.test.js", 39 | "unit-coverage": "env NODE_PATH=../ ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/unit.test.js" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | pull_request: 4 | push: 5 | jobs: 6 | test: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | fail-fast: false 10 | matrix: 11 | node: [16, 18, 20] 12 | os: [ubuntu-20.04] 13 | mongodbNodeDriver: [5, 6] 14 | include: 15 | - os: ubuntu-20.04 16 | mongo-os: ubuntu2004 17 | mongo: 5.0.2 18 | name: Node ${{ matrix.node }} MongoDB ${{ matrix.mongo }} Node Driver ${{ matrix.mongodbNodeDriver }} 19 | steps: 20 | - uses: actions/checkout@v2 21 | 22 | - name: Setup node 23 | uses: actions/setup-node@v1 24 | with: 25 | node-version: ${{ matrix.node }} 26 | 27 | - run: npm install 28 | - run: npm install mongodb@${{ matrix.mongodbNodeDriver }} 29 | 30 | - name: Setup 31 | run: | 32 | wget -q https://downloads.mongodb.org/linux/mongodb-linux-x86_64-${{ matrix.mongo-os }}-${{ matrix.mongo }}.tgz 33 | tar xf mongodb-linux-x86_64-${{ matrix.mongo-os }}-${{ matrix.mongo }}.tgz 34 | mkdir -p ./data/db/27017 ./data/db/27000 35 | printf "\n--timeout 8000" >> ./test/mocha.opts 36 | ./mongodb-linux-x86_64-${{ matrix.mongo-os }}-${{ matrix.mongo }}/bin/mongod --fork --dbpath ./data/db/27017 --syslog --port 27017 37 | sleep 2 38 | mongod --version 39 | echo `pwd`/mongodb-linux-x86_64-${{ matrix.mongo-os }}-${{ matrix.mongo }}/bin >> $GITHUB_PATH 40 | 41 | - run: npm test 42 | -------------------------------------------------------------------------------- /History.md: -------------------------------------------------------------------------------- 1 | 5.0.0 / 2024-01-25 2 | ================== 3 | * BREAKING CHANGE: use MongoDB Node driver 6.x by default, retain support for MongoDB Node driver 5.x 4 | 5 | 4.0.0 / 2024-01-17 6 | ================== 7 | * BREAKING CHANGE: upgrade to MongoDB driver 5.x 8 | 9 | 3.1.1 / 2021-10-04 10 | ================== 11 | * fix: upgrade archetype -> 0.13.x 12 | 13 | 3.1.0 / 2021-08-28 14 | ================== 15 | * feat: add expirescolumn and expiresafterseconds for azure cosmos support #91 [MrSimonEmms](https://github.com/MrSimonEmms) 16 | 17 | 3.0.0 / 2021-07-19 18 | ================== 19 | * BREAKING CHANGE: upgrade to MongoDB driver 4.x for MongoDB 5.0 support #95 20 | 21 | 2.4.1 / 2020-08-17 22 | ================== 23 | * fix: upgrade archetype to remove dependency on standard-error #86 #84 24 | 25 | 2.4.0 / 2020-08-04 26 | ================== 27 | * fix: upgrade to mongodb@3.6 28 | 29 | 2.3.3 / 2020-06-10 30 | ================== 31 | * feat: support creating MongoDBStore without `new` #83 32 | 33 | 2.3.2 / 2020-05-19 34 | ================== 35 | * fix: bump archetype -> 0.11.x #82 [ThomasCrevoisier](https://github.com/ThomasCrevoisier) 36 | 37 | 2.3.1 / 2020-02-06 38 | ================== 39 | * fix: enable `useUnifiedTopology` connection option by default to suppress deprecation warning #77 [alpn](https://github.com/alpn) 40 | 41 | 2.3.0 / 2020-01-20 42 | ================== 43 | * fix: upgrade mongodb -> 3.5.x 44 | 45 | 2.2.0 / 2019-06-15 46 | ================== 47 | * chore: upgrade mongodb -> 3.2.x 48 | 49 | 2.1.1 / 2019-02-06 50 | ================== 51 | * fix: add back mistakenly removed databaseName parameter #66 #64 [ramicohen303](https://github.com/ramicohen303) 52 | 53 | 2.1.0 / 2019-02-05 54 | ================== 55 | * feat: add store.all #65 [itsinprog](https://github.com/itsinprog) 56 | 57 | 2.0.8 / 2019-02-03 58 | ================== 59 | * fix: use archetype to cast options 60 | 61 | 2.0.7 / 2019-01-23 62 | ================== 63 | * docs: replace assert with console.log() to make example copy/pastable #63 [Roeefl](https://github.com/Roeefl) 64 | 65 | 2.0.6 / 2018-12-04 66 | ================== 67 | * fix: use `deleteOne()` and `deleteMany()` instead of deprecated `remove()` #60 #59 [ramicohen303](https://github.com/ramicohen303) 68 | 69 | 2.0.5 / 2018-11-17 70 | ================== 71 | * fix: use `updateOne()` instead of deprecated `update()` #58 #57 [johannordin](https://github.com/johannordin) 72 | 73 | 2.0.4 / 2018-11-12 74 | ================== 75 | * fix: upgrade mongodb driver -> 3.1.8 and set `useNewUrlParser` by default #55 [ddtraceweb](https://github.com/ddtraceweb) 76 | 77 | 2.0.3 / 2018-06-06 78 | ================== 79 | * fix: expose store.client property so you can disconnect properly #52 80 | 81 | 2.0.2 / 2018-03-27 82 | ================== 83 | * fix: use client.db() syntax to support getting db name from URI with replica set #50 84 | 85 | 2.0.1 / 2018-03-13 86 | ================== 87 | * fix: pull databaseName from URI by default for backwards compat #51 #50 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # connect-mongodb-session 2 | 3 | [MongoDB](http://mongodb.com)-backed session storage for [connect](https://www.npmjs.org/package/connect) and [Express](http://www.expressjs.com). Meant to be a well-maintained and fully-featured replacement for modules like [connect-mongo](https://www.npmjs.org/package/connect-mongo) 4 | 5 | [![Build Status](https://travis-ci.org/mongodb-js/connect-mongodb-session.svg?branch=master)](https://travis-ci.org/mongodb-js/connect-mongodb-session) [![Coverage Status](https://coveralls.io/repos/mongodb-js/connect-mongodb-session/badge.svg?branch=master)](https://coveralls.io/r/mongodb-js/connect-mongodb-session?branch=master) 6 | 7 | 8 | 9 | # MongoDBStore 10 | 11 | 12 | This module exports a single function which takes an instance of connect 13 | (or Express) and returns a `MongoDBStore` class that can be used to 14 | store sessions in MongoDB. 15 | 16 | 17 | ## It can store sessions for Express 4 18 | 19 | 20 | If you pass in an instance of the 21 | [`express-session` module](http://npmjs.org/package/express-session) 22 | the MongoDBStore class will enable you to store your Express sessions 23 | in MongoDB. 24 | 25 | The MongoDBStore class has 3 required options: 26 | 27 | 1. `uri`: a [MongoDB connection string](http://docs.mongodb.org/manual/reference/connection-string/) 28 | 2. `databaseName`: the MongoDB database to store sessions in 29 | 3. `collection`: the MongoDB collection to store sessions in 30 | 31 | **Note:** You can pass a callback to the `MongoDBStore` constructor, 32 | but this is entirely optional. The Express 3.x example demonstrates 33 | that you can use the MongoDBStore class in a synchronous-like style: the 34 | module will manage the internal connection state for you. 35 | 36 | 37 | ```javascript 38 | var express = require('express'); 39 | var session = require('express-session'); 40 | var MongoDBStore = require('connect-mongodb-session')(session); 41 | 42 | var app = express(); 43 | var store = new MongoDBStore({ 44 | uri: 'mongodb://127.0.0.1:27017/connect_mongodb_session_test', 45 | collection: 'mySessions' 46 | }); 47 | 48 | // Catch errors 49 | store.on('error', function(error) { 50 | console.log(error); 51 | }); 52 | 53 | app.use(require('express-session')({ 54 | secret: 'This is a secret', 55 | cookie: { 56 | maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week 57 | }, 58 | store: store, 59 | // Boilerplate options, see: 60 | // * https://www.npmjs.com/package/express-session#resave 61 | // * https://www.npmjs.com/package/express-session#saveuninitialized 62 | resave: true, 63 | saveUninitialized: true 64 | })); 65 | 66 | app.get('/', function(req, res) { 67 | res.send('Hello ' + JSON.stringify(req.session)); 68 | }); 69 | 70 | server = app.listen(3000); 71 | ``` 72 | 73 | ## It throws an error when it can't connect to MongoDB 74 | 75 | 76 | You should pass a callback to the `MongoDBStore` constructor to catch 77 | errors. If you don't pass a callback to the `MongoDBStore` constructor, 78 | `MongoDBStore` will `throw` if it can't connect. 79 | 80 | 81 | ```javascript 82 | var express = require('express'); 83 | var session = require('express-session'); 84 | var MongoDBStore = require('connect-mongodb-session')(session); 85 | 86 | var app = express(); 87 | var store = new MongoDBStore( 88 | { 89 | uri: 'mongodb://bad.host:27000/connect_mongodb_session_test?connectTimeoutMS=10', 90 | databaseName: 'connect_mongodb_session_test', 91 | collection: 'mySessions' 92 | }, 93 | function(error) { 94 | // Should have gotten an error 95 | }); 96 | 97 | store.on('error', function(error) { 98 | // Also get an error here 99 | }); 100 | 101 | app.use(session({ 102 | secret: 'This is a secret', 103 | cookie: { 104 | maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week 105 | }, 106 | store: store, 107 | // Boilerplate options, see: 108 | // * https://www.npmjs.com/package/express-session#resave 109 | // * https://www.npmjs.com/package/express-session#saveuninitialized 110 | resave: true, 111 | saveUninitialized: true 112 | })); 113 | 114 | app.get('/', function(req, res) { 115 | res.send('Hello ' + JSON.stringify(req.session)); 116 | }); 117 | 118 | server = app.listen(3000); 119 | ``` 120 | 121 | ## It supports several other options 122 | 123 | 124 | There are several other options you can pass to `new MongoDBStore()`: 125 | 126 | 127 | ```javascript 128 | var express = require('express'); 129 | var session = require('express-session'); 130 | var MongoDBStore = require('connect-mongodb-session')(session); 131 | 132 | var store = new MongoDBStore({ 133 | uri: 'mongodb://127.0.0.1:27017/connect_mongodb_session_test', 134 | collection: 'mySessions', 135 | 136 | // By default, sessions expire after 2 weeks. The `expires` option lets 137 | // you overwrite that by setting the expiration in milliseconds 138 | expires: 1000 * 60 * 60 * 24 * 30, // 30 days in milliseconds 139 | 140 | // Lets you set options passed to `MongoClient.connect()`. Useful for 141 | // configuring connectivity or working around deprecation warnings. 142 | connectionOptions: { 143 | serverSelectionTimeoutMS: 10000 144 | } 145 | }); 146 | ``` 147 | 148 | ## Azure Cosmos MongoDB support 149 | 150 | 151 | It can support MongoDB instances inside Azure Cosmos. As Cosmos can only support 152 | time-based index on fields called `_ts`, you will need to update your configuration. 153 | Unlike in MongoDB, Cosmos starts the timer at the point of document creation so the 154 | `expiresAfterSeconds` should have the same value as `expires` - as `expires` is in 155 | milliseconds, the `expiresAfterSeconds` must equal `expires / 1000`. 156 | 157 | 158 | ```javascript 159 | 160 | var express = require('express'); 161 | var session = require('express-session'); 162 | var MongoDBStore = require('connect-mongodb-session')(session); 163 | 164 | var store = new MongoDBStore({ 165 | uri: 'mongodb://username:password@cosmosdb-name.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@cosmosdb-name@', 166 | databaseName: 'myDb', 167 | collection: 'mySessions', 168 | 169 | // Change the expires key name 170 | expiresKey: `_ts`, 171 | // This controls the life of the document - set to same value as expires / 1000 172 | expiresAfterSeconds: 60 * 60 * 24 * 14 173 | }); 174 | ``` 175 | -------------------------------------------------------------------------------- /test/examples.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var assert = require('assert'); 4 | var superagent = require('superagent'); 5 | var mongodb = require('mongodb'); 6 | 7 | /** 8 | * This module exports a single function which takes an instance of connect 9 | * (or Express) and returns a `MongoDBStore` class that can be used to 10 | * store sessions in MongoDB. 11 | */ 12 | describe('MongoDBStore', function() { 13 | var underlyingDb; 14 | var server; 15 | 16 | beforeEach(async function() { 17 | const client = await mongodb.MongoClient.connect( 18 | 'mongodb://127.0.0.1:27017/connect_mongodb_session_test', 19 | { serverSelectionTimeoutMS: 5000 } 20 | ); 21 | underlyingDb = client.db('connect_mongodb_session_test'); 22 | await client.db('connect_mongodb_session_test').collection('mySessions').deleteMany({}); 23 | }); 24 | 25 | afterEach(function() { 26 | server && server.close(); 27 | }); 28 | 29 | /** 30 | * If you pass in an instance of the 31 | * [`express-session` module](http://npmjs.org/package/express-session) 32 | * the MongoDBStore class will enable you to store your Express sessions 33 | * in MongoDB. 34 | * 35 | * The MongoDBStore class has 3 required options: 36 | * 37 | * 1. `uri`: a [MongoDB connection string](http://docs.mongodb.org/manual/reference/connection-string/) 38 | * 2. `databaseName`: the MongoDB database to store sessions in 39 | * 3. `collection`: the MongoDB collection to store sessions in 40 | * 41 | * **Note:** You can pass a callback to the `MongoDBStore` constructor, 42 | * but this is entirely optional. The Express 3.x example demonstrates 43 | * that you can use the MongoDBStore class in a synchronous-like style: the 44 | * module will manage the internal connection state for you. 45 | */ 46 | it('can store sessions for Express 4', async function() { 47 | var express = require('express'); 48 | var session = require('express-session'); 49 | var MongoDBStore = require('connect-mongodb-session')(session); 50 | 51 | var app = express(); 52 | var store = new MongoDBStore({ 53 | uri: 'mongodb://127.0.0.1:27017/connect_mongodb_session_test', 54 | collection: 'mySessions' 55 | }); 56 | // acquit:ignore:start 57 | 58 | store.on('connected', function() { 59 | store.client; // The underlying MongoClient object from the MongoDB driver 60 | assert.ok(store.client); 61 | assert.ok(store.db); 62 | }); 63 | // acquit:ignore:end 64 | 65 | // Catch errors 66 | store.on('error', function(error) { 67 | console.log(error); 68 | // acquit:ignore:start 69 | assert.ifError(error); 70 | assert.ok(false); 71 | // acquit:ignore:end 72 | }); 73 | 74 | app.use(require('express-session')({ 75 | secret: 'This is a secret', 76 | cookie: { 77 | maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week 78 | }, 79 | store: store, 80 | // Boilerplate options, see: 81 | // * https://www.npmjs.com/package/express-session#resave 82 | // * https://www.npmjs.com/package/express-session#saveuninitialized 83 | resave: true, 84 | saveUninitialized: true 85 | })); 86 | 87 | app.get('/', function(req, res) { 88 | res.send('Hello ' + JSON.stringify(req.session)); 89 | }); 90 | 91 | server = app.listen(3000); 92 | 93 | let count = await underlyingDb.collection('mySessions').countDocuments({}); 94 | assert.equal(0, count); 95 | 96 | let response = await superagent.get('http://127.0.0.1:3000'); 97 | assert.equal(1, response.headers['set-cookie'].length); 98 | var cookie = require('cookie').parse(response.headers['set-cookie'][0]); 99 | assert.ok(cookie['connect.sid']); 100 | count = await underlyingDb.collection('mySessions').countDocuments({}); 101 | assert.equal(count, 1); 102 | response = await superagent.get('http://127.0.0.1:3000').set('Cookie', 'connect.sid=' + cookie['connect.sid']); 103 | assert.ok(!response.headers['set-cookie']); 104 | await store.clear(); 105 | count = await underlyingDb.collection('mySessions').countDocuments({}); 106 | assert.equal(count, 0); 107 | }); 108 | 109 | /** 110 | * You should pass a callback to the `MongoDBStore` constructor to catch 111 | * errors. If you don't pass a callback to the `MongoDBStore` constructor, 112 | * `MongoDBStore` will `throw` if it can't connect. 113 | */ 114 | it('throws an error when it can\'t connect to MongoDB', function(done) { 115 | var express = require('express'); 116 | var session = require('express-session'); 117 | var MongoDBStore = require('connect-mongodb-session')(session); 118 | 119 | var app = express(); 120 | var numExpectedSources = 2; 121 | var store = new MongoDBStore( 122 | { 123 | uri: 'mongodb://bad.host:27000/connect_mongodb_session_test?serverSelectionTimeoutMS=100', 124 | databaseName: 'connect_mongodb_session_test', 125 | collection: 'mySessions' 126 | }, 127 | function(error) { 128 | // Should have gotten an error 129 | // acquit:ignore:start 130 | assert.ok(error); 131 | --numExpectedSources || done(); 132 | // acquit:ignore:end 133 | }); 134 | 135 | store.on('error', function(error) { 136 | // Also get an error here 137 | // acquit:ignore:start 138 | assert.ok(error); 139 | --numExpectedSources || done(); 140 | // acquit:ignore:end 141 | }); 142 | 143 | app.use(session({ 144 | secret: 'This is a secret', 145 | cookie: { 146 | maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week 147 | }, 148 | store: store, 149 | // Boilerplate options, see: 150 | // * https://www.npmjs.com/package/express-session#resave 151 | // * https://www.npmjs.com/package/express-session#saveuninitialized 152 | resave: true, 153 | saveUninitialized: true 154 | })); 155 | 156 | app.get('/', function(req, res) { 157 | res.send('Hello ' + JSON.stringify(req.session)); 158 | }); 159 | 160 | server = app.listen(3000); 161 | }); 162 | 163 | /** 164 | * There are several other options you can pass to `new MongoDBStore()`: 165 | */ 166 | it('supports several other options', function() { 167 | var express = require('express'); 168 | var session = require('express-session'); 169 | var MongoDBStore = require('connect-mongodb-session')(session); 170 | 171 | var store = new MongoDBStore({ 172 | uri: 'mongodb://127.0.0.1:27017/connect_mongodb_session_test', 173 | collection: 'mySessions', 174 | 175 | // By default, sessions expire after 2 weeks. The `expires` option lets 176 | // you overwrite that by setting the expiration in milliseconds 177 | expires: 1000 * 60 * 60 * 24 * 30, // 30 days in milliseconds 178 | 179 | // Lets you set options passed to `MongoClient.connect()`. Useful for 180 | // configuring connectivity or working around deprecation warnings. 181 | connectionOptions: { 182 | serverSelectionTimeoutMS: 10000 183 | } 184 | }); 185 | }); 186 | }); 187 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Archetype = require('archetype'); 4 | const EventEmitter = require('events').EventEmitter; 5 | const mongodb = require('mongodb'); 6 | 7 | const OptionsType = new Archetype({ 8 | uri: { 9 | $type: 'string', 10 | $required: true, 11 | $default: 'mongodb://127.0.0.1:27017/test' 12 | }, 13 | collection: { 14 | $type: 'string', 15 | $required: true, 16 | $default: 'sessions' 17 | }, 18 | connectionOptions: { 19 | $type: Object, 20 | $default: null 21 | }, 22 | expires: { 23 | $type: 'number', 24 | $required: true, 25 | $default: 1000 * 60 * 60 * 24 * 14 // 2 weeks 26 | }, 27 | idField: { 28 | $type: 'string', 29 | $required: true, 30 | $default: '_id' 31 | }, 32 | databaseName: { 33 | $type: 'string', 34 | $required: false, 35 | $default: null 36 | }, 37 | expiresKey: { 38 | $type: 'string', 39 | $required: true, 40 | $default: 'expires' 41 | }, 42 | expiresAfterSeconds: { 43 | $type: 'number', 44 | $required: true, 45 | $default: 0 46 | } 47 | }).compile('OptionsType'); 48 | 49 | /** 50 | * Returns a constructor with the specified connect middleware's Store 51 | * class as its prototype 52 | * 53 | * ####Example: 54 | * 55 | * connectMongoDBSession(require('express-session')); 56 | * 57 | * @param {Function} connect connect-compatible session middleware (e.g. Express 3, express-session) 58 | * @api public 59 | */ 60 | module.exports = function(connect) { 61 | const Store = connect.Store || connect.session.Store; 62 | 63 | const MongoDBStore = function(options, callback) { 64 | if (!(this instanceof MongoDBStore)) { 65 | return new MongoDBStore(options, callback); 66 | } 67 | const _this = this; 68 | this._emitter = new EventEmitter(); 69 | this._errorHandler = handleError.bind(this); 70 | this.client = null; 71 | this.db = null; 72 | 73 | if (typeof options === 'function') { 74 | callback = options; 75 | options = {}; 76 | } else { 77 | options = options || {}; 78 | } 79 | 80 | options = new OptionsType(options); 81 | 82 | Store.call(this, options); 83 | this.options = options; 84 | 85 | const connOptions = options.connectionOptions; 86 | const client = new mongodb.MongoClient(options.uri, connOptions); 87 | this.client = client; 88 | const db = options.databaseName == null ? 89 | client.db() : 90 | client.db(options.databaseName); 91 | this.db = db; 92 | this.collection = db.collection(this.options.collection); 93 | this.initialConnectionPromise = client.connect(). 94 | then(() => { 95 | const expiresIndex = {}; 96 | expiresIndex[options.expiresKey] = 1 97 | 98 | return this.collection. 99 | createIndex(expiresIndex, { expireAfterSeconds: options.expiresAfterSeconds }). 100 | catch(err => { 101 | const e = new Error('Error creating index: ' + err.message); 102 | return _this._errorHandler(e, callback); 103 | }); 104 | }).then(() => { 105 | process.nextTick(() => callback && callback()); 106 | this._emitter.emit('connected'); 107 | return client; 108 | }). 109 | catch(error => { 110 | var e = new Error('Error connecting to db: ' + error.message); 111 | _this._errorHandler(e, callback); 112 | if (callback == null) { 113 | throw e; 114 | } 115 | }); 116 | }; 117 | 118 | MongoDBStore.prototype = Object.create(Store.prototype); 119 | 120 | MongoDBStore.prototype._generateQuery = function(id) { 121 | const ret = {}; 122 | ret[this.options.idField] = id; 123 | return ret; 124 | }; 125 | 126 | MongoDBStore.prototype.get = function(id, callback) { 127 | const _this = this; 128 | 129 | this.collection. 130 | findOne(this._generateQuery(id)). 131 | then(session => { 132 | if (session) { 133 | if (!session.expires || new Date < session.expires) { 134 | return process.nextTick(() => callback(null, session.session)); 135 | } else { 136 | return _this.destroy(id, callback); 137 | } 138 | } else { 139 | return process.nextTick(() => callback()); 140 | } 141 | }). 142 | catch(error => { 143 | const e = new Error('Error finding ' + id + ': ' + error.message); 144 | return _this._errorHandler(e, callback); 145 | }); 146 | }; 147 | 148 | // new store.all() for all sessions 149 | 150 | MongoDBStore.prototype.all = function(callback) { 151 | const _this = this; 152 | 153 | if (!this.db) { 154 | return this._emitter.once('connected', function() { 155 | _this.all.call(_this, callback); 156 | }); 157 | } 158 | 159 | this.db.collection(this.options.collection). 160 | find({}).toArray(function(error, sessions) { 161 | if (error) { 162 | const e = new Error('Error gathering sessions'); 163 | return _this._errorHandler(e, callback); 164 | } else if (sessions) { 165 | if (sessions) { 166 | return callback(null, sessions); 167 | } 168 | } else { 169 | return callback(); 170 | } 171 | }); 172 | }; 173 | 174 | MongoDBStore.prototype.destroy = function(id, callback) { 175 | const _this = this; 176 | 177 | this.collection.deleteOne(this._generateQuery(id)). 178 | then(() => { 179 | process.nextTick(() => callback && callback()); 180 | }).catch(error => { 181 | const e = new Error('Error destroying ' + id + ': ' + error.message); 182 | return _this._errorHandler(e, callback); 183 | }); 184 | }; 185 | 186 | MongoDBStore.prototype.clear = function(callback) { 187 | const _this = this; 188 | 189 | this.collection.deleteMany({}). 190 | then(() => { 191 | process.nextTick(() => callback && callback()); 192 | }). 193 | catch(error => { 194 | const e = new Error('Error clearing all sessions: ' + error.message); 195 | return _this._errorHandler(e, callback); 196 | }); 197 | }; 198 | 199 | MongoDBStore.prototype.set = function(id, session, callback) { 200 | const _this = this; 201 | 202 | const sess = {}; 203 | for (const key in session) { 204 | if (key === 'cookie') { 205 | sess[key] = session[key].toJSON ? session[key].toJSON() : session[key]; 206 | } else { 207 | sess[key] = session[key]; 208 | } 209 | } 210 | 211 | const s = this._generateQuery(id); 212 | s.session = sess; 213 | if (session && session.cookie && session.cookie.expires) { 214 | s[this.options.expiresKey] = new Date(session.cookie.expires); 215 | } else { 216 | const now = new Date(); 217 | s[this.options.expiresKey] = new Date(now.getTime() + this.options.expires); 218 | } 219 | 220 | this.collection.updateOne(this._generateQuery(id), { $set: s }, { upsert: true }). 221 | then(() => { 222 | process.nextTick(() => callback && callback()); 223 | }).catch(error => { 224 | const e = new Error('Error setting ' + id + ' to ' + 225 | require('util').inspect(session) + ': ' + error.message); 226 | return _this._errorHandler(e, callback); 227 | }); 228 | }; 229 | 230 | MongoDBStore.prototype.on = function() { 231 | this._emitter.on.apply(this._emitter, arguments); 232 | }; 233 | 234 | MongoDBStore.prototype.once = function() { 235 | this._emitter.once.apply(this._emitter, arguments); 236 | }; 237 | 238 | return MongoDBStore; 239 | }; 240 | 241 | function handleError(error, callback) { 242 | if (this._emitter.listeners('error').length) { 243 | this._emitter.emit('error', error); 244 | } 245 | 246 | if (callback) { 247 | callback(error); 248 | } 249 | 250 | if (!this._emitter.listeners('error').length && !callback) { 251 | throw error; 252 | } 253 | } 254 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /test/unit.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const connectMongoDBSession = require('../'); 5 | const ee = require('events').EventEmitter; 6 | const mongodb = require('mongodb'); 7 | const sinon = require('sinon'); 8 | 9 | describe('connectMongoDBSession', function() { 10 | var StoreStub; 11 | 12 | afterEach(() => sinon.restore()); 13 | 14 | beforeEach(function() { 15 | StoreStub = function() {}; 16 | StoreStub.prototype = { connectMongoDB: 1 }; 17 | }); 18 | 19 | describe('options', function() { 20 | it('can specify uri', function(done) { 21 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 22 | var session = new SessionStore({ uri: 'mongodb://host:1111/db' }); 23 | assert.equal(session.options.uri, 'mongodb://host:1111/db'); 24 | assert.equal(session.options.idField, '_id'); 25 | done(); 26 | }); 27 | 28 | it('can specify collection', function(done) { 29 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 30 | var session = SessionStore({ collection: 'notSessions' }); 31 | assert.equal(session.options.uri, 'mongodb://127.0.0.1:27017/test'); 32 | assert.equal(session.options.collection, 'notSessions'); 33 | done(); 34 | }); 35 | 36 | it('can specify expires', function(done) { 37 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 38 | var session = new SessionStore({ expires: 25 }); 39 | assert.equal(session.options.uri, 'mongodb://127.0.0.1:27017/test'); 40 | assert.equal(session.options.expires, 25); 41 | done(); 42 | }); 43 | 44 | it('can specify idField', function(done) { 45 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 46 | var session = new SessionStore({ idField: 'sessionId' }); 47 | assert.equal(session.options.uri, 'mongodb://127.0.0.1:27017/test'); 48 | assert.deepEqual(session._generateQuery('1234'), { sessionId: '1234' }); 49 | done(); 50 | }); 51 | 52 | it('can specify databaseName', function(done) { 53 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 54 | var session = new SessionStore({ databaseName: 'other_db' }); 55 | assert.equal(session.options.databaseName, 'other_db'); 56 | done(); 57 | }); 58 | }); 59 | 60 | it('can get Store object from Express 3', function(done) { 61 | var SessionStore = connectMongoDBSession({ session: { Store: StoreStub } }); 62 | assert.ok(SessionStore.prototype.connectMongoDB); 63 | done(); 64 | }); 65 | 66 | it('specifying options is optional', function(done) { 67 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 68 | 69 | var session = new SessionStore(function(error) { 70 | assert.ifError(error); 71 | done(); 72 | }); 73 | assert.equal(session.options.uri, 'mongodb://127.0.0.1:27017/test'); 74 | }); 75 | 76 | it('uses default options and no callback if no args passed', function(done) { 77 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 78 | 79 | var session = new SessionStore(); 80 | assert.equal(session.options.uri, 'mongodb://127.0.0.1:27017/test'); 81 | 82 | session.on('connected', function() { 83 | done(); 84 | }); 85 | }); 86 | 87 | it('throws an error when connection fails and no callback', function(done) { 88 | sinon.stub(mongodb.MongoClient.prototype, 'connect').callsFake(() => { 89 | return Promise.reject(new Error('Cant connect')); 90 | }); 91 | 92 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 93 | 94 | var threw = false; 95 | try { 96 | new SessionStore(); 97 | } catch (error) { 98 | threw = true; 99 | assert.equal(error.message, 'Error connecting to db: Cant connect'); 100 | } 101 | 102 | done(); 103 | }); 104 | 105 | it('passes error to callback if specified', function(done) { 106 | sinon.stub(mongodb.MongoClient.prototype, 'connect').callsFake(() => { 107 | return Promise.reject(new Error('connect issues')); 108 | }); 109 | 110 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 111 | var numSources = 2; 112 | var store = new SessionStore(function(error) { 113 | assert.ok(error); 114 | --numSources || done(); 115 | }); 116 | store.once('error', function(error) { 117 | assert.ok(error); 118 | --numSources || done(); 119 | }); 120 | }); 121 | 122 | it('handles index errors', function(done) { 123 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 124 | 125 | sinon.stub(mongodb.Collection.prototype, 'createIndex').callsFake(() => { 126 | return Promise.reject(new Error('Index fail')); 127 | }); 128 | 129 | var session = new SessionStore(function(error) { 130 | assert.equal(error.message, 'Error creating index: Index fail'); 131 | done(); 132 | }); 133 | }); 134 | 135 | describe('get()', function() { 136 | it('gets the session', function(done) { 137 | const SessionStore = connectMongoDBSession({ Store: StoreStub }); 138 | 139 | var session = new SessionStore(); 140 | 141 | sinon.stub(session.collection, 'findOne').callsFake(() => { 142 | return Promise.resolve({ expires: new Date('2040-06-01T00:00:00.000Z'), session: { data: 1 } }); 143 | }); 144 | session.get('1234', function(error, session) { 145 | assert.ifError(error); 146 | assert.deepStrictEqual(session, { data: 1 }); 147 | done(); 148 | }); 149 | }); 150 | 151 | it('handles get() errors', function(done) { 152 | const SessionStore = connectMongoDBSession({ Store: StoreStub }); 153 | 154 | const session = new SessionStore(); 155 | sinon.stub(session.collection, 'findOne').callsFake(() => { 156 | return Promise.reject(new Error('fail!')); 157 | }); 158 | 159 | session.get('1234', function(error) { 160 | assert.ok(error); 161 | assert.equal(error.message, 'Error finding 1234: fail!'); 162 | done(); 163 | }); 164 | }); 165 | 166 | it('calls destroy() on stale sessions', function(done) { 167 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 168 | 169 | var session = new SessionStore(); 170 | sinon.stub(session.collection, 'findOne').callsFake(() => { 171 | return Promise.resolve({ expires: new Date('2011-06-01T00:00:00.000Z') }); 172 | }); 173 | sinon.stub(session.collection, 'deleteOne').callsFake(() => { 174 | return Promise.resolve(); 175 | }); 176 | 177 | session.get('1234', function(error, doc) { 178 | assert.ifError(error); 179 | assert.ok(!doc); 180 | assert.equal(session.collection.deleteOne.getCalls().length, 1); 181 | done(); 182 | }); 183 | }); 184 | 185 | it('returns empty if no session found', function(done) { 186 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 187 | 188 | var session = new SessionStore(); 189 | sinon.stub(session.collection, 'findOne').callsFake(() => { 190 | return Promise.resolve(null); 191 | }); 192 | 193 | session.get('1234', function(error, doc) { 194 | assert.ifError(error); 195 | assert.ok(!doc); 196 | done(); 197 | }); 198 | }); 199 | }); 200 | 201 | describe('destroy()', function() { 202 | it('reports driver errors', function(done) { 203 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 204 | 205 | var session = new SessionStore(); 206 | sinon.stub(session.collection, 'deleteOne') 207 | .callsFake(() => Promise.reject(new Error('roadrunners pachyderma'))); 208 | 209 | session.destroy('1234', function(error) { 210 | assert.ok(error); 211 | assert.equal(error.message, 'Error destroying 1234: roadrunners pachyderma'); 212 | done(); 213 | }); 214 | }); 215 | }); 216 | 217 | describe('set()', function() { 218 | it('converts expires to a date', function(done) { 219 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 220 | 221 | var session = new SessionStore(); 222 | 223 | sinon.stub(session.collection, 'updateOne').callsFake(() => { 224 | return Promise.resolve(null); 225 | }); 226 | var update = { 227 | test: 1, 228 | cookie: { expires: '2011-06-01T00:00:00.000Z' } 229 | }; 230 | session.set('1234', update, function(error) { 231 | assert.ifError(error); 232 | assert.equal(session.collection.updateOne.getCalls().length, 1); 233 | assert.ok(session.collection.updateOne.getCalls()[0].args[1].$set.expires instanceof Date); 234 | assert.equal(session.collection.updateOne.getCalls()[0].args[1].$set.expires.getTime(), 235 | new Date('2011-06-01T00:00:00.000Z').getTime()); 236 | done(); 237 | }); 238 | }); 239 | 240 | it('handles set() errors', function(done) { 241 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 242 | 243 | var session = new SessionStore(); 244 | sinon.stub(session.collection, 'updateOne').callsFake(() => { 245 | return Promise.reject(new Error('taco tuesday')); 246 | }); 247 | 248 | session.set('1234', {}, function(error) { 249 | assert.ok(error); 250 | assert.equal(error.message, 'Error setting 1234 to {}: taco tuesday'); 251 | done(); 252 | }); 253 | }); 254 | 255 | /** For backwards compatibility with connect-mongo */ 256 | it('converts cookies to JSON strings', function(done) { 257 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 258 | 259 | var session = new SessionStore(); 260 | 261 | sinon.stub(session.collection, 'updateOne').callsFake(() => { 262 | return Promise.resolve(null); 263 | }); 264 | var update = { 265 | test: 1, 266 | cookie: { toJSON: function() { return 'put that cookie down!'; } } 267 | }; 268 | session.set('1234', update, function(error) { 269 | assert.ifError(error); 270 | assert.equal(session.collection.updateOne.getCalls().length, 1); 271 | assert.equal( 272 | session.collection.updateOne.getCalls()[0].args[1].$set.session.cookie, 273 | 'put that cookie down!' 274 | ); 275 | done(); 276 | }); 277 | }); 278 | 279 | /** For backwards compatibility with connect-mongo */ 280 | it('unless they do not have a toJSON()', function(done) { 281 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 282 | 283 | var session = new SessionStore(); 284 | 285 | sinon.stub(session.collection, 'updateOne').callsFake(() => { 286 | return Promise.resolve(null); 287 | }); 288 | var update = { 289 | test: 1, 290 | cookie: { test: 2 } 291 | }; 292 | session.set('1234', update, function(error) { 293 | assert.ifError(error); 294 | assert.equal(session.collection.updateOne.getCalls().length, 1); 295 | assert.deepEqual( 296 | session.collection.updateOne.getCalls()[0].args[1].$set.session.cookie, 297 | { test: 2 } 298 | ); 299 | done(); 300 | }); 301 | }); 302 | }); 303 | 304 | describe('clear()', function() { 305 | it('clears the session store', function(done) { 306 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 307 | 308 | var session = new SessionStore(); 309 | sinon.stub(session.collection, 'deleteMany').callsFake(() => Promise.resolve()); 310 | 311 | session.clear(function(error) { 312 | assert.ifError(error); 313 | assert.ok(session.collection.deleteMany.calledOnce); 314 | assert.deepStrictEqual(session.collection.deleteMany.getCalls()[0].args[0], {}); 315 | done(); 316 | }); 317 | }); 318 | 319 | it('handles set() errors', function(done) { 320 | var SessionStore = connectMongoDBSession({ Store: StoreStub }); 321 | 322 | var session = new SessionStore(); 323 | sinon.stub(session.collection, 'deleteMany'). 324 | callsFake(() => Promise.reject(new Error('clear issue'))); 325 | 326 | session.clear(function(error) { 327 | assert.ok(error); 328 | assert.equal(error.message, 'Error clearing all sessions: clear issue'); 329 | done(); 330 | }); 331 | }); 332 | }); 333 | }); 334 | --------------------------------------------------------------------------------