scs

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2017 License: MIT Imports: 15 Imported by: 0

README

SCS: A HTTP Session Manager

godoc go report card

SCS is a fast and lightweight HTTP session manager for Go. It features:

  • Built-in PostgreSQL, MySQL, Redis, encrypted cookie and in-memory storage engines. Custom storage engines are also supported.
  • Supports OWASP good-practices, including absolute and idle session timeouts and easy regeneration of session tokens.
  • Fast and very memory-efficient performance.
  • Type-safe and sensible API for managing session data. Safe for concurrent use.
  • Automatic saving of session data.

Recent changes: Release v1.0.0 made breaking changes to the package layout and API. If you need the old version please vendor release v0.1.1.

Installation & Usage

Install with go get:

$ go get github.com/alexedwards/scs
Basic use
package main

import (
    "io"
    "net/http"

    "github.com/alexedwards/scs"
)

// Initialize a new encrypted-cookie based session manager and store it in a global
// variable. In a real application, you might inject the session manager as a
// dependency to your handlers instead. The parameter to the NewCookieManager()
// function is a 32 character long random key, which is used to encrypt and
// authenticate the session cookies.
var sessionManager = scs.NewCookieManager("u46IpCV9y5Vlur8YvODJEhgOY8m9JVE4")

func main() {
    // Set up your HTTP handlers in the normal way.
    mux := http.NewServeMux()
    mux.HandleFunc("/put", putHandler)
    mux.HandleFunc("/get", getHandler)

    http.ListenAndServe(":4000", mux)
}

func putHandler(w http.ResponseWriter, r *http.Request) {
    // Load the session data for the current request. Any errors are deferred
    // until you actually use the session data.
    session := sessionManager.Load(r)

    // Use the PutString() method to add a new key and associated string value
    // to the session data. Methods for many other common data types are also
    // provided. The session data is automatically saved.
    err := session.PutString(w, "message", "Hello world!")
    if err != nil {
        http.Error(w, err.Error(), 500)
    }
}

func getHandler(w http.ResponseWriter, r *http.Request) {
    // Load the session data for the current request.
    session := sessionManager.Load(r)

    // Use the GetString() helper to retrieve the string value for the "message"
    // key from the session data. The zero value for a string is returned if the
    // key does not exist.
    message, err := session.GetString("message")
    if err != nil {
        http.Error(w, err.Error(), 500)
    }

    io.WriteString(w, message)
}

Please note: If you are calling session.Load() multiple times in the same request cycle you must wrap your handlers with the manager.Multi() middleware.

SCS provides a wide range of functions for working with session data.

  • Put… and Get… methods for storing and retrieving a variety of common data types and custom objects.
  • Pop… methods for one-time retrieval of common data types (and custom objects) from the session data.
  • Keys returns an alphabetically-sorted slice of all keys in the session data.
  • Exists returns whether a specific key exists in the session data.
  • Remove removes an individual key and value from the session data.
  • Clear removes all data for the current session.
  • RenewToken creates a new session token. This should be used before privilege changes to help avoid session fixation.
  • Destroy deletes the current session and instructs the browser to delete the session cookie.

A full list of available functions can be found in the GoDoc.

Customizing the session manager

The session manager can be configured to customize its behavior. For example:

sessionManager = scs.NewCookieManager("u46IpCV9y5Vlur8YvODJEhgOY8m9JVE4")
sessionManager.Lifetime(time.Hour) // Set the maximum session lifetime to 1 hour.
sessionManager.Persist(true) // Persist the session after a user has closed their browser.
sessionManager.Secure() // Set the Secure flag on the session cookie.

A full list of available settings can be found in the GoDoc.

Using a different session store

The above examples use encrypted cookies to store session data, but SCS also supports a range of server-side stores.

Package
stores/memstore In-memory session store
stores/cookiestore Encrypted-cookie based session store
stores/pgstore PostgreSQL based storage eninge
stores/mysqlstore MySQL based session store
stores/redisstore Redis based session store
stores/boltstore BoltDB based session store
stores/buntstore BuntDB based session store

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CookieName = "session"

Deprecated: Please use the Manager.Name() method to change the name of the session cookie.

View Source
var ErrTypeAssertionFailed = errors.New("type assertion failed")

ErrTypeAssertionFailed is returned by operations on session data where the received value could not be type asserted or converted into the required type.

Functions

This section is empty.

Types

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager is a session manager.

func NewCookieManager

func NewCookieManager(key string) *Manager

func NewManager

func NewManager(store Store) *Manager

NewManager returns a pointer to a new session manager.

func (*Manager) Domain

func (m *Manager) Domain(s string)

Domain sets the 'Domain' attribute on the session cookie. By default it will be set to the domain name that the cookie was issued from.

func (*Manager) HttpOnly

func (m *Manager) HttpOnly(b bool)

HttpOnly sets the 'HttpOnly' attribute on the session cookie. The default value is true.

func (*Manager) IdleTimeout

func (m *Manager) IdleTimeout(t time.Duration)

IdleTimeout sets 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. The inactivity period is reset whenever the session data is changed (but not read).

By default IdleTimeout is not set and there is no inactivity timeout.

func (*Manager) Lifetime

func (m *Manager) Lifetime(t time.Duration)

Lifetime sets the maximum length of time that a session is valid for before it expires. The lifetime is an 'absolute expiry' which is set when the session is first created and does not change.

The default value is 24 hours.

func (*Manager) Load

func (m *Manager) Load(r *http.Request) *Session

Load returns the session data for the current request.

func (*Manager) Multi added in v1.1.0

func (m *Manager) Multi(next http.Handler) http.Handler

func (*Manager) Name added in v1.1.0

func (m *Manager) Name(s string)

Name sets the name of the session cookie. This name should not contain whitespace, commas, semicolons, backslashes, the equals sign or control characters as per RFC6265.

func (*Manager) Path

func (m *Manager) Path(s string)

Path sets the 'Path' attribute on the session cookie. The default value is "/". Passing the empty string "" will result in it being set to the path that the cookie was issued from.

func (*Manager) Persist

func (m *Manager) Persist(b bool)

Persist sets whether the session cookie should be persistent or not (i.e. whether it should be retained after a user closes their browser).

The default value is false, which means that the session cookie will be destroyed when the user closes their browser. If set to true, explicit 'Expires' and 'MaxAge' values will be added to the cookie and it will be retained by the user's browser until the given expiry time is reached.

func (*Manager) Secure

func (m *Manager) Secure(b bool)

Secure sets the 'Secure' attribute on the session cookie. The default value is false. It's recommended that you set this to true and serve all requests over HTTPS in production environments.

func (*Manager) Use added in v1.1.0

func (m *Manager) Use(next http.Handler) http.Handler

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session contains data for the current session.

func (*Session) Clear

func (s *Session) Clear(w http.ResponseWriter) error

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 operation is a no-op.

func (*Session) Destroy

func (s *Session) Destroy(w http.ResponseWriter) error

Destroy deletes the current session. The session token and accompanying data are deleted from the session store, and the client is instructed to delete the session cookie.

Any further operations on the session in the same request cycle will result in a new session being created.

A new empty session will be created for any client that subsequently tries to use the destroyed session token.

func (*Session) Exists

func (s *Session) Exists(key string) (bool, error)

Exists returns true if the given key is present in the session data.

func (*Session) GetBool

func (s *Session) GetBool(key string) (bool, error)

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. An ErrTypeAssertionFailed error is returned if the value could not be type asserted to a bool.

func (*Session) GetBytes

func (s *Session) GetBytes(key string) ([]byte, error)

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. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to []byte.

func (*Session) GetFloat

func (s *Session) GetFloat(key string) (float64, error)

GetFloat returns the float64 value for a given key from the session data. The zero value for an float (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a float64.

func (*Session) GetInt

func (s *Session) GetInt(key string) (int, error)

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. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a int.

func (*Session) GetInt64

func (s *Session) GetInt64(key string) (int64, error)

GetInt64 returns the int64 value for a given key from the session data. The zero value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a int64.

func (*Session) GetObject

func (s *Session) GetObject(key string, dst interface{}) error

GetObject reads the data for a given session key into an arbitrary object (represented by the dst parameter). It should only be used to retrieve custom data types that have been stored using PutObject. The object represented by dst will remain unchanged if the key does not exist.

The dst parameter must be a pointer.

func (*Session) GetString

func (s *Session) GetString(key string) (string, error)

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. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a string.

func (*Session) GetTime

func (s *Session) GetTime(key string) (time.Time, error)

GetTime returns the time.Time value for a given key from the session data. The zero value for a time.Time object is returned if the key does not exist (this can be checked for with the time.IsZero method). An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a time.Time.

func (*Session) Keys

func (s *Session) Keys() ([]string, error)

Keys returns a slice of all key names present in the session data, sorted alphabetically. If the session contains no data then an empty slice will be returned.

func (*Session) PopBool

func (s *Session) PopBool(w http.ResponseWriter, key string) (bool, error)

PopBool removes the bool value for a given key from the session data and returns it. The zero value for a bool (false) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted to a bool.

func (*Session) PopBytes

func (s *Session) PopBytes(w http.ResponseWriter, key string) ([]byte, error)

PopBytes removes the byte slice ([]byte) value for a given key from the session data and returns it. The zero value for a slice (nil) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a []byte.

func (*Session) PopFloat

func (s *Session) PopFloat(w http.ResponseWriter, key string) (float64, error)

PopFloat removes the float64 value for a given key from the session data and returns it. The zero value for an float (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a float64.

func (*Session) PopInt

func (s *Session) PopInt(w http.ResponseWriter, key string) (int, error)

PopInt removes the int value for a given key from the session data and returns it. The zero value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a int.

func (*Session) PopInt64

func (s *Session) PopInt64(w http.ResponseWriter, key string) (int64, error)

PopInt64 remvoes the int64 value for a given key from the session data and returns it. The zero value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a int64.

func (*Session) PopObject

func (s *Session) PopObject(w http.ResponseWriter, key string, dst interface{}) error

PopObject removes the data for a given session key and reads it into a custom object (represented by the dst parameter). It should only be used to retrieve custom data types that have been stored using PutObject. The object represented by dst will remain unchanged if the key does not exist.

The dst parameter must be a pointer.

func (*Session) PopString

func (s *Session) PopString(w http.ResponseWriter, key string) (string, error)

PopString removes the string value for a given key from the session data and returns it. The zero value for a string ("") is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted to a string.

func (*Session) PopTime

func (s *Session) PopTime(w http.ResponseWriter, key string) (time.Time, error)

PopTime removes the time.Time value for a given key from the session data and returns it. The zero value for a time.Time object is returned if the key does not exist (this can be checked for with the time.IsZero method). An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a time.Time.

func (*Session) PutBool

func (s *Session) PutBool(w http.ResponseWriter, key string, val bool) error

PutBool adds a bool value and corresponding key to the session data. Any existing value for the key will be replaced.

func (*Session) PutBytes

func (s *Session) PutBytes(w http.ResponseWriter, key string, val []byte) error

PutBytes adds a byte slice ([]byte) value and corresponding key to the the session data. Any existing value for the key will be replaced.

func (*Session) PutFloat

func (s *Session) PutFloat(w http.ResponseWriter, key string, val float64) error

PutFloat adds an float64 value and corresponding key to the session data. Any existing value for the key will be replaced.

func (*Session) PutInt

func (s *Session) PutInt(w http.ResponseWriter, key string, val int) error

PutInt adds an int value and corresponding key to the session data. Any existing value for the key will be replaced.

func (*Session) PutInt64

func (s *Session) PutInt64(w http.ResponseWriter, key string, val int64) error

PutInt64 adds an int64 value and corresponding key to the session data. Any existing value for the key will be replaced.

func (*Session) PutObject

func (s *Session) PutObject(w http.ResponseWriter, key string, val interface{}) error

PutObject adds an arbitrary object and corresponding key to the the session data. Any existing value for the key will be replaced.

The val parameter must be a pointer to your object.

PutObject is typically used to store custom data types. It encodes the object into a gob and then into a base64-encoded string which is persisted by the session store. This makes PutObject (and the accompanying GetObject and PopObject functions) comparatively expensive operations.

Because gob encoding is used, the fields on custom types must be exported in order to be persisted correctly. Custom data types must also be registered with gob.Register before PutObject is called (see https://golang.org/pkg/encoding/gob/#Register).

func (*Session) PutString

func (s *Session) PutString(w http.ResponseWriter, key string, val string) error

PutString adds a string value and corresponding key to the the session data. Any existing value for the key will be replaced.

func (*Session) PutTime

func (s *Session) PutTime(w http.ResponseWriter, key string, val time.Time) error

PutTime adds an time.Time value and corresponding key to the session data. Any existing value for the key will be replaced.

func (*Session) Remove

func (s *Session) Remove(w http.ResponseWriter, key string) error

Remove deletes the given key and corresponding value from the session data. If the key is not present this operation is a no-op.

func (*Session) RenewToken

func (s *Session) RenewToken(w http.ResponseWriter) error

RenewToken creates a new session token while retaining the current session data. The session lifetime is also reset.

The old session token and accompanying data are deleted from the session store.

To mitigate the risk of session fixation attacks, it's important that you call RenewToken before making any changes to privilege levels (e.g. login and logout operations). See https://www.owasp.org/index.php/Session_fixation for additional information.

func (*Session) Touch added in v1.1.0

func (s *Session) Touch(w http.ResponseWriter) error

type Store

type Store interface {
	// Delete should remove the session token and corresponding data from the
	// session store. If the token does not exist then Delete should be a no-op
	// and return nil (not an error).
	Delete(token string) (err error)

	// Find should return the data for a session token from the session store.
	// If the session token is not found or is expired, the found return value
	// should be false (and the err return value should be nil). Similarly, tampered
	// or malformed tokens should result in a found return value of false and a
	// nil err value. The err return value should be used for system errors only.
	Find(token string) (b []byte, found bool, err error)

	// Save should add the session token and data to the session store, with
	// the given expiry time. If the session token already exists, then the data
	// and expiry time should be overwritten.
	Save(token string, b []byte, expiry time.Time) (err error)
}

Store is the interface for session stores.

Directories

Path Synopsis
stores
boltstore
Package boltstore is a boltdb based session store for the SCS session package.
Package boltstore is a boltdb based session store for the SCS session package.
buntstore
Package buntstore is a buntdb based session store for the SCS session package.
Package buntstore is a buntdb based session store for the SCS session package.
dynamostore
Package dynamostore is a DynamoDB-based session store for the SCS session package.
Package dynamostore is a DynamoDB-based session store for the SCS session package.
memstore
Package memstore is a in-memory session store for the SCS session package.
Package memstore is a in-memory session store for the SCS session package.
mysqlstore
Package mysqlstore is a MySQL-based session store for the SCS session package.
Package mysqlstore is a MySQL-based session store for the SCS session package.
pgstore
Package pgstore is a PostgreSQL-based session store for the SCS session package.
Package pgstore is a PostgreSQL-based session store for the SCS session package.
qlstore
Package qlstore is a ql-based session store for the SCS session package.
Package qlstore is a ql-based session store for the SCS session package.
redisstore
Package redisstore is a Redis-based session store for the SCS session package.
Package redisstore is a Redis-based session store for the SCS session package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL