possessions

package module
v0.0.0-...-cd6fb4d Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2021 License: BSD-3-Clause Imports: 14 Imported by: 0

README

possessions

License GoDoc Go Report Card

Available Session Storers

  • Disk
  • Memory
  • Redis
  • Cookie

Overseer interface

The job of an Overseer is to interface with your storers and manage your session cookies. If you want to work with the session values you probably want to use the higher level API functions listed above, but if you want to work with the session directly you can use these overseer methods.

Storer interface

In the case of session management, "keys" here are synonymous with session IDs. This is as lower level API and generally not used too much, because the above higher-level API functions call these functions. This can be used if you need to deal with the storer directly for whatever reason.

Available Overseers

// StorageOverseer is used for all server-side sessions (disk, memory, redis, etc).
NewStorageOverseer(opts CookieOptions, storer Storer) *StorageOverseer

//CookieOverseer is used for client-side only cookie sessions.
NewCookieOverseer(opts CookieOptions, secretKey [32]byte) *CookieOverseer

How does each Storer work?

Disk

Disk sessions store the session as a text file on disk. By default they store in the systems temp directory under a folder that is randomly generated when you generate your app using abcweb app generator command. The file names are the UUIDs of the session. Each time the file is accessed (using Get, Set, manually on disk, or by using the ResetMiddleware) it will reset the access time of the file, which will push back the expiration defined by maxAge. For example, if your maxAge is set to 1 week, and your cleanInterval is set to 2 hours, then every 2 hours the cleaner will find all disk sessions files that have not been accessed for over 1 week and delete them. If the user refreshes a website and you're using the ResetMiddleware then that 1 week timer will be reset. If your maxAge and cleanInterval is set to 0 then these disk session files will permanently persist, however the browser will still expire sessions depending on your cookieOptions maxAge configuration. In a typical (default) setup, cookieOptions will be set to maxAge 0 (expire on browser close), your DiskStorer maxAge will be set to 2 days, and your DiskStorer cleanInterval will be set to 1 hour.

Memory

Memory sessions are stored in memory in a mutex protected map[string]memorySession. The key to the map is the session ID and the memorySession stores the value and expiry of the session. The memory storer also has methods to start and stop a cleaner go routine that will delete expired sessions on an interval that is defined when creating the memory session storer (cleanInterval).

Redis

Redis sessions are stored in a Redis database. Different databases can be used by specifying a different database ID on creation of the storer. Redis handles session expiration automatically.

The cookie storer is intermingled with the CookieOverseer, so to use it you must use the CookieOverseer instead of the StorageOverseer. Cookie sessions are stored in encrypted form (AES-GCM encrypted and base64 encoded) in the clients browser.

Middlewares

TODO: Document RefreshMiddleware

Error types

If an API operation fails, and you would like to check if it failed due to no session existing (errNoSession type), or the key used in a map-key operation not existing (errNoMapKey type), you can check the error types using the following functions against the errors returned:

// errNoSession is a possible return value of Get and ResetExpiry
IsNoSessionError(err error) bool

// errNoMapKey is a possible return value of possessions.Get and possessions.GetFlash
// It indicates that the key-value map stored under a session did not have the 
// requested key
IsNoMapKeyError(err error) bool

Examples

TODO: Add examples

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFlash

func AddFlash(w http.ResponseWriter, key string, value string)

AddFlash adds a flash message to the session. Typically read and removed on the next request.

func AddFlashObj

func AddFlashObj(w http.ResponseWriter, key string, obj interface{}) error

AddFlashObj adds a flash message to the session using an object that's marshalled into JSON

func Del

func Del(w http.ResponseWriter, key string)

Del a session key

func DelAll

func DelAll(w http.ResponseWriter, whitelist []string)

DelAll delete all keys except for a whitelist

func Get

func Get(ctx context.Context, key string) (string, bool)

Get a session string value

func GetFlash

func GetFlash(w http.ResponseWriter, ctx context.Context, key string) (string, bool)

GetFlash reads a flash message from the request and deletes it using the responsewriter.

func GetFlashObj

func GetFlashObj(w http.ResponseWriter, ctx context.Context, key string, obj interface{}) error

GetFlashObj reads a json-encoded flash message from the session and unmarshals it into obj. Use IsNoMapKeyError to determine if the value was found or not.

func GetObj

func GetObj(ctx context.Context, key string, obj interface{}) error

GetObj a session json encoded string and decode it into obj. Use the IsNoMapKeyError to determine if the value was found or not.

func IsNoMapKeyError

func IsNoMapKeyError(err error) bool

IsNoMapKeyError checks an error to see if it means that there was no session map key

func IsNoSessionError

func IsNoSessionError(err error) bool

IsNoSessionError checks an error to see if it means that there was no session

func Refresh

func Refresh(w http.ResponseWriter)

Refresh a session's ttl

func Set

func Set(w http.ResponseWriter, key, value string)

Set a session-value string

func SetObj

func SetObj(w http.ResponseWriter, key string, obj interface{}) error

SetObj marshals the value to a json string and sets it in the session

Types

type CTXKeyPossessions

type CTXKeyPossessions struct{}

CTXKeyPossessions key for caching sessions

type CookieOptions

type CookieOptions struct {
	// Domain is the domain name the cookie is for
	Domain string
	// Path is the URI path the cookie is for
	Path string
	// Name for the session cookie, defaults to "id"
	Name string
	// MaxAge sets the max-age and the expires fields of a cookie
	// A value of 0 means the browser will expire the session on browser close
	MaxAge time.Duration
	// Secure ensures the cookie is only given on https connections
	Secure bool
	// HTTPOnly means the browser will never allow JS to touch this cookie
	HTTPOnly bool
	// SameSite allows you to declare if your cookie should be restricted to a first-party or same-site context
	SameSite http.SameSite
}

CookieOptions for the session cookies themselves. See https://tools.ietf.org/html/rfc6265 for details.

func NewCookieOptions

func NewCookieOptions() CookieOptions

NewCookieOptions gives healthy defaults for session cookies

type DiskStorer

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

DiskStorer is a session storer implementation for saving sessions to disk.

func NewDefaultDiskStorer

func NewDefaultDiskStorer(tmpSubFolder string) (*DiskStorer, error)

NewDefaultDiskStorer returns a DiskStorer object with default values. The default values are: FolderPath: system tmp dir + random folder maxAge: 2 days (clear session stored on server after 2 days) cleanInterval: 1 hour (delete sessions older than maxAge every 1 hour)

func NewDiskStorer

func NewDiskStorer(folderPath string, maxAge, cleanInterval time.Duration) (*DiskStorer, error)

NewDiskStorer initializes and returns a new DiskStorer object. It takes the maxAge of how long each session should live on disk, and a cleanInterval duration which defines how often the clean task should check for maxAge expired sessions to be removed from disk. Persistent storage can be attained by setting maxAge and cleanInterval to zero.

func (*DiskStorer) All

func (d *DiskStorer) All(ctx context.Context) ([]string, error)

All keys in the disk store

func (*DiskStorer) Clean

func (d *DiskStorer) Clean()

Clean checks all session files on disk to see if they are older than maxAge by checking their access time. If it finds an expired session file it will remove it from disk.

func (*DiskStorer) Del

func (d *DiskStorer) Del(ctx context.Context, key string) error

Del the session pointed to by the session id key and remove it.

func (*DiskStorer) Get

func (d *DiskStorer) Get(ctx context.Context, key string) (value string, err error)

Get returns the value string saved in the session pointed to by the session id key.

func (*DiskStorer) ResetExpiry

func (d *DiskStorer) ResetExpiry(ctx context.Context, key string) error

ResetExpiry resets the expiry of the key

func (*DiskStorer) Set

func (d *DiskStorer) Set(ctx context.Context, key, value string) error

Set saves the value string to the session pointed to by the session id key.

func (*DiskStorer) StartCleaner

func (d *DiskStorer) StartCleaner()

StartCleaner starts the disk session cleaner go routine. This go routine will delete expired disk sessions on the cleanInterval interval.

func (*DiskStorer) StopCleaner

func (d *DiskStorer) StopCleaner()

StopCleaner stops the cleaner go routine

type Event

type Event struct {
	Kind EventKind
	Key  string
	Val  string
	Keys []string
}

Event represents an operation on a session

type EventKind

type EventKind int

EventKind of session mutation

const (
	// EventSet sets a key-value pair
	EventSet EventKind = iota
	// EventDel removes a key
	EventDel
	// EventDelAll means you should delete EVERY key-value pair from
	// the client state - though a whitelist of keys that should not be deleted
	// will be set in Keys
	EventDelAll
	// EventRefresh should refresh the TTL if any on the session
	EventRefresh
	// Deletes the client state
	EventDelClientState
)

type MemoryStorer

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

MemoryStorer is a session storer implementation for saving sessions to memory.

func NewDefaultMemoryStorer

func NewDefaultMemoryStorer() (*MemoryStorer, error)

NewDefaultMemoryStorer returns a MemoryStorer object with default values. The default values are: maxAge: 2 days (clear session stored on server after 2 days) cleanInterval: 1 hour (delete sessions older than maxAge every hour)

func NewMemoryStorer

func NewMemoryStorer(maxAge, cleanInterval time.Duration) (*MemoryStorer, error)

NewMemoryStorer initializes and returns a new MemoryStorer object. It takes the maxAge of how long each session should live in memory, and a cleanInterval duration which defines how often the clean task should check for maxAge sessions to be removed from memory. Persistent storage can be attained by setting maxAge and cleanInterval to zero, however the memory will be wiped when the server is restarted.

func (*MemoryStorer) All

func (m *MemoryStorer) All(ctx context.Context) ([]string, error)

All keys in the memory store

func (*MemoryStorer) Clean

func (m *MemoryStorer) Clean()

Clean checks all sessions in memory to see if they are older than maxAge by checking their expiry. If it finds an expired session it will remove it from memory.

func (*MemoryStorer) Del

func (m *MemoryStorer) Del(ctx context.Context, key string) error

Del the session pointed to by the session id key and remove it.

func (*MemoryStorer) Get

func (m *MemoryStorer) Get(ctx context.Context, key string) (value string, err error)

Get returns the value string saved in the session pointed to by the session id key.

func (*MemoryStorer) ResetExpiry

func (m *MemoryStorer) ResetExpiry(ctx context.Context, key string) error

ResetExpiry resets the expiry of the key

func (*MemoryStorer) Set

func (m *MemoryStorer) Set(ctx context.Context, key, value string) error

Set saves the value string to the session pointed to by the session id key.

func (*MemoryStorer) StartCleaner

func (m *MemoryStorer) StartCleaner()

StartCleaner starts the memory session cleaner go routine. This go routine will delete expired sessions from the memory map on the cleanInterval interval.

func (*MemoryStorer) StopCleaner

func (m *MemoryStorer) StopCleaner()

StopCleaner stops the cleaner go routine

type OverseeingMiddleware

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

OverseeingMiddleware enables the use of sessions in this package by allowing read and writes of client state during the request.

func NewOverseeingMiddleware

func NewOverseeingMiddleware(overseer Overseer) OverseeingMiddleware

NewOverseeingMiddleware constructs a middleware

func (OverseeingMiddleware) Wrap

Wrap a handler

type Overseer

type Overseer interface {
	// ReadState should return a map like structure allowing it to look up
	// any values in the current session, or any cookie in the request
	ReadState(*http.Request) (Session, error)
	// WriteState can sometimes be called with a nil ClientState in the event
	// that no ClientState was read in from LoadClientState
	WriteState(context.Context, http.ResponseWriter, Session, []Event) error
}

Overseer of session cookies

type RedisStorer

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

RedisStorer is a session storer implementation for saving sessions to a Redis database.

func NewDefaultRedisStorer

func NewDefaultRedisStorer(addr, password string, db int) (*RedisStorer, error)

NewDefaultRedisStorer takes a bind address of the Redis server host:port and returns a RedisStorer object with default values. The default values are: Addr: localhost:6379 Password: no password DB: First database (0) to be selected after connecting to Redis maxAge: 2 days (clear session stored in Redis after 2 days)

func NewRedisStorer

func NewRedisStorer(opts redis.Options, maxAge time.Duration) (*RedisStorer, error)

NewRedisStorer initializes and returns a new RedisStorer object. It takes a bind address of the Redis server host:port and the maxAge of how long each session should live in the Redis server. Persistent storage can be attained by setting maxAge to zero.

func NewRedisStorerClient

func NewRedisStorerClient(client *redis.Client, maxAge time.Duration) (*RedisStorer, error)

NewRedisStorerClient behaves the same as NewRedisStorer but does not create a new connection pool.

func (*RedisStorer) All

func (r *RedisStorer) All(ctx context.Context) ([]string, error)

All keys in the redis store

func (*RedisStorer) Del

func (r *RedisStorer) Del(ctx context.Context, key string) error

Del the session pointed to by the session id key and remove it.

func (*RedisStorer) Get

func (r *RedisStorer) Get(ctx context.Context, key string) (value string, err error)

Get returns the value string saved in the session pointed to by the session id key.

func (*RedisStorer) ResetExpiry

func (r *RedisStorer) ResetExpiry(ctx context.Context, key string) error

ResetExpiry resets the expiry of the key

func (*RedisStorer) Set

func (r *RedisStorer) Set(ctx context.Context, key, value string) error

Set saves the value string to the session pointed to by the session id key.

type RefreshMiddleware

type RefreshMiddleware struct{}

RefreshMiddleware refreshes sessions on each request

func NewRefreshMiddleware

func NewRefreshMiddleware() RefreshMiddleware

NewRefreshMiddleware creates a refresh middleware

func (RefreshMiddleware) Wrap

Wrap wraps a handler with refreshing middleware

type Session

type Session interface {
	Get(key string) (value string, hasKey bool)
}

Session gets strings

type StorageOverseer

type StorageOverseer struct {
	Storer Storer
	// contains filtered or unexported fields
}

StorageOverseer holds cookie related variables and a session storer

func NewStorageOverseer

func NewStorageOverseer(opts CookieOptions, storer Storer) *StorageOverseer

NewStorageOverseer returns a new storage overseer

func (StorageOverseer) ReadState

func (s StorageOverseer) ReadState(r *http.Request) (Session, error)

ReadState from the request

func (StorageOverseer) WriteState

func (s StorageOverseer) WriteState(ctx context.Context, w http.ResponseWriter, sess Session, evs []Event) error

WriteState to the response

type Storer

type Storer interface {
	// All returns all keys in the store
	All(ctx context.Context) (keys []string, err error)
	Get(ctx context.Context, key string) (value string, err error)
	Set(ctx context.Context, key, value string) error
	Del(ctx context.Context, key string) error
	ResetExpiry(ctx context.Context, key string) error
}

Storer provides methods to retrieve, add and delete sessions.

type UnderlyingResponseWriter

type UnderlyingResponseWriter interface {
	UnderlyingResponseWriter() http.ResponseWriter
}

UnderlyingResponseWriter allows wrapping responsewriters to be able to hand the possessions.responseWriter back to possessions for session management while still being able to use their own custom one.

Jump to

Keyboard shortcuts

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