1
0
mirror of https://github.com/alexedwards/scs.git synced 2025-07-13 01:00:17 +02:00

Alias Session to SessionManager and NewSession to New

This commit is contained in:
Alex Edwards
2019-06-18 12:49:37 +02:00
parent d74621f361
commit 1e47e13c24
9 changed files with 138 additions and 128 deletions

View File

@ -46,34 +46,35 @@ package main
import (
"io"
"net/http"
"time"
"github.com/alexedwards/scs/v2"
)
var session *scs.Session
var sessionManager *scs.SessionManager
func main() {
// Initialize the session manager and configure the session lifetime.
session = scs.NewSession()
session.Lifetime = 24 * time.Hour
// Initialize a new session manager and configure the session lifetime.
sessionManager = scs.New()
sessionManager.Lifetime = 24 * time.Hour
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
// Wrap your handlers with the LoadAndSave() middleware.
http.ListenAndServe(":4000", session.LoadAndSave(mux))
http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
// Store a new key and value in the session data.
session.Put(r.Context(), "message", "Hello from a session!")
sessionManager.Put(r.Context(), "message", "Hello from a session!")
}
func getHandler(w http.ResponseWriter, r *http.Request) {
// Use the GetString helper to retrieve the string value associated with a
// key. The zero value is returned if the key does not exist.
msg := session.GetString(r.Context(), "message")
msg := sessionManager.GetString(r.Context(), "message")
io.WriteString(w, msg)
}
```
@ -98,40 +99,40 @@ Hello from a session!
### Configuring Session Behavior
Session behavior can be configured via the `Session` fields.
Session behavior can be configured via the `SessionManager` fields.
```go
session = scs.NewSession()
session.Lifetime = 3 * time.Hour
session.IdleTimeout = 20 * time.Minute
session.Cookie.Name = "session_id"
session.Cookie.Domain = "example.com"
session.Cookie.HttpOnly = true
session.Cookie.Path = "/example/"
session.Cookie.Persist = true
session.Cookie.SameSite = http.SameSiteStrictMode
session.Cookie.Secure = true
sessionManager = scs.New()
sessionManager.Lifetime = 3 * time.Hour
sessionManager.IdleTimeout = 20 * time.Minute
sessionManager.Cookie.Name = "session_id"
sessionManager.Cookie.Domain = "example.com"
sessionManager.Cookie.HttpOnly = true
sessionManager.Cookie.Path = "/example/"
sessionManager.Cookie.Persist = true
sessionManager.Cookie.SameSite = http.SameSiteStrictMode
sessionManager.Cookie.Secure = true
```
Documentation for all available settings and their default values can be [found here](https://godoc.org/github.com/alexedwards/scs#Session).
Documentation for all available settings and their default values can be [found here](https://godoc.org/github.com/alexedwards/scs#SessionManager).
### Working with Session Data
Data can be set using the [`Put()`](https://godoc.org/github.com/alexedwards/scs#Session.Put) method and retrieved with the [`Get()`](https://godoc.org/github.com/alexedwards/scs#Session.Get) method. A variety of helper methods like [`GetString()`](https://godoc.org/github.com/alexedwards/scs#Session.GetString), [`GetInt()`](https://godoc.org/github.com/alexedwards/scs#Session.GetInt) and [`GetBytes()`](https://godoc.org/github.com/alexedwards/scs#Session.GetBytes) are included for common data types. Please see [the documentation](https://godoc.org/github.com/alexedwards/scs#pkg-index) for a full list of helper methods.
Data can be set using the [`Put()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Put) method and retrieved with the [`Get()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Get) method. A variety of helper methods like [`GetString()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetString), [`GetInt()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetInt) and [`GetBytes()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetBytes) are included for common data types. Please see [the documentation](https://godoc.org/github.com/alexedwards/scs#pkg-index) for a full list of helper methods.
The [`Pop()`](https://godoc.org/github.com/alexedwards/scs#Session.Pop) method (and accompanying helpers for common data types) act like a one-time `Get()`, retrieving the data and removing it from the session in one step. These are useful if you want to implement 'flash' message functionality in your application, where messages are displayed to the user once only.
The [`Pop()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Pop) method (and accompanying helpers for common data types) act like a one-time `Get()`, retrieving the data and removing it from the session in one step. These are useful if you want to implement 'flash' message functionality in your application, where messages are displayed to the user once only.
Some other useful functions are [`Exists()`](https://godoc.org/github.com/alexedwards/scs#Session.Exists) (which returns a `bool` indicating whether or not a given key exists in the session data) and [`Keys()`](https://godoc.org/github.com/alexedwards/scs#Session.Keys) (which returns a sorted slice of keys in the session data).
Some other useful functions are [`Exists()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Exists) (which returns a `bool` indicating whether or not a given key exists in the session data) and [`Keys()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Keys) (which returns a sorted slice of keys in the session data).
Individual data items can be deleted from the session using the [`Remove()`](https://godoc.org/github.com/alexedwards/scs#Session.Remove) method. Alternatively, all session data can de deleted by using the [`Destroy()`](https://godoc.org/github.com/alexedwards/scs#Session.Destroy) method. After calling `Destroy()`, any further operations in the same request cycle will result in a new session being created --- with a new session token and a new lifetime.
Individual data items can be deleted from the session using the [`Remove()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Remove) method. Alternatively, all session data can de deleted by using the [`Destroy()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Destroy) method. After calling `Destroy()`, any further operations in the same request cycle will result in a new session being created --- with a new session token and a new lifetime.
Behind the scenes SCS uses gob encoding to store session data, so if you want to store custom types in the session data they must be [registered](https://golang.org/pkg/encoding/gob/#Register) with the encoding/gob package first. Struct fields of custom types must also be exported so that they are visible to the encoding/gob package. Please [see here](https://gist.github.com/alexedwards/d6eca7136f98ec12ad606e774d3abad3) for a working example.
### Loading and Saving Sessions
Most applications will use the [`LoadAndSave()`](https://godoc.org/github.com/alexedwards/scs#Session.LoadAndSave) middleware. This middleware takes care of loading and committing session data to the session store, and communicating the session token to/from the client in a cookie as necessary.
Most applications will use the [`LoadAndSave()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.LoadAndSave) middleware. This middleware takes care of loading and committing session data to the session store, and communicating the session token to/from the client in a cookie as necessary.
If you want to communicate the session token to/from the client in a different way (for example in a different HTTP header) you are encouraged to create your own alternative middleware using the code in [`LoadAndSave()`](https://godoc.org/github.com/alexedwards/scs#Session.LoadAndSave) as a template. An example is [given here](https://gist.github.com/alexedwards/cc6190195acfa466bf27f05aa5023f50).
If you want to communicate the session token to/from the client in a different way (for example in a different HTTP header) you are encouraged to create your own alternative middleware using the code in [`LoadAndSave()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.LoadAndSave) as a template. An example is [given here](https://gist.github.com/alexedwards/cc6190195acfa466bf27f05aa5023f50).
Or for more fine-grained control you can load and save sessions within your individual handlers (or from anywhere in your application). [See here](https://gist.github.com/alexedwards/0570e5a59677e278e13acb8ea53a3b30) for an example.
@ -178,21 +179,21 @@ type Store interface {
### Preventing Session Fixation
To help prevent session fixation attacks you should [renew the session token after any privilege level change](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change). Commonly, this means that the session token must to be changed when a user logs in or out of your application. You can do this using the [`RenewToken()`](https://godoc.org/github.com/alexedwards/scs#Session.RenewToken) method like so:
To help prevent session fixation attacks you should [renew the session token after any privilege level change](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change). Commonly, this means that the session token must to be changed when a user logs in or out of your application. You can do this using the [`RenewToken()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.RenewToken) method like so:
```go
func loginHandler(w http.ResponseWriter, r *http.Request) {
userID := 123
// First renew the session token...
err := session.RenewToken(r.Context())
err := sessionManager.RenewToken(r.Context())
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// Then make the privilege-level change.
session.Put(r.Context(), "userID", userID)
sessionManager.Put(r.Context(), "userID", userID)
}
```

View File

@ -20,7 +20,7 @@ import (
"go.etcd.io/bbolt"
)
var session *scs.Session
var sessionManager *scs.SessionManager
func main() {
// Establish a Bolt database.
@ -32,23 +32,23 @@ func main() {
// Initialize a new session manager and configure it to use boltstore as
// the session store.
session = scs.NewSession()
session.Store = boltstore.NewWithCleanupInterval(db, 20*time.Second)
session.Lifetime = time.Minute
sessionManager = scs.New()
sessionManager.Store = boltstore.NewWithCleanupInterval(db, 20*time.Second)
sessionManager.Lifetime = time.Minute
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", session.LoadAndSave(mux))
http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "message", "Hello from a session!")
sessionManager.Put(r.Context(), "message", "Hello from a session!")
}
func getHandler(w http.ResponseWriter, r *http.Request) {
msg := session.GetString(r.Context(), "message")
msg := sessionManager.GetString(r.Context(), "message")
io.WriteString(w, msg)
}
```
@ -82,8 +82,8 @@ func TestExample(t *testing.T) {
store := boltstore.New(db)
defer store.StopCleanup()
session = scs.NewSession()
session.Store = store
sessionManager = scs.New()
sessionManager.Store = store
// Run test...
}

52
data.go
View File

@ -51,7 +51,7 @@ func newSessionData(lifetime time.Duration) *sessionData {
//
// Most applications will use the LoadAndSave() middleware and will not need to
// use this method.
func (s *Session) Load(ctx context.Context, token string) (context.Context, error) {
func (s *SessionManager) Load(ctx context.Context, token string) (context.Context, error) {
if _, ok := ctx.Value(s.contextKey).(*sessionData); ok {
return ctx, nil
}
@ -90,7 +90,7 @@ func (s *Session) Load(ctx context.Context, token string) (context.Context, erro
//
// Most applications will use the LoadAndSave() middleware and will not need to
// use this method.
func (s *Session) Commit(ctx context.Context) (string, time.Time, error) {
func (s *SessionManager) Commit(ctx context.Context) (string, time.Time, error) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -128,7 +128,7 @@ func (s *Session) Commit(ctx context.Context) (string, time.Time, error) {
// Destroy deletes the session data from the session store and sets the session
// status to Destroyed. Any further operations in the same request cycle will
// result in a new session being created.
func (s *Session) Destroy(ctx context.Context) error {
func (s *SessionManager) Destroy(ctx context.Context) error {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -154,7 +154,7 @@ func (s *Session) Destroy(ctx context.Context) error {
// Put adds a key and corresponding value to the session data. Any existing
// value for the key will be replaced. The session data status will be set to
// Modified.
func (s *Session) Put(ctx context.Context, key string, val interface{}) {
func (s *SessionManager) Put(ctx context.Context, key string, val interface{}) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -174,7 +174,7 @@ func (s *Session) Put(ctx context.Context, key string, val interface{}) {
//
// Also see the GetString(), GetInt(), GetBytes() and other helper methods which
// wrap the type conversion for common types.
func (s *Session) Get(ctx context.Context, key string) interface{} {
func (s *SessionManager) Get(ctx context.Context, key string) interface{} {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -187,7 +187,7 @@ func (s *Session) Get(ctx context.Context, key string) interface{} {
// session data and deletes the key and value from the session data. The
// session data status will be set to Modified. The return value has the type
// interface{} so will usually need to be type asserted before you can use it.
func (s *Session) Pop(ctx context.Context, key string) interface{} {
func (s *SessionManager) Pop(ctx context.Context, key string) interface{} {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -206,7 +206,7 @@ func (s *Session) Pop(ctx context.Context, key string) interface{} {
// Remove deletes the given key and corresponding value from the session data.
// The session data status will be set to Modified. If the key is not present
// this operation is a no-op.
func (s *Session) Remove(ctx context.Context, key string) {
func (s *SessionManager) Remove(ctx context.Context, key string) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -224,7 +224,7 @@ func (s *Session) Remove(ctx context.Context, key string) {
// Clear removes all data for the current session. The session token and
// lifetime are unaffected. If there is no data in the current session this is
// a no-op.
func (s *Session) Clear(ctx context.Context) error {
func (s *SessionManager) Clear(ctx context.Context) error {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -242,7 +242,7 @@ func (s *Session) Clear(ctx context.Context) error {
}
// Exists returns true if the given key is present in the session data.
func (s *Session) Exists(ctx context.Context, key string) bool {
func (s *SessionManager) Exists(ctx context.Context, key string) bool {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -255,7 +255,7 @@ func (s *Session) Exists(ctx context.Context, key string) bool {
// Keys returns a slice of all key names present in the session data, sorted
// alphabetically. If the data contains no data then an empty slice will be
// returned.
func (s *Session) Keys(ctx context.Context) []string {
func (s *SessionManager) Keys(ctx context.Context) []string {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -281,7 +281,7 @@ func (s *Session) Keys(ctx context.Context) []string {
// RenewToken before making any changes to privilege levels (e.g. login and
// logout operations). See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change
// for additional information.
func (s *Session) RenewToken(ctx context.Context) error {
func (s *SessionManager) RenewToken(ctx context.Context) error {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -305,7 +305,7 @@ func (s *Session) RenewToken(ctx context.Context) error {
}
// Status returns the current status of the session data.
func (s *Session) Status(ctx context.Context) Status {
func (s *SessionManager) Status(ctx context.Context) Status {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
@ -317,7 +317,7 @@ func (s *Session) Status(ctx context.Context) Status {
// GetString returns the string value for a given key from the session data.
// The zero value for a string ("") is returned if the key does not exist or the
// value could not be type asserted to a string.
func (s *Session) GetString(ctx context.Context, key string) string {
func (s *SessionManager) GetString(ctx context.Context, key string) string {
val := s.Get(ctx, key)
str, ok := val.(string)
if !ok {
@ -329,7 +329,7 @@ func (s *Session) GetString(ctx context.Context, key string) string {
// GetBool returns the bool value for a given key from the session data. The
// zero value for a bool (false) is returned if the key does not exist or the
// value could not be type asserted to a bool.
func (s *Session) GetBool(ctx context.Context, key string) bool {
func (s *SessionManager) GetBool(ctx context.Context, key string) bool {
val := s.Get(ctx, key)
b, ok := val.(bool)
if !ok {
@ -341,7 +341,7 @@ func (s *Session) GetBool(ctx context.Context, key string) bool {
// GetInt returns the int value for a given key from the session data. The
// zero value for an int (0) is returned if the key does not exist or the
// value could not be type asserted to an int.
func (s *Session) GetInt(ctx context.Context, key string) int {
func (s *SessionManager) GetInt(ctx context.Context, key string) int {
val := s.Get(ctx, key)
i, ok := val.(int)
if !ok {
@ -353,7 +353,7 @@ func (s *Session) GetInt(ctx context.Context, key string) int {
// GetFloat returns the float64 value for a given key from the session data. The
// zero value for an float64 (0) is returned if the key does not exist or the
// value could not be type asserted to a float64.
func (s *Session) GetFloat(ctx context.Context, key string) float64 {
func (s *SessionManager) GetFloat(ctx context.Context, key string) float64 {
val := s.Get(ctx, key)
f, ok := val.(float64)
if !ok {
@ -365,7 +365,7 @@ func (s *Session) GetFloat(ctx context.Context, key string) float64 {
// GetBytes returns the byte slice ([]byte) value for a given key from the session
// data. The zero value for a slice (nil) is returned if the key does not exist
// or could not be type asserted to []byte.
func (s *Session) GetBytes(ctx context.Context, key string) []byte {
func (s *SessionManager) GetBytes(ctx context.Context, key string) []byte {
val := s.Get(ctx, key)
b, ok := val.([]byte)
if !ok {
@ -378,7 +378,7 @@ func (s *Session) GetBytes(ctx context.Context, key string) []byte {
// zero value for a time.Time object is returned if the key does not exist or the
// value could not be type asserted to a time.Time. This can be tested with the
// time.IsZero() method.
func (s *Session) GetTime(ctx context.Context, key string) time.Time {
func (s *SessionManager) GetTime(ctx context.Context, key string) time.Time {
val := s.Get(ctx, key)
t, ok := val.(time.Time)
if !ok {
@ -391,7 +391,7 @@ func (s *Session) GetTime(ctx context.Context, key string) time.Time {
// session data. The session data status will be set to Modified. The zero
// value for a string ("") is returned if the key does not exist or the value
// could not be type asserted to a string.
func (s *Session) PopString(ctx context.Context, key string) string {
func (s *SessionManager) PopString(ctx context.Context, key string) string {
val := s.Pop(ctx, key)
str, ok := val.(string)
if !ok {
@ -404,7 +404,7 @@ func (s *Session) PopString(ctx context.Context, key string) string {
// session data. The session data status will be set to Modified. The zero
// value for a bool (false) is returned if the key does not exist or the value
// could not be type asserted to a bool.
func (s *Session) PopBool(ctx context.Context, key string) bool {
func (s *SessionManager) PopBool(ctx context.Context, key string) bool {
val := s.Pop(ctx, key)
b, ok := val.(bool)
if !ok {
@ -417,7 +417,7 @@ func (s *Session) PopBool(ctx context.Context, key string) bool {
// session data. The session data status will be set to Modified. The zero
// value for an int (0) is returned if the key does not exist or the value could
// not be type asserted to an int.
func (s *Session) PopInt(ctx context.Context, key string) int {
func (s *SessionManager) PopInt(ctx context.Context, key string) int {
val := s.Pop(ctx, key)
i, ok := val.(int)
if !ok {
@ -430,7 +430,7 @@ func (s *Session) PopInt(ctx context.Context, key string) int {
// session data. The session data status will be set to Modified. The zero
// value for an float64 (0) is returned if the key does not exist or the value
// could not be type asserted to a float64.
func (s *Session) PopFloat(ctx context.Context, key string) float64 {
func (s *SessionManager) PopFloat(ctx context.Context, key string) float64 {
val := s.Pop(ctx, key)
f, ok := val.(float64)
if !ok {
@ -443,7 +443,7 @@ func (s *Session) PopFloat(ctx context.Context, key string) float64 {
// deletes it from the from the session data. The session data status will be
// set to Modified. The zero value for a slice (nil) is returned if the key does
// not exist or could not be type asserted to []byte.
func (s *Session) PopBytes(ctx context.Context, key string) []byte {
func (s *SessionManager) PopBytes(ctx context.Context, key string) []byte {
val := s.Pop(ctx, key)
b, ok := val.([]byte)
if !ok {
@ -456,7 +456,7 @@ func (s *Session) PopBytes(ctx context.Context, key string) []byte {
// the session data. The session data status will be set to Modified. The zero
// value for a time.Time object is returned if the key does not exist or the
// value could not be type asserted to a time.Time.
func (s *Session) PopTime(ctx context.Context, key string) time.Time {
func (s *SessionManager) PopTime(ctx context.Context, key string) time.Time {
val := s.Pop(ctx, key)
t, ok := val.(time.Time)
if !ok {
@ -465,11 +465,11 @@ func (s *Session) PopTime(ctx context.Context, key string) time.Time {
return t
}
func (s *Session) addSessionDataToContext(ctx context.Context, sd *sessionData) context.Context {
func (s *SessionManager) addSessionDataToContext(ctx context.Context, sd *sessionData) context.Context {
return context.WithValue(ctx, s.contextKey, sd)
}
func (s *Session) getSessionDataFromContext(ctx context.Context) *sessionData {
func (s *SessionManager) getSessionDataFromContext(ctx context.Context) *sessionData {
c, ok := ctx.Value(s.contextKey).(*sessionData)
if !ok {
panic("scs: no session data in context")

View File

@ -18,27 +18,27 @@ import (
"github.com/alexedwards/scs/v2/memstore"
)
var session *scs.Session
var sessionManager *scs.SessionManager
func main() {
// Initialize a new session manager and configure it to use memstore as
// the session store.
session = scs.NewSession()
session.Store = memstore.New()
sessionManager = scs.New()
sessionManager.Store = memstore.New()
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", session.LoadAndSave(mux))
http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "message", "Hello from a session!")
sessionManager.Put(r.Context(), "message", "Hello from a session!")
}
func getHandler(w http.ResponseWriter, r *http.Request) {
msg := session.GetString(r.Context(), "message")
msg := sessionManager.GetString(r.Context(), "message")
io.WriteString(w, msg)
}
```
@ -66,8 +66,8 @@ func TestExample(t *testing.T) {
store := memstore.New()
defer store.StopCleanup()
session = scs.NewSession()
session.Store = store
sessionManager = scs.New()
sessionManager.Store = store
// Run test...
}

View File

@ -35,7 +35,7 @@ import (
_ "github.com/go-sql-driver/mysql"
)
var session *scs.Session
var sessionManager *scs.SessionManager
func main() {
db, err := sql.Open("mysql", "user:pass@/db?parseTime=true")
@ -46,22 +46,22 @@ func main() {
// Initialize a new session manager and configure it to use MySQL as
// the session store.
session = scs.NewSession()
session.Store = mysqlstore.New(db)
sessionManager = scs.New()
sessionManager.Store = mysqlstore.New(db)
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", session.LoadAndSave(mux))
http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "message", "Hello from a session!")
sessionManager.Put(r.Context(), "message", "Hello from a session!")
}
func getHandler(w http.ResponseWriter, r *http.Request) {
msg := session.GetString(r.Context(), "message")
msg := sessionManager.GetString(r.Context(), "message")
io.WriteString(w, msg)
}
```
@ -95,8 +95,8 @@ func TestExample(t *testing.T) {
store := mysqlstore.New(db)
defer store.StopCleanup()
session = scs.NewSession()
session.Store = store
sessionManager = scs.New()
sessionManager.Store = store
// Run test...
}

View File

@ -35,7 +35,7 @@ import (
_ "github.com/lib/pq"
)
var session *scs.Session
var sessionManager *scs.SessionManager
func main() {
db, err := sql.Open("postgres", "postgres://user:pass@localhost/db")
@ -46,22 +46,22 @@ func main() {
// Initialize a new session manager and configure it to use PostgreSQL as
// the session store.
session = scs.NewSession()
session.Store = postgresstore.New(db)
sessionManager = scs.New()
sessionManager.Store = postgresstore.New(db)
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", session.LoadAndSave(mux))
http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "message", "Hello from a session!")
sessionManager.Put(r.Context(), "message", "Hello from a session!")
}
func getHandler(w http.ResponseWriter, r *http.Request) {
msg := session.GetString(r.Context(), "message")
msg := sessionManager.GetString(r.Context(), "message")
io.WriteString(w, msg)
}
```
@ -95,8 +95,8 @@ func TestExample(t *testing.T) {
store := postgresstore.New(db)
defer store.StopCleanup()
session = scs.NewSession()
session.Store = store
sessionManager = scs.New()
sessionManager.Store = store
// Run test...
}

View File

@ -18,7 +18,7 @@ import (
"github.com/gomodule/redigo/redis"
)
var session *scs.Session
var sessionManager *scs.SessionManager
func main() {
// Establish a redigo connection pool.
@ -31,22 +31,22 @@ func main() {
// Initialize a new session manager and configure it to use redisstore as
// the session store.
session = scs.NewSession()
session.Store = redisstore.New(pool)
sessionManager = scs.New()
sessionManager.Store = redisstore.New(pool)
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", session.LoadAndSave(mux))
http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "message", "Hello from a session!")
sessionManager.Put(r.Context(), "message", "Hello from a session!")
}
func getHandler(w http.ResponseWriter, r *http.Request) {
msg := session.GetString(r.Context(), "message")
msg := sessionManager.GetString(r.Context(), "message")
io.WriteString(w, msg)
}
```
@ -73,9 +73,9 @@ pool := &redis.Pool{
},
}
sessionOne = scs.NewSession()
sessionOne.Store = redisstore.NewWithPrefix(pool, "scs:session:1:")
sessionManagerOne = scs.New()
sessionManagerOne.Store = redisstore.NewWithPrefix(pool, "scs:session:1:")
sessionTwo = scs.NewSession()
sessionTwo.Store = redisstore.NewWithPrefix(pool, "scs:session:2:")
sessionManagerTwo = scs.New()
sessionManagerTwo.Store = redisstore.NewWithPrefix(pool, "scs:session:2:")
```

View File

@ -9,8 +9,11 @@ import (
"github.com/alexedwards/scs/v2/memstore"
)
// Session holds the configuration settings for your sessions.
type Session struct {
// Deprecated: Session is a backwards-compatible alias for SessionManager.
type Session = SessionManager
// SessionManager holds the configuration settings for your sessions.
type SessionManager struct {
// IdleTimeout controls the maximum length of time a session can be inactive
// before it expires. For example, some applications may wish to set this so
// there is a timeout after 20 minutes of inactivity. By default IdleTimeout
@ -75,10 +78,10 @@ type SessionCookie struct {
Secure bool
}
// NewSession returns a new session manager with the default options. It is
// safe for concurrent use.
func NewSession() *Session {
s := &Session{
// New returns a new session manager with the default options. It is safe for
// concurrent use.
func New() *SessionManager {
s := &SessionManager{
IdleTimeout: 0,
Lifetime: 24 * time.Hour,
Store: memstore.New(),
@ -96,10 +99,16 @@ func NewSession() *Session {
return s
}
// Deprecated: NewSession is a backwards-compatible alias for New. Use the New
// function instead.
func NewSession() *SessionManager {
return New()
}
// LoadAndSave provides middleware which automatically loads and saves session
// data for the current request, and communicates the session token to and from
// the client in a cookie.
func (s *Session) LoadAndSave(next http.Handler) http.Handler {
func (s *SessionManager) LoadAndSave(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var token string
cookie, err := r.Cookie(s.Cookie.Name)
@ -138,7 +147,7 @@ func (s *Session) LoadAndSave(next http.Handler) http.Handler {
})
}
func (s *Session) writeSessionCookie(w http.ResponseWriter, token string, expiry time.Time) {
func (s *SessionManager) writeSessionCookie(w http.ResponseWriter, token string, expiry time.Time) {
cookie := &http.Cookie{
Name: s.Cookie.Name,
Value: token,

View File

@ -52,18 +52,18 @@ func extractTokenFromCookie(c string) string {
}
func TestEnable(t *testing.T) {
session := NewSession()
sessionManager := New()
mux := http.NewServeMux()
mux.HandleFunc("/put", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "foo", "bar")
sessionManager.Put(r.Context(), "foo", "bar")
}))
mux.HandleFunc("/get", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := session.Get(r.Context(), "foo").(string)
s := sessionManager.Get(r.Context(), "foo").(string)
w.Write([]byte(s))
}))
ts := newTestServer(t, session.LoadAndSave(mux))
ts := newTestServer(t, sessionManager.LoadAndSave(mux))
defer ts.Close()
header, _ := ts.execute(t, "/put")
@ -85,15 +85,15 @@ func TestEnable(t *testing.T) {
}
func TestLifetime(t *testing.T) {
session := NewSession()
session.Lifetime = 500 * time.Millisecond
sessionManager := New()
sessionManager.Lifetime = 500 * time.Millisecond
mux := http.NewServeMux()
mux.HandleFunc("/put", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "foo", "bar")
sessionManager.Put(r.Context(), "foo", "bar")
}))
mux.HandleFunc("/get", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := session.Get(r.Context(), "foo")
v := sessionManager.Get(r.Context(), "foo")
if v == nil {
http.Error(w, "foo does not exist in session", 500)
return
@ -101,7 +101,7 @@ func TestLifetime(t *testing.T) {
w.Write([]byte(v.(string)))
}))
ts := newTestServer(t, session.LoadAndSave(mux))
ts := newTestServer(t, sessionManager.LoadAndSave(mux))
defer ts.Close()
ts.execute(t, "/put")
@ -119,16 +119,16 @@ func TestLifetime(t *testing.T) {
}
func TestIdleTimeout(t *testing.T) {
session := NewSession()
session.IdleTimeout = 200 * time.Millisecond
session.Lifetime = time.Second
sessionManager := New()
sessionManager.IdleTimeout = 200 * time.Millisecond
sessionManager.Lifetime = time.Second
mux := http.NewServeMux()
mux.HandleFunc("/put", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "foo", "bar")
sessionManager.Put(r.Context(), "foo", "bar")
}))
mux.HandleFunc("/get", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := session.Get(r.Context(), "foo")
v := sessionManager.Get(r.Context(), "foo")
if v == nil {
http.Error(w, "foo does not exist in session", 500)
return
@ -136,7 +136,7 @@ func TestIdleTimeout(t *testing.T) {
w.Write([]byte(v.(string)))
}))
ts := newTestServer(t, session.LoadAndSave(mux))
ts := newTestServer(t, sessionManager.LoadAndSave(mux))
defer ts.Close()
ts.execute(t, "/put")
@ -158,21 +158,21 @@ func TestIdleTimeout(t *testing.T) {
}
func TestDestroy(t *testing.T) {
session := NewSession()
sessionManager := New()
mux := http.NewServeMux()
mux.HandleFunc("/put", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session.Put(r.Context(), "foo", "bar")
sessionManager.Put(r.Context(), "foo", "bar")
}))
mux.HandleFunc("/destroy", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := session.Destroy(r.Context())
err := sessionManager.Destroy(r.Context())
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}))
mux.HandleFunc("/get", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := session.Get(r.Context(), "foo")
v := sessionManager.Get(r.Context(), "foo")
if v == nil {
http.Error(w, "foo does not exist in session", 500)
return
@ -180,15 +180,15 @@ func TestDestroy(t *testing.T) {
w.Write([]byte(v.(string)))
}))
ts := newTestServer(t, session.LoadAndSave(mux))
ts := newTestServer(t, sessionManager.LoadAndSave(mux))
defer ts.Close()
ts.execute(t, "/put")
header, _ := ts.execute(t, "/destroy")
cookie := header.Get("Set-Cookie")
if strings.HasPrefix(cookie, fmt.Sprintf("%s=;", session.Cookie.Name)) == false {
t.Fatalf("got %q: expected prefix %q", cookie, fmt.Sprintf("%s=;", session.Cookie.Name))
if strings.HasPrefix(cookie, fmt.Sprintf("%s=;", sessionManager.Cookie.Name)) == false {
t.Fatalf("got %q: expected prefix %q", cookie, fmt.Sprintf("%s=;", sessionManager.Cookie.Name))
}
if strings.Contains(cookie, "Expires=Thu, 01 Jan 1970 00:00:01 GMT") == false {
t.Fatalf("got %q: expected to contain %q", cookie, "Expires=Thu, 01 Jan 1970 00:00:01 GMT")