Skip to content

Commit

Permalink
Delete key if resulting TTL is negative in set method. (#321)
Browse files Browse the repository at this point in the history
If the set method is invoked with a session object which has a cookie
that expires in the past then the key is deleted / destroyed. Otherwise,
a negative TTL is calculated and that leads to Redis throwing an error
'ERR invalid expire time in set'.
  • Loading branch information
bebadt committed Apr 20, 2021
1 parent 736bdc6 commit 65387e4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/connect-redis.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,19 @@ module.exports = function (session) {
return cb(er)
}
args.push(value)
if (!this.disableTTL) args.push('EX', this._getTTL(sess))

this.client.set(args, cb)
let ttl = 1
if (!this.disableTTL) {
ttl = this._getTTL(sess)
args.push('EX', ttl)
}

if (ttl > 0) {
this.client.set(args, cb)
} else {
// If the resulting TTL is negative we can delete / destroy the key
this.destroy(sid, cb)
}
}

touch(sid, sess, cb = noop) {
Expand Down
14 changes: 14 additions & 0 deletions test/connect-redis-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,20 @@ async function lifecycleTest(store, t) {

res = await p(store, 'clear')()
t.equal(res, count, 'bulk clear')

expires = new Date(Date.now() + ttl * 1000).toISOString() // expires in the future
res = await p(store, 'set')('789', { cookie: { expires } })
t.equal(res, 'OK', 'set value')

res = await p(store, 'length')()
t.equal(res, 1, 'one key exists (session 789)')

expires = new Date(Date.now() - ttl * 1000).toISOString() // expires in the past
res = await p(store, 'set')('789', { cookie: { expires } })
t.equal(res, 1, 'returns 1 because destroy was invoked')

res = await p(store, 'length')()
t.equal(res, 0, 'no key remains and that includes session 789')
}

function load(store, count) {
Expand Down

0 comments on commit 65387e4

Please sign in to comment.