1
0
mirror of https://github.com/alexedwards/scs.git synced 2024-11-24 08:32:19 +02:00

Add support to MSSQL store

This commit is contained in:
gandaldf 2021-11-23 10:42:00 +01:00
parent 116f5d40e8
commit 4b9db7318e
No known key found for this signature in database
GPG Key ID: FA7AC1A7F1169C06
6 changed files with 538 additions and 13 deletions

View File

@ -8,7 +8,7 @@
## Features
* Automatic loading and saving of session data via middleware.
* Choice of server-side session stores including PostgreSQL, MySQL, Redis, Badger, Bolt and BuntDB. Custom session stores are also supported.
* Choice of server-side session stores including PostgreSQL, MySQL, MSSQL, SQLite, Redis, MongoDB, Badger, Bolt and BuntDB. Custom session stores are also supported.
* Supports multiple sessions per request, 'flash' messages, session token regeneration, idle and absolute session timeouts, and 'remember me' functionality.
* Easy to extend and customize. Communicate session tokens to/from clients in HTTP headers or request/response bodies.
* Efficient design. Smaller, faster and uses less memory than [gorilla/sessions](https://github.com/gorilla/sessions).
@ -145,18 +145,19 @@ By default SCS uses an in-memory store for session data. This is convenient (no
The session stores currently included are shown in the table below. Please click the links for usage instructions and examples.
| Package | |
|:------------------------------------------------------------------------------------- |----------------------------------------------------------------------------------|
| [badgerstore](https://github.com/alexedwards/scs/tree/master/badgerstore) | Badger based session store |
| [boltstore](https://github.com/alexedwards/scs/tree/master/boltstore) | Bolt based session store |
| [buntdbstore](https://github.com/alexedwards/scs/tree/master/buntdbstore) | BuntDB based session store |
| [memstore](https://github.com/alexedwards/scs/tree/master/memstore) | In-memory session store (default) |
| [mongodbstore](https://github.com/alexedwards/scs/tree/master/mongodbstore) | MongoDB based session store |
| [mysqlstore](https://github.com/alexedwards/scs/tree/master/mysqlstore) | MySQL based session store |
| [postgresstore](https://github.com/alexedwards/scs/tree/master/postgresstore) | PostgreSQL based session store (using the [pq](https://github.com/lib/pq) driver) |
| [pgxstore](https://github.com/alexedwards/scs/tree/master/pgxstore) | PostgreSQL based session store (using the [pgx](https://github.com/jackc/pgx) driver) |
| [redisstore](https://github.com/alexedwards/scs/tree/master/redisstore) | Redis based session store |
| [sqlite3store](https://github.com/alexedwards/scs/tree/master/sqlite3store) | SQLite3 based session store |
| Package | |
|:------------------------------------------------------------------------------------- |---------------------------------------------------------------------------------------|
| [badgerstore](https://github.com/alexedwards/scs/tree/master/badgerstore) | Badger based session store |
| [boltstore](https://github.com/alexedwards/scs/tree/master/boltstore) | Bolt based session store |
| [buntdbstore](https://github.com/alexedwards/scs/tree/master/buntdbstore) | BuntDB based session store |
| [memstore](https://github.com/alexedwards/scs/tree/master/memstore) | In-memory session store (default) |
| [mongodbstore](https://github.com/alexedwards/scs/tree/master/mongodbstore) | MongoDB based session store |
| [mssqlstore](https://github.com/alexedwards/scs/tree/master/mssqlstore) | MSSQL based session store |
| [mysqlstore](https://github.com/alexedwards/scs/tree/master/mysqlstore) | MySQL based session store |
| [pgxstore](https://github.com/alexedwards/scs/tree/master/pgxstore) | PostgreSQL based session store (using the [pgx](https://github.com/jackc/pgx) driver) |
| [postgresstore](https://github.com/alexedwards/scs/tree/master/postgresstore) | PostgreSQL based session store (using the [pq](https://github.com/lib/pq) driver) |
| [redisstore](https://github.com/alexedwards/scs/tree/master/redisstore) | Redis based session store |
| [sqlite3store](https://github.com/alexedwards/scs/tree/master/sqlite3store) | SQLite3 based session store |
Custom session stores are also supported. Please [see here](#using-custom-session-stores) for more information.

103
mssqlstore/README.md Normal file
View File

@ -0,0 +1,103 @@
# mssqlstore
A MSSQL-based session store supporting the [denisenkom/go-mssqldb](https://github.com/denisenkom/go-mssqldb) driver.
## Setup
You should have a working MSSQL database containing a `sessions` table with the definition:
```sql
CREATE TABLE sessions (
token CHAR(43) PRIMARY KEY,
data VARBINARY(MAX) NOT NULL,
expiry DATETIME2(6) 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/mssqlstore"
_ "github.com/denisenkom/go-mssqldb"
)
var sessionManager *scs.SessionManager
func main() {
db, err := sql.Open("sqlserver", "sqlserver://username:password@host?database=dbname")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Initialize a new session manager and configure it to use MSSQL as
// the session store.
sessionManager = scs.New()
sessionManager.Store = mssqlstore.New(db)
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
sessionManager.Put(r.Context(), "message", "Hello from a session!")
}
func getHandler(w http.ResponseWriter, r *http.Request) {
msg := sessionManager.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.
mssqlstore.NewWithCleanupInterval(db, 30*time.Minute)
// Disable the cleanup goroutine by setting the cleanup interval to zero.
mssqlstore.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("sqlserver", "sqlserver://username:password@host?database=dbname")
if err != nil {
t.Fatal(err)
}
defer db.Close()
store := mssqlstore.New(db)
defer store.StopCleanup()
sessionManager = scs.New()
sessionManager.Store = store
// Run test...
}
```

5
mssqlstore/go.mod Normal file
View File

@ -0,0 +1,5 @@
module github.com/alexedwards/scs/mssqlstore
go 1.12
require github.com/denisenkom/go-mssqldb v0.11.0

7
mssqlstore/go.sum Normal file
View File

@ -0,0 +1,7 @@
github.com/denisenkom/go-mssqldb v0.11.0 h1:9rHa233rhdOyrz2GcP9NM+gi2psgJZ4GWDpL/7ND8HI=
github.com/denisenkom/go-mssqldb v0.11.0/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI=
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=

136
mssqlstore/mssqlstore.go Normal file
View File

@ -0,0 +1,136 @@
package mssqlstore
import (
"database/sql"
"log"
"time"
)
// MSSQLStore represents the session store.
type MSSQLStore struct {
db *sql.DB
stopCleanup chan bool
}
// New returns a new MSSQLStore instance, with a background cleanup goroutine
// that runs every 5 minutes to remove expired session data.
func New(db *sql.DB) *MSSQLStore {
return NewWithCleanupInterval(db, 5*time.Minute)
}
// NewWithCleanupInterval returns a new MSSQLStore 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) *MSSQLStore {
m := &MSSQLStore{db: db}
if cleanupInterval > 0 {
go m.startCleanup(cleanupInterval)
}
return m
}
// Find returns the data for a given session token from the MSSQLStore instance.
// If the session token is not found or is expired, the returned exists flag will
// be set to false.
func (m *MSSQLStore) Find(token string) (b []byte, exists bool, err error) {
row := m.db.QueryRow("SELECT data FROM sessions WHERE token = @p1 AND GETUTCDATE() < 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 MSSQLStore instance with the
// given expiry time. If the session token already exists, then the data and expiry
// time are updated.
func (m *MSSQLStore) Commit(token string, b []byte, expiry time.Time) error {
_, err := m.db.Exec(`MERGE INTO sessions WITH (HOLDLOCK) AS T USING (VALUES(@p1)) AS S (token) ON (T.token = S.token)
WHEN MATCHED THEN UPDATE SET data = @p2, expiry = @p3
WHEN NOT MATCHED THEN INSERT (token, data, expiry) VALUES(@p1, @p2, @p3);`, token, b, expiry.UTC())
if err != nil {
return err
}
return nil
}
// Delete removes a session token and corresponding data from the MSSQLStore
// instance.
func (m *MSSQLStore) Delete(token string) error {
_, err := m.db.Exec("DELETE FROM sessions WHERE token = @p1", token)
return err
}
// All returns a map containing the token and data for all active (i.e.
// not expired) sessions in the MSSQLStore instance.
func (m *MSSQLStore) All() (map[string][]byte, error) {
rows, err := m.db.Query("SELECT token, data FROM sessions WHERE GETUTCDATE() < expiry")
if err != nil {
return nil, err
}
defer rows.Close()
sessions := make(map[string][]byte)
for rows.Next() {
var (
token string
data []byte
)
err = rows.Scan(&token, &data)
if err != nil {
return nil, err
}
sessions[token] = data
}
err = rows.Err()
if err != nil {
return nil, err
}
return sessions, nil
}
func (m *MSSQLStore) startCleanup(interval time.Duration) {
m.stopCleanup = make(chan bool)
ticker := time.NewTicker(interval)
for {
select {
case <-ticker.C:
err := m.deleteExpired()
if err != nil {
log.Println(err)
}
case <-m.stopCleanup:
ticker.Stop()
return
}
}
}
// StopCleanup terminates the background cleanup goroutine for the MSSQLStore
// instance. It's rare to terminate this; generally MSSQLStore 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 MSSQLStore is transient.
// An example is creating a new MSSQLStore instance in a test function. In this
// scenario, the cleanup goroutine (which will run forever) will prevent the
// MSSQLStore object from being garbage collected even after the test function
// has finished. You can prevent this by manually calling StopCleanup.
func (m *MSSQLStore) StopCleanup() {
if m.stopCleanup != nil {
m.stopCleanup <- true
}
}
func (m *MSSQLStore) deleteExpired() error {
_, err := m.db.Exec("DELETE FROM sessions WHERE expiry < GETUTCDATE()")
return err
}

View File

@ -0,0 +1,273 @@
package mssqlstore
import (
"bytes"
"database/sql"
"os"
"reflect"
"testing"
"time"
_ "github.com/denisenkom/go-mssqldb"
)
func TestFind(t *testing.T) {
dsn := os.Getenv("SCS_MSSQL_TEST_DSN")
db, err := sql.Open("sqlserver", 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', CONVERT(varbinary, 'encoded_data'), DATEADD(MINUTE, 1, GETUTCDATE()))")
if err != nil {
t.Fatal(err)
}
m := NewWithCleanupInterval(db, 0)
b, found, err := m.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_MSSQL_TEST_DSN")
db, err := sql.Open("sqlserver", 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)
}
m := NewWithCleanupInterval(db, 0)
_, found, err := m.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_MSSQL_TEST_DSN")
db, err := sql.Open("sqlserver", 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)
}
m := NewWithCleanupInterval(db, 0)
err = m.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_MSSQL_TEST_DSN")
db, err := sql.Open("sqlserver", 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', CONVERT(varbinary, 'encoded_data'), DATEADD(MINUTE, 1, GETUTCDATE()))")
if err != nil {
t.Fatal(err)
}
m := NewWithCleanupInterval(db, 0)
err = m.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_MSSQL_TEST_DSN")
db, err := sql.Open("sqlserver", 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)
}
m := NewWithCleanupInterval(db, 0)
err = m.Commit("session_token", []byte("encoded_data"), time.Now().Add(1*time.Second))
if err != nil {
t.Fatal(err)
}
_, found, _ := m.Find("session_token")
if found != true {
t.Fatalf("got %v: expected %v", found, true)
}
time.Sleep(2 * time.Second)
_, found, _ = m.Find("session_token")
if found != false {
t.Fatalf("got %v: expected %v", found, false)
}
}
func TestDelete(t *testing.T) {
dsn := os.Getenv("SCS_MSSQL_TEST_DSN")
db, err := sql.Open("sqlserver", 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', CONVERT(varbinary, 'encoded_data'), DATEADD(MINUTE, 1, GETUTCDATE()))")
if err != nil {
t.Fatal(err)
}
m := NewWithCleanupInterval(db, 0)
err = m.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_MSSQL_TEST_DSN")
db, err := sql.Open("sqlserver", 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)
}
m := NewWithCleanupInterval(db, 2*time.Second)
defer m.StopCleanup()
err = m.Commit("session_token", []byte("encoded_data"), time.Now().Add(1*time.Second))
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(3 * time.Second)
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_MSSQL_TEST_DSN")
db, err := sql.Open("sqlserver", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err = db.Ping(); err != nil {
t.Fatal(err)
}
m := NewWithCleanupInterval(db, 0)
time.Sleep(1 * time.Second)
// A send to a nil channel will block forever
m.StopCleanup()
}