Skip to content

Commit

Permalink
Merge 8bdead0 into fb0edc1
Browse files Browse the repository at this point in the history
  • Loading branch information
byeokim committed Nov 4, 2019
2 parents fb0edc1 + 8bdead0 commit aa0e212
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 36 deletions.
93 changes: 63 additions & 30 deletions README.md
Expand Up @@ -41,7 +41,7 @@ In many circumstances, `connect-mongo` will not be the only part of your applica

Alternatively, you can configure `connect-mongo` to establish a new connection.

#### Re-use a Mongoose connection
#### Re-use an existing Mongoose connection

```js
const mongoose = require('mongoose');
Expand All @@ -61,7 +61,7 @@ app.use(session({
}));
```

#### Re-use a native MongoDB driver client (or a promise)
#### Re-use an existing native MongoDB driver client (or a promise)

In this case, you just have to give your `MongoClient` instance to `connect-mongo`.

Expand All @@ -70,17 +70,36 @@ In this case, you just have to give your `MongoClient` instance to `connect-mong
** There are many ways to create MongoClient.
** You should refer to the driver documentation.
*/

// Database name present in the connection string will be used
app.use(session({
store: new MongoStore({ client: clientInstance })
}));

// Explicitly specifying database name
app.use(session({
store: new MongoStore({
client: clientInstance,
dbName: 'test-app'
})
}));
```

Or just give a promise...

```js
// Database name present in the connection string will be used
app.use(session({
store: new MongoStore({ clientPromise: clientInstancePromise })
}));

// Explicitly specifying database name
app.use(session({
store: new MongoStore({
clientPromise: clientInstancePromise,
dbName: 'test-app'
})
}));
```

#### Create a new connection from a MongoDB connection string
Expand Down Expand Up @@ -210,34 +229,48 @@ const store = new MongoStore({
})
```

## More options

- `collection` Collection (default: `sessions`)
- `fallbackMemory` Fallback to `MemoryStore`. Useful if you want to use MemoryStore in some case, like in development environment.
- `stringify` If true, connect-mongo will serialize sessions using `JSON.stringify` before
setting them, and deserialize them with `JSON.parse` when getting them.
(optional, default: true). This is useful if you are using types that
MongoDB doesn't support.
- `serialize` Custom hook for serializing sessions to MongoDB. This is helpful if you need
to modify the session before writing it out.
- `unserialize` Custom hook for unserializing sessions from MongoDB. This can be used in
scenarios where you need to support different types of serializations
(e.g., objects and JSON strings) or need to modify the session before using
it in your app.
- `writeOperationOptions` Options object to pass to every MongoDB write operation call that
supports it (e.g. `update`, `remove`). Useful for adjusting the write concern.
Only exception: If `autoRemove` is set to `'interval'`, the write concern
from the `writeOperationOptions` object will get overwritten.
- `transformId` (optional) Transform original sessionId in whatever you want to use as storage key.

## Crypto options
- `secret` (optional) Enables transparent crypto in accordance with [OWASP session management recommendations](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md).
- `algorithm` (optional) Allows for changes to the default symmetric encryption cipher; default is `GCM`. See `crypto.getCiphers()` for supported algorithms.
- `hashing` (optional) May be used to change the default hashing algorithm; default is `sha512`. See `crypto.getHashes()` for supported hashing algorithms.
- `encodeas` (optional) Specify to change the session data cipher text encoding. Default is `hex`.
- `key_size` (optional) When using varying algorithms the key size may be used. Default is `32` based on the `AES` blocksize.
- `iv_size` (optional) This can be used to adjust the default [IV](https://csrc.nist.gov/glossary/term/IV) size if a different algorithm requires a different size. Default is `16`.
- `at_size` (optional) When using newer `AES` modes such as the default `GCM` or `CCM` an authentication tag size can be defined; default is `16`.
## Options

### Connection-related options (required)

One of the following options should be provided. If more than one option are provided, each option will take precedence over others according to priority.

|Priority|Option|Description|
|:------:|------|-----------|
|1|`url`|A [connection string](https://docs.mongodb.com/manual/reference/connection-string/) for creating a new MongoClient connection. If database name is not present in the connection string, database name should be provided using `dbName` option. Otherwise MongoDB will set the database name to `'test'`.|
|2|`mongooseConnection`|An existing Mongoose connection. If the connection was established without database name being present in the connection string, database name is set to MongoDB default `'test'`.|
|3|`client`|An existing MongoClient connection. If the connection was established without database name being present in the connection string, database name should be provided using `dbName` option. Otherwise MongoDB will set the database name to `'test'`.|
|4|`clientPromise`|A Promise that is resolved with MongoClient connection. If the connection was established without database name being present in the connection string, database name should be provided using `dbName` option. Otherwise MongoDB will set the database name to `'test'`.|

### More options

|Option|Default|Description|
|------|:-----:|-----------|
|`mongoOptions`|`{useNewUrlParser: true, useUnifiedTopology: true}`|Options object for [`MongoClient.connect()`](https://mongodb.github.io/node-mongodb-native/3.3/api/MongoClient.html#.connect) method. Can be used with `url` option.|
|`dbName`||A name of database used for storing sessions. Can be used with `url`, `client` or `clientPromise` options. Takes precedence over database name present in the connection string.|
|`collection`|`'sessions'`|A name of collection used for storing sessions.|
|`ttl`|`1209600`|The maximum lifetime (in seconds) of the session which will be used to set `session.cookie.expires` if it is not yet set. Default is 14 days.|
|`autoRemove`|`'native'`|Behavior for removing expired sessions. Possible values: `'native'`, `'interval'` and `'disabled'`.|
|`autoRemoveInterval`|`10`|Interval (in minutes) used when `autoRemove` option is set to `interval`.|
|`touchAfter`||Interval (in seconds) between session updates.|
|`fallbackMemory`||Fallback to `MemoryStore` if `true`. Useful if you want to use `MemoryStore` in some case, like in development environment.|
|`stringify`|`true`|If `true`, connect-mongo will serialize sessions using `JSON.stringify` before setting them, and deserialize them with `JSON.parse` when getting them. This is useful if you are using types that MongoDB doesn't support.|
|`serialize`||Custom hook for serializing sessions to MongoDB. This is helpful if you need to modify the session before writing it out.|
|`unserialize`||Custom hook for unserializing sessions from MongoDB. This can be used in scenarios where you need to support different types of serializations (e.g., objects and JSON strings) or need to modify the session before using it in your app.|
|`writeOperationOptions`||Options object to pass to every MongoDB write operation call that supports it (e.g. `update`, `remove`). Useful for adjusting the write concern. Only exception: If `autoRemove` is set to `'interval'`, the write concern from the `writeOperationOptions` object will get overwritten.|
|`transformId`||Transform original `sessionId` in whatever you want to use as storage key.|

### Crypto-related options

|Option|Default|Description|
|------|:-----:|-----------|
|`secret`|`false`|Enables transparent crypto in accordance with [OWASP session management recommendations](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md).|
|`algorithm`|`'aes-256-gcm'`|Allows for changes to the default symmetric encryption cipher. See [`crypto.getCiphers()`](https://nodejs.org/api/crypto.html#crypto_crypto_getciphers) for supported algorithms.|
|`hashing`|`'sha512'`|May be used to change the default hashing algorithm. See [`crypto.getHashes()`](https://nodejs.org/api/crypto.html#crypto_crypto_gethashes) for supported hashing algorithms.|
|`encodeas`|`'hex'`|Specify to change the session data cipher text encoding.|
|`key_size`|`32`|When using varying algorithms the key size may be used. Default value `32` is based on the `AES` blocksize.|
|`iv_size`|`16`|This can be used to adjust the default [IV](https://csrc.nist.gov/glossary/term/IV) size if a different algorithm requires a different size.|
|`at_size`|`16`|When using newer `AES` modes such as the default `GCM` or `CCM` an authentication tag size can be defined.|

## Tests

Expand Down
14 changes: 8 additions & 6 deletions src/index.js
Expand Up @@ -94,7 +94,7 @@ module.exports = function(connect) {
if (err) {
this.connectionFailed(err)
} else {
this.handleNewConnectionAsync(client)
this.handleNewConnectionAsync(client, options.dbName)
}
}

Expand All @@ -113,15 +113,15 @@ module.exports = function(connect) {
}
} else if (options.client) {
if (options.client.isConnected()) {
this.handleNewConnectionAsync(options.client)
this.handleNewConnectionAsync(options.client, options.dbName)
} else {
options.client.once('open', () =>
this.handleNewConnectionAsync(options.client)
this.handleNewConnectionAsync(options.client, options.dbName)
)
}
} else if (options.clientPromise) {
options.clientPromise
.then(client => this.handleNewConnectionAsync(client))
.then(client => this.handleNewConnectionAsync(client, options.dbName))
.catch(err => this.connectionFailed(err))
} else {
throw new Error('Connection strategy not found')
Expand All @@ -135,9 +135,11 @@ module.exports = function(connect) {
throw err
}

handleNewConnectionAsync(client) {
handleNewConnectionAsync(client, dbName) {
this.client = client
this.db = typeof client.db !== 'function' ? client.db : client.db()
// If dbName === undefined, client.db(dbName) will return
// the same value that client.db() would return.
this.db = typeof client.db !== 'function' ? client.db : client.db(dbName)
return this.setCollection(this.db.collection(this.collectionName))
.setAutoRemoveAsync()
.then(() => this.changeState('connected'))
Expand Down

0 comments on commit aa0e212

Please sign in to comment.