session

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2023 License: BSD-2-Clause Imports: 13 Imported by: 0

README

simple-session

Minimal storage-backed session management for small golang web apps.

Offers:

  • Creation and management of time-bound session objects with arbitrary data payloads.
  • Storage of session data to Redis (or any implementation of SessionStore).
  • Session-bound CSRF tokens, suitable for, e.g., embedding in hidden form fields.
  • Authenticated (HMAC-SHA256) end-user visible identifiers (i.e., SIDs and CSRF tokens).
  • Easily integrated with go-chi/chi.

Does not offer (at least at this time):

  • Session extension.

Documentation

Overview

Package session provides helpers for managing user sessions.

At a high level, Manager manages the creation of time-bounded Session instances, which are in turn stored to a SessionStore. The Session is imbued with an arbitrary Data payload, which can be used to store user session details (e.g., identity).

At Session creation, Manager will set a session token cookie to that refers to the Session ID.

Sessions also contain an assocated CSRF token, which can be used in CSRF protections (e.g., hidden form fields).

Both tokens (session ID and CSRF) are authenticated (currently HMAC-SHA256) using separate keys.

The general principle is that HTTP handlers that must be Session-aware will use the Manage middleware. The latter ensures that a Session always exists, and defaults to a pre-session - i.e., one with nil associated Data. This ensures that CSRF protection is always possible.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateStrictCookie added in v0.2.0

func CreateStrictCookie(name, value string, expires time.Time) *http.Cookie

CreateStrictCookie returns an http.Cookie with strict defaults, with the provided name, value, and expiration. The resulting cookie is marked Secure, HttpOnly, and SameSite Strict, with no Domain or Path attribute. Consider using this as a base for your own implementation of CreateCookie.

Types

type Manager added in v0.5.0

type Manager[D any] struct {
	// Clock can be used to override measurement of time in tests.
	Clock func() time.Time
	// contains filtered or unexported fields
}

Manager manages user sessions (i.e., Session instances).

func NewManager added in v0.5.0

func NewManager[D any](s store.SessionStore[Session[D]], key []byte, opts *Options) (*Manager[D], error)

NewManager returns a new Manager using the provided store for session storage and respecting the provided options. Session IDs and associated CSRF tokens are authenticated (HMAC-SHA256) using keys derived from the provided initial key.

func (*Manager[D]) Clear added in v0.5.0

func (m *Manager[D]) Clear(ctx context.Context, w http.ResponseWriter, sid string) (*Session[D], error)

Clear creates a new pre-session (i.e., a Session with no Data payload) and attempts to delete the prior session from the SessionStore. The former is stored to the SessionStore and its ID set in the SID cookie, and it is also returned. Deletion of the old session is considered non-critical (i.e., unexpected errors are merely logged).

func (*Manager[D]) Create added in v0.5.0

func (m *Manager[D]) Create(ctx context.Context, w http.ResponseWriter, data *D) (*Session[D], error)

Create creates a new Session with the provided Data payload, storing the session to the SessionStore and setting the associated SID cookie.

func (*Manager[D]) Manage added in v0.5.0

func (m *Manager[D]) Manage(next http.Handler) http.Handler

Manage is a chi-compatible middleware that validates the session cookie, looks up the associated session data, and stores it to the request Context (which can be retrieved via Get). If no session cookie is present, a pre-session (i.e., one with nil Data payload) will be created. In other words, Manage ensures a session always exists (with an associated CSRF token).

func (*Manager[D]) VerifySessionCSRFToken added in v0.5.0

func (m *Manager[D]) VerifySessionCSRFToken(token string, s *Session[D]) error

VerifySessionCSRFToken verifies the authenticity of the provided CSRF token and that it matches the expected value for the provided Session.

type Options

type Options struct {
	// TTL is the duration that any given session is valid. Note that there is
	// no facility for session extension at this time.
	// Default if unspecified: 30m
	TTL time.Duration
	// IDLen is the length of random portion of user-facing identifiers (i.e.,
	// SIDs and CSRF tokens). Note that the full identifier will be extended
	// with its HMAC (32 bytes) and base64url enconded.
	// Default if unspecified: 16 bytes
	IDLen int
	// SessionCookieName is the name of the session ID cookie set by Manager.
	// For example, together with a suitable definition of CreateCookie (see
	// below), this can be used to configure a secure cookie name prefix (e.g.,
	// "__Host-").
	// Default if unspecified: "session"
	SessionCookieName string
	// CreateCookie is a user-supplied factory for creating session ID cookies
	// with the provided name, value, and expiration. This is provided as a
	// convenience for granular control of cookie attributes, such as Path.
	// Default if unspecified: CreateStrictCookie
	CreateCookie func(name, value string, expires time.Time) *http.Cookie
	// OnCreate is a user-supplied callback invoked on session creation, with
	// the associated ResponseWriter instance and newly created Session. May be
	// used, e.g., to inject a CSRF Token cookie into the response.
	// Default if unspecified: nil, in which case OnCreate is not invoked.
	OnCreate func(w http.ResponseWriter, session any)
}

Options represents tunable knobs that control the behavior of Manager.

type Session

type Session[D any] struct {
	// ID is a random unique identifier (authenticated).
	ID string `json:"id"`
	// Data is an arbitrary data payload. Type D must meet any requirements of
	// the chosen SessionStore (e.g., must marshal to / from JSON).
	Data *D `json:"data"`
	// Expiration is the time after which this session is no longer valid.
	Expiration time.Time `json:"expiration"`
	// CSRFToken is a random identifier (authenticated) bound to this session,
	// suitable for, e.g., embedding in a hidden form field.
	CSRFToken string `json:"csrf_token"`
}

Session represents a user session.

func Get added in v0.4.0

func Get[D any](ctx context.Context) *Session[D]

Get returns the Session object instance stored in the provided request Context by the Manage middleware.

Directories

Path Synopsis
internal
retry
Package retry implements retries with jittered exponential backoff.
Package retry implements retries with jittered exponential backoff.
token
Package token provides utilities for creation and verification of authenticated token strings.
Package token provides utilities for creation and verification of authenticated token strings.
token/v0
Package v0 implements operations supporting the v0 token version.
Package v0 implements operations supporting the v0 token version.
Package store and its subpackages provide session storage functionality for use by SessionManager.
Package store and its subpackages provide session storage functionality for use by SessionManager.
memory
Package memory provides an in-memory SessionStore.
Package memory provides an in-memory SessionStore.
redis
Package redis provides a Redis-backed SessionStore.
Package redis provides a Redis-backed SessionStore.

Jump to

Keyboard shortcuts

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