Coder Social home page Coder Social logo

voxpelli / node-connect-pg-simple Goto Github PK

View Code? Open in Web Editor NEW
231.0 7.0 73.0 267 KB

A simple, minimal PostgreSQL session store for Express

Home Page: https://www.npmjs.com/package/connect-pg-simple

License: MIT License

JavaScript 99.65% Shell 0.35%
sessionstorage postgres node-js express express-session postgresql

node-connect-pg-simple's Introduction

Connect PG Simple

A simple, minimal PostgreSQL session store for Express/Connect

npm version npm downloads Module type: CJS js-semistandard-style Follow @voxpelli@mastodon.social

Installation

npm install connect-pg-simple

Once npm installed the module, you need to create the "session" table in your database.

For that you can use the table.sql file provided with the module:

psql mydatabase < node_modules/connect-pg-simple/table.sql

Or simply play the file via a GUI, like the pgAdminIII queries tool.

Or instruct this module to create it itself, by setting the createTableIfMissing option.

Note that connect-pg-simple requires PostgreSQL version 9.5 or above.

Usage

Examples are based on Express 4.

Simple example:

const session = require('express-session');

app.use(session({
  store: new (require('connect-pg-simple')(session))({
    // Insert connect-pg-simple options here
  }),
  secret: process.env.FOO_COOKIE_SECRET,
  resave: false,
  cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
  // Insert express-session options here
}));

Advanced example showing some custom options:

const pg = require('pg');
const expressSession = require('express-session');
const pgSession = require('connect-pg-simple')(expressSession);

const pgPool = new pg.Pool({
    // Insert pool options here
});

app.use(expressSession({
  store: new pgSession({
    pool : pgPool,                // Connection pool
    tableName : 'user_sessions'   // Use another table-name than the default "session" one
    // Insert connect-pg-simple options here
  }),
  secret: process.env.FOO_COOKIE_SECRET,
  resave: false,
  cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
  // Insert express-session options here
}));

Advanced options

Connection options

Listed in the order they will be picked up. If multiple are defined, then the first in the lists that is defined will be used, the rest ignored.

  • pool - The recommended one – Connection pool object (compatible with pg.Pool) for the underlying database module.
  • pgPromise - Database object from pg-promise to be used for DB communications.
  • conObject - If you don't specify a pool object, use this option or conString to specify a PostgreSQL Pool connection object and this module will create a new pool for you.
  • conString - If you don't specify a pool object, use this option or conObject to specify a PostgreSQL connection string like postgres://user:password@host:5432/database and this module will create a new pool for you. If there's a connection string in the DATABASE_URL environment variable (as it is by default on eg. Heroku) then this module will fallback to that if no other connection method has been specified.

Other options

  • ttl - the time to live for the session in the database – specified in seconds. Defaults to the cookie maxAge if the cookie has a maxAge defined and otherwise defaults to one day.
  • createTableIfMissing - if set to true then creates the table in the case where the table does not already exist. Defaults to false.
  • disableTouch – boolean value that if set to true disables the updating of TTL in the database when using touch. Defaults to false.
  • schemaName - if your session table is in another Postgres schema than the default (it normally isn't), then you can specify that here.
  • tableName - if your session table is named something else than session, then you can specify that here.
  • pruneSessionInterval - sets the delay in seconds at which expired sessions are pruned from the database. Default is 900 seconds (15 minutes). If set to false no automatic pruning will happen. By default every delay is randomized between 50% and 150% of set value, resulting in an average delay equal to the set value, but spread out to even the load on the database. Automatic pruning will happen pruneSessionInterval seconds after the last pruning (includes manual prunes).
  • pruneSessionRandomizedInterval – if set to false, then the exact value of pruneSessionInterval will be used in all delays. No randomization will happen. If multiple instances all start at once, disabling randomization can mean that multiple instances are all triggering pruning at once, causing unnecessary load on the database. Can also be set to a method, taking a numeric delay parameter and returning a modified one, thus allowing a custom delay algorithm if wanted.
  • errorLog – the method used to log errors in those cases where an error can't be returned to a callback. Defaults to console.error(), but can be useful to override if one eg. uses Bunyan for logging.

Useful methods

  • close() – if this module used its own database module to connect to Postgres, then this will shut that connection down to allow a graceful shutdown. Returns a Promise that will resolve when the database has shut down.
  • pruneSessions([callback(err)]) – will prune old sessions. Only really needed to be called if pruneSessionInterval has been set to false – which can be useful if one wants improved control of the pruning.

For enterprise

Available as part of the Tidelift Subscription.

The maintainers of connect-pg-simple and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. Learn more.

node-connect-pg-simple's People

Contributors

aadeshmisra avatar bobnil avatar bsaf avatar ddehghan avatar eugene1g avatar focusaurus avatar fossabot avatar g3z avatar github-actions[bot] avatar hvrauhal avatar i8-pi avatar japherwocky avatar mdmower-csnw avatar nalexandrov avatar nstuyvesant avatar rauno56 avatar renovate-bot avatar renovate[bot] avatar safareli avatar sebcagnon avatar singingwolfboy avatar toddpi314 avatar voxpelli 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

node-connect-pg-simple's Issues

shemaName

Introducing 'shemaName' was

  1. Breaking change.
    • default went from 'session' to 'public.session' which means people who used search path to specify their shema, broke their code.
    • 'someTable' users had the same problem as above.
    • 'someSchema.someTable' users(who don't leave it in the hands of search path) now went to 'public.someSchema.someTable' which also breaks.
  2. a bad idea IMO: Who needed it could have just specify tableName in the format of 'someSchema.someTable' on the other hand there is no way now to force this library to use search path because of the javascript coercion and schemaName || 'public' usage.

using with express 4.4

This might not be a bug actually, but a funny workaround I just put into place that I figured I'd report anyhow.

Using express 4.4, express.session throws an error about packages being bundled separately. So, when this module initializes with var Store = connect.session.Store, problems ensue!

Instead of require('connect-pg-simple')(express), I worked around this like:

var session = require('express-session');
var pgSession = require('connect-pg-simple')({'session':session});

my javascript-fu is kind of weak, I'm not sure if there's a good way to "fix" this and keep backwards compatibility?

sessions not found when node.js server and DB server not having same time

Came across a nice issue that happens when node.js and pgsql are not running on the same machine and where both machines were in different timezones (or simply had differences in their curren time). I'm posting a fix here in case anybody encounters this or wants to fix this inside the module.

The session prune and query functions use NOW() of pgsql while the insert/update statements are formed using node.js Date.now(), thus taking the time of the node.js server.

I fixed this for me by making sure all queries take the time from the same server. In this case I used the time from the node.js server in all cases. For anyone interested:

pruneSessions() then becomes:

this.query('DELETE FROM ' + this.quotedTable() + ' WHERE expire < to_timestamp($1)', [Date.now() / 1000], ....

and get() becomes:

this.query('SELECT sess FROM ' + this.quotedTable() + ' WHERE sid = $1 AND expire >= to_timestamp($2)', [sid, Date.now() / 1000], ...

I later found out the date on my DB server was 1 day off ;-)

Does not work with pg-pool

Hi,
Module itself is great. Thank You. The only thing, it cannot work with pg-pool.
The only difference, i noticed, is in parameters of pg.connect. for pg-pool instance conString parameter is not needed (it is defined during initialization of pg-pool). As of myself i rewritten this function to use with my app, but basically it would be great, if there would be one of the options to use pg-pool,

Options in constructor seem to be ignored

I am trying to use pg's Pool instance and pass it to the constructor. However I'm getting an error message:

Failed to prune sessions: database "username" does not exist

The way I construct the pool is this:

const { Pool } = require('pg')

const pool = new Pool({
  host: pgConfig.host,
  user: pgConfig.username,
  database: pgConfig.database,
  port: pgConfig.port,
  password: null,
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
})

I am using express-session package so in my Express app I create session instance like this:

const session = require('express-session')
const pgSession = require('connect-pg-simple')(session)

app.use(session({
  name: 'my-app-name',
  store: new pgSession({
    pgPool: pool,
    tableName: 'Sessions',
  }),
  key: 'user_sid',
  secret: 'somerandonstuffs',
  resave: false,
  cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 },
  httpOnly: true,
  saveUninitialized: true,
}))

I think the pg part works correctly because when I try to run pool.query and read the data from that database, I get the results.

Its somehow trying to default to my user account's database (which I have not created because why?)

fatal error: terminating connection due to a administrator command

I received this error over the weekend which crashed my app:

error: terminating connection due to administrator command
    at Connection.parseE (/usr/src/app/node_modules/connect-pg-simple/node_modules/pg/lib/connection.js:539:11)
    at Connection.parseMessage (/usr/src/app/node_modules/connect-pg-simple/node_modules/pg/lib/connection.js:366:17)
    at Socket.<anonymous> (/usr/src/app/node_modules/connect-pg-simple/node_modules/pg/lib/connection.js:105:22)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:153:18)
    at Socket.Readable.push (_stream_readable.js:111:10)
    at TCP.onread (net.js:537:20)

I understand that something unusual has happened with postgres (see this and this). But is there a way I can prevent the error from bringing down the house?

Table Name Configuration

Can we add a configuration parm to allow variable table name?

This is important for scenarios where the naming conventions of a pre-existing DB are different than the standard 'sessions' table.

Keep up the great work!

ERROR: date/time field value out of range: "1478362007"

3.1.1 and in particular bd6d3a2 appears to have broken sessions for me, causing the error in the title on all connections (with a changing timestamp, obviously).

This is on a dockerised app (node 6.9.1, express 4.14.0, express-session 1.14.2) connecting to Postgres 9.5.5. I'm using connect-pg-simple here, with this Postgres table config.

add an option to automatically create table if not present

I came here because of issues with https://github.com/llambda/connect-session-knex

That library had a really handy createtable option that you could use instead of creating the table yourself.

This is great for setups like mine, that involve an unmodified pg docker container, and a node container that installs npm plugins and calls a js script.

One consideration to have for adding the feature is that the script might be updated, but someone forgets to update the sql file, or vice versa. I don't know much about postgres, but getting the sql file as text and sending it as a raw query to the server would work, right? This way, there's a single source for creating the table

Cannot use connection pool of application

Hi, this module wont use the connection pool module of the rest of my application. Why is that ?

// db.js

var Promise = require('bluebird'),
    pgp = require('pg-promise')({
        promiseLib: Promise
    }),
    conf = require('./conf.js');

var db = pgp(conf.pgdb.conn);

module.exports = db;

// app.js 

var db = require('./db.js');
//...etc

var sessionOptions = {
    store : new PostgreSqlStore({
        pg : db // <--- db DOES NOT WORK
    })
};

SQL-injection possible in PGStore.prototype.quotedTable

The function PGStore.prototype.quotedTable is vulnerable to SQL-injection, if the input has double quotes. If schemaName is set to 'web".session WHERE $1=$1;--' it will wipe the web.session table every time the prune process runs.

/**
   * Get the quoted table.
   *
   * @return {String} the quoted schema + table for use in queries
   * @access private
   */


  PGStore.prototype.quotedTable = function () {
    let result = '"' + this.tableName + '"';

    if (this.schemaName) {
      result = '"' + this.schemaName + '".' + result;
    }

    return result;
  };

There is a function quote_ident that could be used:

Return the given string suitably quoted to be used as an identifier in an SQL statement string. Quotes are added only if necessary (i.e., if the string contains non-identifier characters or would be case-folded). Embedded quotes are properly doubled.

Calling this function will require a call to the server and requires that the server is available before the table name can be resolved. This call could also get the version of the server, and warn the user if the server version is too old.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codeql-analysis.yml
.github/workflows/compliance.yml
  • mtfoley/pr-compliance-action 11b664f0fcf2c4ce954f05ccfcaab6e52b529f86
.github/workflows/dependency-review.yml
.github/workflows/lint.yml
.github/workflows/nodejs.yml
.github/workflows/release-please.yml
npm
package.json
  • pg ^8.8.0
  • @types/chai ^4.3.11
  • @types/chai-as-promised ^7.1.8
  • @types/cookie-signature ^1.1.2
  • @types/express ^4.17.21
  • @types/express-session ^1.17.10
  • @types/mocha ^10.0.6
  • @types/pg ^8.11.0
  • @types/proxyquire ^1.3.31
  • @types/sinon ^17.0.3
  • @types/sinon-chai ^3.2.12
  • @types/supertest ^6.0.2
  • @voxpelli/eslint-config ^19.0.0
  • @voxpelli/tsconfig ^10.0.0
  • c8 ^9.1.0
  • chai ^4.3.10
  • chai-as-promised ^7.1.1
  • cookie-signature ^1.2.1
  • cookiejar ^2.1.4
  • dotenv ^16.4.1
  • eslint ^8.56.0
  • eslint-plugin-es-x ^7.5.0
  • eslint-plugin-import ^2.29.1
  • eslint-plugin-jsdoc ^46.10.1
  • eslint-plugin-mocha ^10.2.0
  • eslint-plugin-n ^16.6.2
  • eslint-plugin-promise ^6.1.1
  • eslint-plugin-security ^1.7.1
  • eslint-plugin-sort-destructure-keys ^1.5.0
  • eslint-plugin-unicorn ^48.0.1
  • express ^4.18.2
  • express-session ^1.17.3
  • husky ^8.0.3
  • installed-check ^8.0.1
  • knip ^4.3.1
  • mocha ^10.2.0
  • npm-run-all2 ^6.1.2
  • pg-promise ^11.5.4
  • proxyquire ^2.1.3
  • sinon ^17.0.1
  • sinon-chai ^3.7.0
  • supertest ^6.3.4
  • type-coverage ^2.27.0
  • typescript ~5.3.2
  • validate-conventional-commit ^1.0.3
  • node >=16.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

Set session only if login - passport

Hi

Firstly thank you for taking the time to put this out there and maintain it. I had a question around only saving a session if a user logs in (currently use passport). This is my config so far

// server.js
app.use(session({
  store: new PGSession({
  pool: dbConn, // Connection pool
}),
  secret: 'secret-here',
  name: 'session',
  resave: false,
  saveUninitialized: false,
  secure: true,
  cookie: { maxAge: 365 * 24 * 60 * 60 * 1000 },
}));
app.use(passport.initialize());
app.use(passport.session());

What I notice so far is that for when ever someone accesses the site and entry is made like so

123456789,"{""cookie"":{""originalMaxAge"":31536000000,""expires"":""2020-04-13T09:55:11.015Z"",""httpOnly"":true,""path"":""/""},""flash"":{}}",2020-04-13 09:55:12.000000

When someone logs in their user id gets attached like so

1234567,"{""cookie"":{""originalMaxAge"":31536000000,""expires"":""2020-04-10T20:10:07.241Z"",""httpOnly"":true,""path"":""/""},""flash"":{},""passport"":{""user"":12345}}",2020-04-10 20:19:43.000000

Is there a way to set this up so a session only gets stored if logged in

Thanks

Support pg.js

pg.js is a pg driver without the C bindings. It means no compilation if you are not using the C-stuff.

I would gladly patch it, but there's two ways to do this. @voxpelli - tell me what you think.

  1. Support it by trying to require pg driver in the naive way and break when there is not one available. Like knex does it.
  2. Always require the user to provide a driver. IMO the better, more clear way. Let's just say that "with the Store, also give us the driver you are using!". Breaks backwards-compatibility but it would be nice chance to also throw in a fix to #4.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Errors are not propagated correctly

Hi!
I was trying to use this module and didn't pay attention to that it required Postgres 9.5 or later.
The error that was thrown inside the module was not propagated because it used fn.apply instead of fn.call.

I will submit a pull request soon (needed to create an issue to get a logical branch name)

Explicitly calling save on a session can result in wrong expiry date

Due to the implementation of the PGStore.touch method, the expiry date in sess.cookie may be out of sync with the value in the expire column in the PG database. This is typically not a problem since only this expire column is used to filter expired sessions.
However, when explicitly calling sess.save(), the expiry date stored in sess.cookie is put into the expire column in the database (https://github.com/voxpelli/node-connect-pg-simple/blob/master/index.js#L214). Because the expiry date in sess.cookie may be a lot older than the actual expiry date stored in the expire database column, this is a problem.

When you don't call the sess.save() function explicitly, you don't notice this problem. Express-session will automatically call sess.touch() before calling sess.save() https://github.com/expressjs/session/blob/master/index.js#L237.
A workaround for me is to explicitly call sess.touch() before sess.save().

Expire sessions form the same user

It is possible for a user to login multiple times (from same browser or multiple machines). In any case, it would be desirable for some applications to limit this ability to just one session per user. (Auto-log off, security implications). The user may not already have a shared cookiejar either.

It would be desired to have some kind of support to specify how to match existing rows in the session store and delete them. For instance passport puts a 'passport: {/deserializeduser/}' object in the server side of the cookie. If I could provide some kind of match function, or object, that would be awesome.

for instance, if I could supply an object of "{passport: {user: {id: 'value'} } }", then all the cookies with the matching value will be deleted before the cookie is set.

Allow PG-promise module to be loaded

It would be great if you could pass a pg-promise module as the module used for the session store connection. That way those of us who rely entirely on pg-promise can utilize the same connection.

This is similar but different from #32

pg-promise

Would you consider a PR or a different branch to switch over to pg-promise?

It would simplify your code a lot, while also making it more reliable ;)

Cannot set property 'domain' of undefined

I'm getting the following error when trying to set this up:

events.js:24
this.domain = null;
^

TypeError: Cannot set property 'domain' of undefined
at EventEmitter.init (events.js:24:15)
at EventEmitter (events.js:6:21)
at Store (/project/node_modules/express-session/session/store.js:33:16)
at PGStore (/project/node_modules/connect-pg-simple/index.js:19:11)

Any insight?

Session not set immediately after login

I'm using this library with express-session, passport, and the Passport Google OAuth2.0 lib. When the user approves of logging in and gets redirected, req.user is not set (nor, say, req.session.passport.user). I send this info over to the client, so that they know who is logged in. Because it isn't sent, the client believes that the user has not logged in, and redirects them back to the login page. If the user then refreshes that page, things are set at that time, and they are considered logged in.

The cookie is set, but the presence of the cookie isn't very reliable. For instance, when they're logged out, the cookie currently sticks around.

I set this app by following this example, using the in-memory session. The user was set immediately on being redirected. When I refactored to add in this lib, it no longer worked the same way.

Is this an issue anyone else has run into before? I've tried switching around the resave and saveUnitialized options to see if those would affect this, but with no luck.

The code is pretty awful – I'm trying to get it to work before refactoring – but you can see the configuration here.

Results of the investigation:

  • It's also lagging behind when the user gets logged out. After hitting the /logout endpoint, they're sent the user info until they refresh. Update: calling req.session.destroy explicitly fixed this. Full code at the end of this post.
  • Switching to pg rather than pg-promise did not solve the issue
  • Switching from multiple to a single process didn't fix it either
Logout code

Simply calling req.logout() wasn't working. Explicitly calling req.session.destroy(), on the other hand, forces the session to be destroyed 100% of the time.

app.get('/logout', (req, res) => {
  req.logout();
  req.session.destroy(function (err) {
    res.redirect('/login');
  });
});

Interest in ES6 version?

Would you accept a PR to convert the codebase to ES6, as long as it's fully backward compatible?

Query every min.

According to the code, every min. there's a query to the db , deleting all the pruneSessions
Is that really needed?

When database is not available, fatal error should not propagate.

I'm new to node and may not have good way of describing this issue, bear with me please.

When get() called and database is suddenly unavailable it's probably not a best behavior to propagate error all the way and crush application.

I wondered if modifying get() behavior when query returns error is a good thing or no. I would agree that passing just a simple "not found" is likely not a best behavior and may confuse people but crashing everyone, even those users who not yet logged in seem worse to me.

error: relation "session" does not exist

After installing connect-pg-simple in my Drywall app, pg is complaining as such:

error: relation "session" does not exist

I've created the session table in the same database as the rest of my application uses, but I still get the above exception. I've also tried to specify the conString property, as such:

app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: config.cryptoKey,
  store: new (require('connect-pg-simple')(session))(),
  cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
  conString: 'pg://' + config.username + ':' + config.password + '@' + config.host + '/' + config.database
}));

But it doesn't help. Ideas?

tableName : 'user_sessions' vs CREATE TABLE "session"

Just a minor thing I noticed. In table.sql the table name is "session"

but in the read me you wrote

store: new pgSession({
pg : pg,
conString : process.env.FOO_DATABASE_URL,
tableName : 'user_sessions'
}),

should be

store: new pgSession({
pg : pg,
conString : process.env.FOO_DATABASE_URL,
tableName : 'session'
}),

Great work tho, thanks for this repo

Please add this to the documentation

I kept getting this error.

Failed to prune sessions: no pg_hba.conf entry for host "<bad_ip_address>", user "<correct_user_name>", database "<correct_db_name>", SSL off

It turns out I was placing the connection string and connection object in the wrong place in the config. I don't think the solution is clear from the documentation.

I was trying to do this.

server.use(session({
  store: new pgStore(),
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  conString: process.env.DATABASE_URL,
  cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
}));

I finally found the correct place to put the conString on Stack.
https://stackoverflow.com/questions/39124709/can-i-configure-connect-pg-simple-to-have-ssl-on

Node v14 not supported

To make it work right under Node v14, you need to update pg dependency to version 8.0.3, which is where compatibility with Node v14 was fixed.

Random deletion of expired sessions

The following seems sort of arbitrary -- 5% of requests will trigger the deletion of expired sessions. Where's this number from? Why bind this cleanup event to request events at all?

if (Math.random() < 0.05) {
  this.query('DELETE FROM ' + this.quotedTable() + ' WHERE expire < NOW()');
}

Support for socket connection string

I am using a socket connection string for database connection

socket:/home/thefive/tmp/?db=osmbcdev'

Url.parse generates the following:

Params parsed  Url {
  protocol: 'socket:',
  slashes: null,
  auth: null,
  host: '',
  port: null,
  hostname: '',
  hash: null,
  search: '?db=osmbcdev',
  query: 'db=osmbcdev',
  pathname: '/home/thefive/tmp/',
  path: '/home/thefive/tmp/?db=osmbcdev',
  href: 'socket:/home/thefive/tmp/?db=osmbcdev' }

This leads to the following connection object

{ user: undefined,
  password: undefined,
  host: '',
  port: undefined,
  database: 'home' }

Which can not connect to the correct database.

As i am using shared hosting, and am "not allowed" to use postgres on an internal port, but should use sockets, it would be nice, if sockets are still supported.

As a workaround i go back to 3.x and will use the connection object as an alternative.

Invalid DB logic

Line 127:

if (fn) { fn(err, result && result.rows[0] ? result.rows[0] : false); }

result in that context is non-null even when 0 rows are returned, so your code will throw an exception trying to access result.rows[0] in that case.

publish patch to npm

It's been a few months since 76af336 landed so I guess things are pretty stable. If you wouldn't mind releasing a patch release to npm for that, it would remove some warnings from my CI build scripts. Very low priority - just if you have a chance.

pgPromise docs description is not clear enough

As @vitaly-t mentioned in #41 the docs are not clear about what needs to be passed as the option pgPromise for this module. Also it will be worth mentioning that db.$pool from pg-promise can be used as of pg-promise 6.x for the pool option as mentioned here.

The changes I suggest are:

- * pgPromise - Existing instance of pg-promise to be used for DB communications.
+ * pgPromise - Database object from `pg-promise` to be used for DB communications.
- * pool - Recommended. Connection pool object (compatible with pg.Pool) for the underlying database module
+ * pool - Recommended. Connection pool object (compatible with pg.Pool) for the underlying database module. If using `pg-promise` `db.$pool` can be used.

I can submit a PR with the fixes suggested.

`pg` custom option failing on newer versions of `node-postgres`

I was using the extended options so that I could specify the connection string, and supplying the pg instance that I was using elsewhere in the application, and recently ran into an issue when the pg version updated to 6.0.0

  store: new pgSession({
    pg: datasource.connector.pg
    conString: pgUrl(datasource.settings)
  })

It seems that it stems from a change to the interface for pg.connect which you call here: https://github.com/voxpelli/node-connect-pg-simple/blob/master/index.js#L137

The connect function no longer takes a connection string as it's first argument, only an optional callback.

Possibly all that's needed is for the README to state the versions of pg that are supported for external use? Otherwise, I guess some detection of pg version and changing the usage may work as well?

No license?

Hi @voxpelli, we are using this library in a client project, and they want license information for our top level dependencies. I can't see any license information in the source or package.json, are you able to advise me or update to reflect your license information?

Postgres 9.4 unsupported?

I'm getting the following error any time I try to set a session:

error: syntax error at or near "ON"
    at Connection.parseE (.../node_modules/pg/lib/connection.js:604:11)
    at Connection.parseMessage (.../node_modules/pg/lib/connection.js:401:19)
    at Socket.<anonymous> (.../node_modules/pg/lib/connection.js:121:22)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)
    at Pipe.onread (net.js:597:20)

I tried to extract the query from the source and run it by hand in psql and it yielded the same error.

$ psql --version
psql (PostgreSQL) 9.4.22

Does this mean postgres 9.4 is not supported?

RFC: Increase default prune interval to something like 15 minutes

Does anyone have any feedback on whether this would be a good or a bad change for them?

To me it feels like there's no harm in doing this at a longer interval, as the code checking for a session already checks the timestamp and only returns valid active sessions. This pruning is more of a garbage collector and that we don't need to run 60 times an hour. 4 times an hour would be more appropriate I think.

If someone has a site with lots of sessions, then of course they can change the default.

Will start by increasing from 1 to 5 minutes now, to not break anything for anyone.

multiple rows every 30 seconds in my store

Hi, I want to ask and know why that every 30 seconds a new row is created in my store?

I have the following configuration:

app.use (session ({
    store : pgSession ({
        pg : require ('massive/node_modules/pg'),
        conString: "my ConString",
        tableName : 'session'
    }),
    secret: 'every secret',
    cookie: {maxAge: 1 * 24 * 60 * 60 * 1000},
    resave: false,
    saveUninitialized: true
}))

I am using express-session to session management. I hope you can help me with this because if you leave me a full day generate more than 2,000 records.

Thanks!!! ☺️ 👍

param.auth becomes null if postgres password contains '/'

connect-pg-simple version : 4.0.0

I am getting the following stack trace error on the latest version of connect-pg-simple. I did not have such problems with previous version 3.1.2.

Suggestion : Please accept the connectString as object instead of string to fix this issue.

Stack trace error message

/var/www/html/node_modules/connect-pg-simple/index.js:29
const auth = params.auth.split(':');
^

TypeError: Cannot read property 'split' of null
at new PGStore (/var/www/html/node_modules/connect-pg-simple/index.js:29:31)
at Object. (/var/www/html/lab2-ui/app.js:40:9)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (/var/www/html/lab2-ui/bin/www:7:11)

[Question] Does pruning delete from the database and is there an obfuscation feature?

I have OAuth API's from external platforms being used and the session store records all this information in the database.

I don't really need sessions except for handling OAuth so I'm ok with setting the maxAge to something like 5 minutes or even less so that when pruning happens, it will remove the session entry in the DB. However, if pruning doesn't delete the row from the DB, then this wouldn't work.

The other method I've seen other packages do is to encrypts the payload on write then decrypts it on read. This takes a performance hit, but adds a layer of security that some people need.

DB URL query params are ignored

One way to enable SSL in pg is to pass the flag { ssl: 'require' } through the connection URL:

postgres://user:pass@db:5432/dbname?ssl=require

However, because connect-pg-simple manually parses the URL, the query params are lost.

There are a few solutions that I can think of:

  1. Handle the ssl config option specifically and include it in the soon-to-be-passed conObject (I don't like this option)
  2. Use the parsed query params and include them all, like it's done here: https://github.com/grncdr/parse-db-url/blob/master/parse-url.js#L36
  3. Use the parse-db-url package itself. But perhaps you don't want to add a new dependency.

I'd be happy to submit a PR, just tell me which solution do you prefer?

Thanks,
Andrej

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.