Documentation
¶
Overview ¶
Package sessions provides typed HTTP sessions backed by a cookie, Redis or a SQL database.
It has no single Handler entry point: build the settings with NewOptions, pass that Options value to a database constructor (NewCookieDatabase, NewRedisDatabase, NewPostgresDatabase) and register Handler[T](db, cookieName) or Single(db, cookieName). A session is read back with Get[T] or Load[T], because the type of the session data is the caller's, not the package's.
Index ¶
- Constants
- Variables
- func Handler[T any](database Database[T], cookieName string) context.Handler
- func ReadOnlyHandler[T any](database Database[T], cookieName string) context.Handler
- type Database
- type Options
- type PostgresConn
- type RedisClient
- type SQLDatabase
- type Session
- func (s *Session[T]) Commit(ctx *context.Context) error
- func (s *Session[T]) Cookie() (*http.Cookie, error)
- func (s *Session[T]) Delete(ctx *context.Context) error
- func (s *Session[T]) Flashes(deleteFn func(key string, message any) bool) map[string]any
- func (s *Session[T]) GetExtra[V any]() (V, bool)
- func (s *Session[T]) GetFlash[V any](key string) (V, bool)
- func (s *Session[T]) Name() string
- func (s *Session[T]) RegenerateID(ctx *context.Context) error
- func (s *Session[T]) Set(data T)
- func (s *Session[T]) SetExtra(extra any)
- func (s *Session[T]) SetFlash(key string, message any)
- type SessionData
- type SingleDatabase
Constants ¶
const DefaultTableName = "iris_sessions"
DefaultTableName is the default name of the sessions table in the (Postgre)SQL database.
Variables ¶
var ErrInvalidSessionID = errors.New("sessions: invalid session id")
ErrInvalidSessionID is returned when a client-supplied session id does not have the shape this package generates (a UUID).
var FlashDelete = func(string, any) bool { return true }
FlashDelete is a function that always returns true, indicating that the flash message should be deleted.
Functions ¶
func Handler ¶
Handler returns a new session handler. It retrieves the session from the database based on the cookie name. It commits the session after the request is completed if the Commit function is not already called. The session is stored in the context and can be retrieved using the Get function.
Note: Use this when you want to manage a single session per request, otherwise use the session database's methods instead and don't register this Handler middleware at all.
SECURITY: this handler does NOT rotate the session id on its own.
Call `Session.RegenerateID` immediately after a privilege change - a successful login above all - or an attacker who plants a session id in the victim's browser keeps access to the authenticated session afterwards (session fixation).
func login(ctx iris.Context) {
// ...verify the credentials first...
sess := sessions.Get[MyData](ctx)
if err := sess.RegenerateID(ctx); err != nil { ... }
sess.Data.UserID = user.ID
}
The database re-issues a fresh id when a cookie names a session that has no server-side record, but that only defeats a planted id that was never used: an attacker who first creates a real session and then plants THAT id is not covered.
func ReadOnlyHandler ¶
ReadOnlyHandler returns a new session handler with read-only access. Useful for performance when you create and update the session from a single spot (using the session database directly) and you just want to read the session data from multiple routes and handlers.
Types ¶
type Database ¶
type Database[T any] interface { // Get should return a cached session based on the cookie name. // It retrieves the session associated with the given cookie name from the context. Get(ctx *context.Context, cookieName string) (*Session[T], error) // Load should return a cached or a new session based on the cookie name and value. // If the cookie value is empty, it means that this is a new session and the database should create a new record for it. // Otherwise, it should return the session based on the cookie value. Load(ctx *context.Context, cookieName, cookieValue string) (*Session[T], error) // Commit should persist the session to the database. // It saves the session data to the database. // If the session's Option's MaxAge is set to < 0 // then the database should remove its relative session record. Commit(ctx *context.Context, session *Session[T]) error }
Database is an interface that defines methods for session management. It provides methods to get, load, and commit sessions.
Example usage:
sessionDB := sessions.NewCookieDatabase[UserSession](sessionOptions)
[...]
func handler(ctx iris.Context) {
session, err := sessionDB.Get(ctx, "my_session")
if err != nil {
// handle error
}
// use the session
session.Data = UserSession{ // or session.Set(UserSession{...})
ID: "1",
Username: "kataras",
}
if err := session.Commit(ctx); err != nil {
// handle error
}
}
If you want to use the same cookie name for all sessions (most common usage), you can use the `Single` function. This function simplifies session retrieval by not requiring you to provide a cookie name each time you want to retrieve the session:
Example usage:
sessionDB := sessions.Single(
sessions.NewCookieDatabase[UserSession](sessionOptions),
"my_session",
)
[...]
func handler(ctx iris.Context) {
session, err := sessionDB.Get(ctx)
if err != nil {
// handle error
}
// use the session
}
func NewCookieDatabase ¶
NewCookieDatabase creates and returns a new cookieDatabase instance with the provided options. It registers the generic type T with the gob package for encoding and decoding session data. The cookie-based session database requires a key pair in the session options because it stores the actual session data inside the cookie. The key pair is used to securely encode and decode the session data to ensure data integrity and confidentiality.
Usage:
sessionOptions := sessions.NewOptions(hashKey, blockKey) sessionDB := sessions.NewCookieDatabase[UserSession](sessionOptions)
NewOptions forwards the key pairs to securecookie.CodecsFromPairs, which reads each pair as a hash key followed by an optional block key.
func NewRedisDatabase ¶
NewRedisDatabase returns a new redis-backed session Database for the given client. It panics if client is nil.
The client is built by the caller, so either a single node or a cluster works:
client := redis.NewClient(redis.Options{...})
// OR
client := redis.NewClusterClient(redis.ClusterOptions{...})
type Options ¶
type Options struct {
// Path specifies the cookie path. It is optional.
// NewOptions sets it to "/". An empty path writes no Path attribute, so
// the browser uses its own default: the directory of the request's path.
Path string `json:"path" yaml:"Path"`
// Domain specifies the cookie domain. It is optional.
// If not set, the default domain is the host of the current document URL.
Domain string `json:"domain" yaml:"Domain"`
// MaxAge defines the maximum age of the cookie, as a time.Duration
// (the cookie's Max-Age attribute is written in whole seconds).
// MaxAge=0 means no 'Max-Age' attribute is specified and the
// session is removed after the request life-cycle ends.
// MaxAge<0 means delete the cookie immediately, equivalently 'Max-Age: 0'.
//
// NewOptions sets it to 24 hours.
MaxAge time.Duration `json:"max_age" yaml:"MaxAge"`
// SameSite controls the SameSite attribute of the cookie.
// It can be set to Lax, Strict, or None to control the cookie's
// cross-site request behavior.
//
// NewOptions sets SameSite to Lax (changed from None in v14) to
// mitigate CSRF while still allowing top-level navigations.
SameSite http.SameSite `json:"same_site" yaml:"SameSite"`
// Partitioned indicates whether the cookie is partitioned.
// Partitioned cookies are only sent in a third-party context if the
// request is initiated by the same site that set the cookie.
//
// The default value is false.
Partitioned bool `json:"partitioned" yaml:"Partitioned"`
// Secure indicates whether the cookie should only be transmitted
// over secure protocols such as HTTPS.
//
// NewOptions sets it to true.
Secure bool `json:"secure" yaml:"Secure"`
// DataCodecs are the securecookie codecs used to encode and decode
// the cookie value and the stored session data. NewOptions builds them
// from its key pairs. DataCodecs are shared between all sessions and
// should not be modified per-session. Instead, use each database's
// codecs.
DataCodecs []securecookie.Codec `json:"-" yaml:"-"`
}
Options represents the configuration settings for a session. These settings determine how the session cookies are managed and stored.
The defaults described on the fields (a MaxAge of 24 hours, SameSite Lax, Secure true, Path "/") are set by NewOptions. A zero Options{} has none of them: MaxAge 0, no SameSite attribute, Secure false, no DataCodecs. Start from NewOptions and change the fields you need.
func NewOptions ¶
NewOptions creates and returns a new Options value with default values. The keyPairs parameter is used to initialize the securecookie.Codec for encoding and decoding session data.
func (Options) Apply ¶
Apply applies any changes to the Options before using it in databases. It updates the MaxAge for each securecookie.Codec and returns the Options back.
Note that Options is a value type: copying it copies every field except the DataCodecs slice, whose codecs are shared by design (they hold the keys).
func (Options) Cookie ¶
Cookie converts the Options instance to an http.Cookie with a value. It sets the cookie's attributes based on the Options fields.
type PostgresConn ¶
type PostgresConn interface {
// Exec executes a query that doesn't return rows.
Exec(ctx stdContext.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
// QueryRow executes a query that is expected to return at most one row.
QueryRow(ctx stdContext.Context, sql string, arguments ...any) pgx.Row
}
PostgresConn is an interface that defines the methods required to interact with a PostgreSQL database.
type RedisClient ¶
RedisClient is the interface which both go-redis's Client and Cluster Client implements.
type SQLDatabase ¶
type SQLDatabase[T any] interface { Database[T] // ShiftExpiration sets whether the session expiration should be shifted to the current time plus the MaxAge on Commit. ShiftExpiration(b bool) // StartCleanupScheduler starts a scheduler that periodically cleans up expired sessions from the database. StartCleanupScheduler(ctx stdContext.Context, interval time.Duration) <-chan error }
SQLDatabase is an interface that extends the Database interface with methods specific to SQL databases.
func NewPostgresDatabase ¶
NewPostgresDatabase creates and returns a new PostgreSQL database instance for session management with the provided options. It registers the generic type T with the gob package for encoding and decoding session data.
It panics if - the table name is empty or - the PostgreSQL client is nil or - it fails to create the sessions table in the PostgreSQL database.
Usage:
db := sessions.NewPostgresDatabase(sessions.DefaultTableName, pgDB, sessions.NewOptions(keyPair...))
type Session ¶
type Session[T any] struct { SessionData[T] // SessionData holds both the actual session-specific data and the flash messages. // ID is set by the database, optionally. ID string Options Options // Options contains the session configuration settings. IsNew bool // IsNew indicates whether the session is newly created. // contains filtered or unexported fields }
Session represents a user session with a generic data type T. It holds the session data, configuration options, and state information. If the ID is set by the database, no data, including flash messages, are stored in the session cookie. In such cases, the session data and flash messages should be handled by the database itself.
Note: You should call Commit before any other writes to the response. Ensure that headers are written before the body to maintain proper session handling.
func Get ¶
Get returns the session from the context. It returns nil if the session is not found or if the stored session's type is not the same as the one provided on the Handler function.
func Load ¶
Load retrieves the session associated with the given cookie name from the context or database. If the session is not found in the context, it attempts to load it from the database. It stores the session and any error in the context for future retrieval.
func NewSession ¶
NewSession creates and returns a new Session instance with the provided options.
Options is a value type, so the session gets its own copy: Expire, Commit and Destroy write to Options.MaxAge and must not reach the database's own copy. The DataCodecs slice is the one part still shared, by design, because it holds the keys.
func (*Session[T]) Commit ¶
Commit saves the session data to the database and sets the session cookie in the context. If there is an error during the commit, it expires the session cookie.
Note that you should call Commit before any other writes to the response.
func (*Session[T]) Cookie ¶
Cookie creates an http.Cookie based on the session's options and encoded value. It returns the cookie and any error encountered during encoding.
func (*Session[T]) Delete ¶
Delete sets the session's MaxAge to -1, indicating that the session should be expired immediately. And calls Commit to delete the associated session cookie and any database's record.
func (*Session[T]) Flashes ¶
Flashes returns all the flash messages and optionally deletes them at the same time. The resulting map contains all the flash messages with their corresponding keys. If the deleteFn is not nil, it is called for each flash message to determine whether it should be deleted from the original map. Note that you should call Commit before any other writes to the response, headers should be written before body.
To get and delete all flash messages, use the following:
flashes := session.Flashes(sessions.FlashDelete)
func (*Session[T]) GetExtra ¶
GetExtra returns the session's extra data as V. The second return value reports whether extra data was set AND is of type V.
It is named GetExtra, not Extra: the promoted SessionData field of that name remains directly readable (session.Extra) where the raw any is wanted.
func (*Session[T]) GetFlash ¶
GetFlash returns the flash message associated with the given key as V. A message of the requested type is removed from the flash messages map; a message of a different type is left in place and (zero, false) is returned, so a mistyped read is never destructive.
Use V = any for the old untyped behavior.
func (*Session[T]) RegenerateID ¶
RegenerateID rotates the session's server-side identifier to defend against session fixation attacks. Call it whenever the session's privilege level changes, most importantly right after a successful sign-in, so that any session identifier an attacker may have planted in the victim's browser can no longer be used to access the now-authenticated session.
It deletes the record stored under the previous ID, assigns a freshly generated ID and persists the session (re-issuing the session cookie under the new ID). Set any authenticated data on the session before calling it; a subsequent Commit is not required, but calling it again is safe.
RegenerateID is a no-op for cookie-based sessions: their data lives in the signed and encrypted cookie itself, so there is no server-side ID to rotate. It is likewise a no-op for sessions that were not loaded from a database.
As with Commit, call RegenerateID before writing to the response body so that the updated Set-Cookie header is sent first.
type SessionData ¶
type SessionData[T any] struct { Data T // Data holds the session-specific data. FlashMessages map[string]any // FlashMessages holds temporary messages that are intended to be displayed only once. Extra any // Extra holds any extra data that the user wants to store. }
SessionData is a wrapper struct that includes both the generic data and flash messages.
type SingleDatabase ¶
SingleDatabase is a database extension that defines a method to get a single session. It provides a method to get a single session based on the provided cookie name, so the caller can get a session without having to provide the cookie name each time.