Skip to content

Commit

Permalink
Merge pull request #12 from johnnybravo-xyz/master
Browse files Browse the repository at this point in the history
fix: Redis store should respect 'ttl' and set expiry of keys on Commit
  • Loading branch information
vividvilla authored Jan 1, 2021
2 parents a9169ad + 98e7a3a commit 4427728
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
24 changes: 22 additions & 2 deletions stores/redis/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,29 @@ func (s *Store) Commit(sess *simplesessions.Session, id string) error {
// Set to redis
conn := s.pool.Get()
defer conn.Close()
_, err := conn.Do("HMSET", args...)

return err
conn.Send("MULTI")
conn.Send("HMSET", args...)

// Set expiry of key only if 'ttl' is set, this is to
// ensure that the key remains valid indefinitely like
// how redis handles it by default
if s.ttl > 0 {
conn.Send("EXPIRE", args[0], s.ttl.Seconds())
}

res, err := redis.Values(conn.Do("EXEC"))
if err != nil {
return err
}

for _, r := range res {
if v, ok := r.(redis.Error); ok {
return v
}
}

return nil
}

// Delete deletes a key from redis session hashmap.
Expand Down
9 changes: 8 additions & 1 deletion stores/redis/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,12 +320,14 @@ func TestEmptyCommit(t *testing.T) {
}

func TestCommit(t *testing.T) {
// Test should only set in internal map and not in redis
// Test should commit in redis with expiry on key
assert := assert.New(t)
redisPool := getRedisPool()
str := New(redisPool)
sess := &simplesessions.Session{}

str.SetTTL(10 * time.Second)

// this key is unique across all tests
key := "8dIHy6S2uBuKaNnTUszB2180898ikGY1"
field1 := "somekey"
Expand All @@ -346,6 +348,11 @@ func TestCommit(t *testing.T) {
defer conn.Close()
vals, err := redis.Values(conn.Do("HGETALL", defaultPrefix+key))
assert.Equal(2*2, len(vals))

ttl, err := redis.Int(conn.Do("TTL", defaultPrefix+key))
assert.NoError(err)

assert.Equal(true, ttl > 0 && ttl <= 10)
}

func TestDeleteInvalidSessionError(t *testing.T) {
Expand Down

0 comments on commit 4427728

Please sign in to comment.