Categorygithub.com/volatiletech/possessions
modulepackage
0.0.0-20210817080736-cd6fb4d971c7
Repository: https://github.com/volatiletech/possessions.git
Documentation: pkg.go.dev

# 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.

Cookie

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

# Functions

AddFlash adds a flash message to the session.
AddFlashObj adds a flash message to the session using an object that's marshalled into JSON.
Del a session key.
DelAll delete all keys except for a whitelist.
Get a session string value.
GetFlash reads a flash message from the request and deletes it using the responsewriter.
GetFlashObj reads a json-encoded flash message from the session and unmarshals it into obj.
GetObj a session json encoded string and decode it into obj.
IsNoMapKeyError checks an error to see if it means that there was no session map key.
IsNoSessionError checks an error to see if it means that there was no session.
NewCookieOptions gives healthy defaults for session cookies.
NewDefaultDiskStorer returns a DiskStorer object with default values.
NewDefaultMemoryStorer returns a MemoryStorer object with default values.
NewDefaultRedisStorer takes a bind address of the Redis server host:port and returns a RedisStorer object with default values.
NewDiskStorer initializes and returns a new DiskStorer object.
NewMemoryStorer initializes and returns a new MemoryStorer object.
NewOverseeingMiddleware constructs a middleware.
NewRedisStorer initializes and returns a new RedisStorer object.
NewRedisStorerClient behaves the same as NewRedisStorer but does not create a new connection pool.
NewRefreshMiddleware creates a refresh middleware.
NewStorageOverseer returns a new storage overseer.
Refresh a session's ttl.
Set a session-value string.
SetObj marshals the value to a json string and sets it in the session.

# Constants

EventDel removes a key.
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.
Deletes the client state.
EventRefresh should refresh the TTL if any on the session.
EventSet sets a key-value pair.

# Structs

CookieOptions for the session cookies themselves.
CTXKeyPossessions key for caching sessions.
DiskStorer is a session storer implementation for saving sessions to disk.
Event represents an operation on a session.
MemoryStorer is a session storer implementation for saving sessions to memory.
OverseeingMiddleware enables the use of sessions in this package by allowing read and writes of client state during the request.
RedisStorer is a session storer implementation for saving sessions to a Redis database.
RefreshMiddleware refreshes sessions on each request.
StorageOverseer holds cookie related variables and a session storer.

# Interfaces

Overseer of session cookies.
Session gets strings.
Storer provides methods to retrieve, add and delete sessions.
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.

# Type aliases

EventKind of session mutation.