session

package
v1.16.1 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SameSiteLax    = http.SameSiteLaxMode
	SameSiteStrict = http.SameSiteStrictMode
	SameSiteNone   = http.SameSiteNoneMode
)

SameSite values.

Variables

View Source
var ErrExpired = errors.New("session: session expired or revoked")

ErrExpired means an update lost a race with revocation or expiry.

Functions

func KeyFromString

func KeyFromString(s string) []byte

KeyFromString derives a 32-byte key from a string (e.g. APP_KEY) using HKDF-SHA256. Provide a high-entropy APP_KEY (32 random bytes); this is not a password-stretching KDF.

func Middleware

func Middleware(cfg Config) router.Middleware

Middleware returns middleware that loads the session from the store and sets it on the request context. If no session cookie exists, a new session is created on first write.

Types

type Config

type Config struct {
	Store       Store
	CookieName  string
	MaxAge      time.Duration
	SaveTimeout time.Duration // zero defaults to five seconds
	HttpOnly    bool
	Secure      bool
	SameSite    http.SameSite
}

Config holds session middleware options.

Cookie security attributes are secure-by-default: the session cookie is always written with HttpOnly, and with SameSite=Lax unless overridden. The Secure flag is set automatically whenever the request is served over HTTPS (TLS or X-Forwarded-Proto: https); set Secure=true to force it on even behind a proxy that does not forward the scheme.

type CookieStoreImpl

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

func NewCookieStore

func NewCookieStore(key []byte) *CookieStoreImpl

NewCookieStore creates encrypted sessions with a process-local validity registry. Sessions are invalidated on restart. For multiple instances use NewCookieStoreWithRegistry with a shared Redis or database Store.

func NewCookieStoreWithRegistry added in v1.12.0

func NewCookieStoreWithRegistry(key []byte, registry Store) *CookieStoreImpl

NewCookieStoreWithRegistry stores only cookie fingerprints server-side, enabling expiry, replacement and logout revocation across instances. registry must be a server-side Store, not another cookie store.

func (*CookieStoreImpl) Destroy

func (s *CookieStoreImpl) Destroy(ctx context.Context, id string) error

func (*CookieStoreImpl) Get

func (s *CookieStoreImpl) Get(ctx context.Context, id string) (map[string]any, error)

func (*CookieStoreImpl) Rotate added in v1.15.2

func (s *CookieStoreImpl) Rotate(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

func (*CookieStoreImpl) Set

func (s *CookieStoreImpl) Set(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

func (*CookieStoreImpl) Update added in v1.15.2

func (s *CookieStoreImpl) Update(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

Update retains one revocation record across cookie replacements. Logout removes that record, whether it races before or after a replacement save.

type DatabaseStore

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

DatabaseStore stores sessions in a database table. Create the table with: CREATE TABLE sessions (id VARCHAR(64) PRIMARY KEY, payload TEXT, expires_at DATETIME);

func NewDatabaseStore

func NewDatabaseStore(db *lucid.DB, table string) *DatabaseStore

NewDatabaseStore creates a database-backed session store.

func (*DatabaseStore) Destroy

func (s *DatabaseStore) Destroy(ctx context.Context, id string) error

func (*DatabaseStore) EnsureTable

func (s *DatabaseStore) EnsureTable() error

EnsureTable creates the sessions table if it doesn't exist.

func (*DatabaseStore) Get

func (s *DatabaseStore) Get(ctx context.Context, id string) (map[string]any, error)

func (*DatabaseStore) Replace added in v1.15.2

func (s *DatabaseStore) Replace(ctx context.Context, oldID, newID string, data map[string]any, maxAge time.Duration) error

Replace performs one conditional UPDATE, never an upsert after revocation.

func (*DatabaseStore) Rotate added in v1.15.2

func (s *DatabaseStore) Rotate(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

func (*DatabaseStore) Set

func (s *DatabaseStore) Set(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

func (*DatabaseStore) Update added in v1.15.2

func (s *DatabaseStore) Update(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

type MemoryStore

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

MemoryStore stores JSON session snapshots in memory. Sessions are lost on restart. Use for development or single-instance apps. No background goroutine is started: expired records are pruned on reads and periodically on writes.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

func (*MemoryStore) Destroy

func (s *MemoryStore) Destroy(ctx context.Context, id string) error

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, id string) (map[string]any, error)

func (*MemoryStore) Replace added in v1.15.2

func (s *MemoryStore) Replace(ctx context.Context, oldID, newID string, data map[string]any, maxAge time.Duration) error

func (*MemoryStore) Rotate added in v1.15.2

func (s *MemoryStore) Rotate(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

func (*MemoryStore) Set

func (s *MemoryStore) Set(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

func (*MemoryStore) Update added in v1.15.2

func (s *MemoryStore) Update(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

type RedisStore

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

RedisStore stores sessions in Redis. Suitable for multi-instance deployments. Values are JSON-encoded maps with a TTL based on maxAge.

func NewRedisStore

func NewRedisStore(client *redis.Client) *RedisStore

NewRedisStore creates a Redis-backed session store with the default prefix.

func NewRedisStoreWithPrefix

func NewRedisStoreWithPrefix(client *redis.Client, prefix string) *RedisStore

NewRedisStoreWithPrefix creates a Redis-backed session store with a custom key prefix.

func (*RedisStore) Destroy

func (s *RedisStore) Destroy(ctx context.Context, id string) error

Destroy removes the session.

func (*RedisStore) Get

func (s *RedisStore) Get(ctx context.Context, id string) (map[string]any, error)

Get retrieves session data by ID. Returns nil map if not found or on error.

func (*RedisStore) Replace added in v1.15.2

func (s *RedisStore) Replace(ctx context.Context, oldID, newID string, data map[string]any, maxAge time.Duration) error

func (*RedisStore) Rotate added in v1.15.2

func (s *RedisStore) Rotate(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

func (*RedisStore) Set

func (s *RedisStore) Set(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

Set stores session data with the given maxAge. If id is empty, a new ID is generated.

func (*RedisStore) Update added in v1.15.2

func (s *RedisStore) Update(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)

Update only changes a still-live session; it cannot resurrect a revoked ID.

type Replacer added in v1.15.2

type Replacer interface {
	Replace(ctx context.Context, oldID, newID string, data map[string]any, maxAge time.Duration) error
}

Replacer atomically replaces a live server-side record, optionally changing its ID. Used by encrypted cookie registries to consume the old fingerprint and publish its replacement in one operation. Return ErrExpired if absent.

type Rotator added in v1.15.2

type Rotator interface {
	Rotate(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)
}

Rotator atomically changes a live session's ID, as required by Regenerate.

type Session

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

Session provides access to session data.

func FromContext

func FromContext(ctx context.Context) *Session

FromContext returns the session data from the request context. Returns nil if session middleware was not used.

func (*Session) Delete

func (s *Session) Delete(key string)

Delete removes a key from the session.

func (*Session) Get

func (s *Session) Get(key string) any

Get returns a value from the session.

func (*Session) GetFlash

func (s *Session) GetFlash(key string) any

GetFlash retrieves a value from the session and deletes it immediately.

func (*Session) Invalidate added in v1.12.0

func (s *Session) Invalidate(ctx context.Context) error

Invalidate revokes the current session before clearing local data. A storage failure is returned so logout cannot falsely report success.

func (*Session) Regenerate

func (s *Session) Regenerate()

Regenerate regenerates the session ID (for security after login).

func (*Session) Set

func (s *Session) Set(key string, val any)

Set stores a value in the session.

func (*Session) SetFlash

func (s *Session) SetFlash(key string, val any)

SetFlash stores a value in the session that will be deleted after the next GetFlash.

type SessionRecord

type SessionRecord struct {
	ID        string    `gorm:"primaryKey;size:64"`
	Payload   string    `gorm:"type:text"`
	ExpiresAt time.Time `gorm:"index"`
}

SessionRecord is the DB model for sessions.

type Store

type Store interface {
	// Get retrieves session data by ID. Returns nil map if not found.
	Get(ctx context.Context, id string) (map[string]any, error)
	// Set stores session data. id may be empty for new sessions; returns the session ID.
	Set(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)
	// Destroy removes the session.
	Destroy(ctx context.Context, id string) error
}

Store persists session data. Implementations: MemoryStore, CookieStore, DatabaseStore, RedisStore.

type Updater added in v1.15.2

type Updater interface {
	Update(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)
}

Updater atomically saves an existing live session. It must never recreate a missing or expired ID. Middleware requires this capability for existing IDs.

Jump to

Keyboard shortcuts

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