mirror of
https://github.com/alexedwards/scs.git
synced 2025-07-11 00:50:14 +02:00
Merge v2 changes
This commit is contained in:
103
postgresstore/README.md
Normal file
103
postgresstore/README.md
Normal file
@ -0,0 +1,103 @@
|
||||
# postgresstore
|
||||
|
||||
A PostgreSQL-based session store supporting the [pq](https://github.com/lib/pq) driver.
|
||||
|
||||
## Setup
|
||||
|
||||
You should have a working PostgreSQL database containing a `sessions` table with the definition:
|
||||
|
||||
```sql
|
||||
CREATE TABLE sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
data BYTEA NOT NULL,
|
||||
expiry TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expiry);
|
||||
```
|
||||
|
||||
The database user for your application must have `SELECT`, `INSERT`, `UPDATE` and `DELETE` permissions on this table.
|
||||
|
||||
## Example
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/alexedwards/scs/v2"
|
||||
"github.com/alexedwards/scs/v2/postgresstore"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
var session *scs.Session
|
||||
|
||||
func main() {
|
||||
db, err := sql.Open("postgres", "postgres://user:pass@localhost/db")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
// Initialize a new session manager and configure it to use PostgreSQL as
|
||||
// the session store.
|
||||
session = scs.NewSession()
|
||||
session.Store = postgresstore.New(db)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/put", putHandler)
|
||||
mux.HandleFunc("/get", getHandler)
|
||||
|
||||
http.ListenAndServe(":4000", session.LoadAndSave(mux))
|
||||
}
|
||||
|
||||
func putHandler(w http.ResponseWriter, r *http.Request) {
|
||||
session.Put(r.Context(), "message", "Hello from a session!")
|
||||
}
|
||||
|
||||
func getHandler(w http.ResponseWriter, r *http.Request) {
|
||||
msg := session.GetString(r.Context(), "message")
|
||||
io.WriteString(w, msg)
|
||||
}
|
||||
```
|
||||
|
||||
## Expired Session Cleanup
|
||||
|
||||
This package provides a background 'cleanup' goroutine to delete expired session data. This stops the database table from holding on to invalid sessions indefinitely and growing unnecessarily large. By default the cleanup runs every 5 minutes. You can change this by using the `NewWithCleanupInterval()` function to initialize your session store. For example:
|
||||
|
||||
```go
|
||||
// Run a cleanup every 30 minutes.
|
||||
postgresstore.NewWithCleanupInterval(db, 30*time.Minute)
|
||||
|
||||
// Disable the cleanup goroutine by setting the cleanup interval to zero.
|
||||
postgresstore.NewWithCleanupInterval(db, 0)
|
||||
```
|
||||
|
||||
### Terminating the Cleanup Goroutine
|
||||
|
||||
It's rare that the cleanup goroutine needs to be terminated --- it is generally intended to be long-lived and run for the lifetime of your application.
|
||||
|
||||
However, there may be occasions when your use of a session store instance is transient. A common example would be using it in a short-lived test function. In this scenario, the cleanup goroutine (which will run forever) will prevent the session store instance from being garbage collected even after the test function has finished. You can prevent this by either disabling the cleanup goroutine altogether (as described above) or by stopping it using the `StopCleanup()` method. For example:
|
||||
|
||||
```go
|
||||
func TestExample(t *testing.T) {
|
||||
db, err := sql.Open("postgres", "postgres://user:pass@localhost/db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
store := postgresstore.New(db)
|
||||
defer store.StopCleanup()
|
||||
|
||||
session = scs.NewSession()
|
||||
session.Store = store
|
||||
|
||||
// Run test...
|
||||
}
|
||||
```
|
5
postgresstore/go.mod
Normal file
5
postgresstore/go.mod
Normal file
@ -0,0 +1,5 @@
|
||||
module github.com/alexedwards/scs/v2/postgresstore
|
||||
|
||||
go 1.12
|
||||
|
||||
require github.com/lib/pq v1.1.0
|
2
postgresstore/go.sum
Normal file
2
postgresstore/go.sum
Normal file
@ -0,0 +1,2 @@
|
||||
github.com/lib/pq v1.1.0 h1:/5u4a+KGJptBRqGzPvYQL9p0d/tPR4S31+Tnzj9lEO4=
|
||||
github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
101
postgresstore/postgresstore.go
Normal file
101
postgresstore/postgresstore.go
Normal file
@ -0,0 +1,101 @@
|
||||
package postgresstore
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PostgresStore represents the session store.
|
||||
type PostgresStore struct {
|
||||
db *sql.DB
|
||||
stopCleanup chan bool
|
||||
}
|
||||
|
||||
// New returns a new PostgresStore instance, with a background cleanup goroutine
|
||||
// that runs every 5 minutes to remove expired session data.
|
||||
func New(db *sql.DB) *PostgresStore {
|
||||
return NewWithCleanupInterval(db, 5*time.Minute)
|
||||
}
|
||||
|
||||
// NewWithCleanupInterval returns a new PostgresStore instance. The cleanupInterval
|
||||
// parameter controls how frequently expired session data is removed by the
|
||||
// background cleanup goroutine. Setting it to 0 prevents the cleanup goroutine
|
||||
// from running (i.e. expired sessions will not be removed).
|
||||
func NewWithCleanupInterval(db *sql.DB, cleanupInterval time.Duration) *PostgresStore {
|
||||
p := &PostgresStore{db: db}
|
||||
if cleanupInterval > 0 {
|
||||
go p.startCleanup(cleanupInterval)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Find returns the data for a given session token from the PostgresStore instance.
|
||||
// If the session token is not found or is expired, the returned exists flag will
|
||||
// be set to false.
|
||||
func (p *PostgresStore) Find(token string) (b []byte, exists bool, err error) {
|
||||
row := p.db.QueryRow("SELECT data FROM sessions WHERE token = $1 AND current_timestamp < expiry", token)
|
||||
err = row.Scan(&b)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, false, nil
|
||||
} else if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return b, true, nil
|
||||
}
|
||||
|
||||
// Commit adds a session token and data to the PostgresStore instance with the
|
||||
// given expiry time. If the session token already exists, then the data and expiry
|
||||
// time are updated.
|
||||
func (p *PostgresStore) Commit(token string, b []byte, expiry time.Time) error {
|
||||
_, err := p.db.Exec("INSERT INTO sessions (token, data, expiry) VALUES ($1, $2, $3) ON CONFLICT (token) DO UPDATE SET data = EXCLUDED.data, expiry = EXCLUDED.expiry", token, b, expiry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete removes a session token and corresponding data from the PostgresStore
|
||||
// instance.
|
||||
func (p *PostgresStore) Delete(token string) error {
|
||||
_, err := p.db.Exec("DELETE FROM sessions WHERE token = $1", token)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *PostgresStore) startCleanup(interval time.Duration) {
|
||||
p.stopCleanup = make(chan bool)
|
||||
ticker := time.NewTicker(interval)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
err := p.deleteExpired()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
case <-p.stopCleanup:
|
||||
ticker.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StopCleanup terminates the background cleanup goroutine for the PostgresStore
|
||||
// instance. It's rare to terminate this; generally PostgresStore instances and
|
||||
// their cleanup goroutines are intended to be long-lived and run for the lifetime
|
||||
// of your application.
|
||||
//
|
||||
// There may be occasions though when your use of the PostgresStore is transient.
|
||||
// An example is creating a new PostgresStore instance in a test function. In this
|
||||
// scenario, the cleanup goroutine (which will run forever) will prevent the
|
||||
// PostgresStore object from being garbage collected even after the test function
|
||||
// has finished. You can prevent this by manually calling StopCleanup.
|
||||
func (p *PostgresStore) StopCleanup() {
|
||||
if p.stopCleanup != nil {
|
||||
p.stopCleanup <- true
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PostgresStore) deleteExpired() error {
|
||||
_, err := p.db.Exec("DELETE FROM sessions WHERE expiry < current_timestamp")
|
||||
return err
|
||||
}
|
273
postgresstore/postgresstore_test.go
Normal file
273
postgresstore/postgresstore_test.go
Normal file
@ -0,0 +1,273 @@
|
||||
package postgresstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
func TestFind(t *testing.T) {
|
||||
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("TRUNCATE TABLE sessions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("INSERT INTO sessions VALUES('session_token', 'encoded_data', current_timestamp + interval '1 minute')")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := NewWithCleanupInterval(db, 0)
|
||||
|
||||
b, found, err := p.Find("session_token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if found != true {
|
||||
t.Fatalf("got %v: expected %v", found, true)
|
||||
}
|
||||
if bytes.Equal(b, []byte("encoded_data")) == false {
|
||||
t.Fatalf("got %v: expected %v", b, []byte("encoded_data"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindMissing(t *testing.T) {
|
||||
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("TRUNCATE TABLE sessions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := NewWithCleanupInterval(db, 0)
|
||||
|
||||
_, found, err := p.Find("missing_session_token")
|
||||
if err != nil {
|
||||
t.Fatalf("got %v: expected %v", err, nil)
|
||||
}
|
||||
if found != false {
|
||||
t.Fatalf("got %v: expected %v", found, false)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveNew(t *testing.T) {
|
||||
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("TRUNCATE TABLE sessions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := NewWithCleanupInterval(db, 0)
|
||||
|
||||
err = p.Commit("session_token", []byte("encoded_data"), time.Now().Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
row := db.QueryRow("SELECT data FROM sessions WHERE token = 'session_token'")
|
||||
var data []byte
|
||||
err = row.Scan(&data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reflect.DeepEqual(data, []byte("encoded_data")) == false {
|
||||
t.Fatalf("got %v: expected %v", data, []byte("encoded_data"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveUpdated(t *testing.T) {
|
||||
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("TRUNCATE TABLE sessions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("INSERT INTO sessions VALUES('session_token', 'encoded_data', current_timestamp + interval '1 minute')")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := NewWithCleanupInterval(db, 0)
|
||||
|
||||
err = p.Commit("session_token", []byte("new_encoded_data"), time.Now().Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
row := db.QueryRow("SELECT data FROM sessions WHERE token = 'session_token'")
|
||||
var data []byte
|
||||
err = row.Scan(&data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reflect.DeepEqual(data, []byte("new_encoded_data")) == false {
|
||||
t.Fatalf("got %v: expected %v", data, []byte("new_encoded_data"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiry(t *testing.T) {
|
||||
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("TRUNCATE TABLE sessions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := NewWithCleanupInterval(db, 0)
|
||||
|
||||
err = p.Commit("session_token", []byte("encoded_data"), time.Now().Add(100*time.Millisecond))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, found, _ := p.Find("session_token")
|
||||
if found != true {
|
||||
t.Fatalf("got %v: expected %v", found, true)
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
_, found, _ = p.Find("session_token")
|
||||
if found != false {
|
||||
t.Fatalf("got %v: expected %v", found, false)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete(t *testing.T) {
|
||||
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("TRUNCATE TABLE sessions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("INSERT INTO sessions VALUES('session_token', 'encoded_data', current_timestamp + interval '1 minute')")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := NewWithCleanupInterval(db, 0)
|
||||
|
||||
err = p.Delete("session_token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
row := db.QueryRow("SELECT COUNT(*) FROM sessions WHERE token = 'session_token'")
|
||||
var count int
|
||||
err = row.Scan(&count)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("got %d: expected %d", count, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanup(t *testing.T) {
|
||||
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec("TRUNCATE TABLE sessions")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := NewWithCleanupInterval(db, 200*time.Millisecond)
|
||||
defer p.StopCleanup()
|
||||
|
||||
err = p.Commit("session_token", []byte("encoded_data"), time.Now().Add(100*time.Millisecond))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
row := db.QueryRow("SELECT COUNT(*) FROM sessions WHERE token = 'session_token'")
|
||||
var count int
|
||||
err = row.Scan(&count)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("got %d: expected %d", count, 1)
|
||||
}
|
||||
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
row = db.QueryRow("SELECT COUNT(*) FROM sessions WHERE token = 'session_token'")
|
||||
err = row.Scan(&count)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("got %d: expected %d", count, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStopNilCleanup(t *testing.T) {
|
||||
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := NewWithCleanupInterval(db, 0)
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
// A send to a nil channel will block forever
|
||||
p.StopCleanup()
|
||||
}
|
Reference in New Issue
Block a user