sessionstore

package module
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2026 License: AGPL-3.0 Imports: 23 Imported by: 2

README

Session Store Open in Gitpod

Tests Status Go Report Card PkgGoDev

Stores session to a database table.

License

This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). You can find a copy of the license at https://www.gnu.org/licenses/agpl-3.0.en.html

For commercial use, please use my contact page to obtain a commercial license.

🌏 Open in the Cloud

Click any of the buttons below to start a new development environment to demo or contribute to the codebase without having to install anything on your machine:

Open in VS Code Open in Glitch Open in GitHub Codespaces Edit in Codesandbox Open in StackBlitz Open in Repl.it Open in Codeanywhere Open in Gitpod

Installation

go get -u github.com/dracory/sessionstore

Setup

sessionStore = sessionstore.NewStore(sessionstore.NewStoreOptions{
	DB:                 databaseInstance,
	SessionTableName:   "my_session",
	TimeoutSeconds:     3600, // 1 hour
	AutomigrateEnabled: true,
	DebugEnabled:       false,
})

go sessionStore.SessionExpiryGoroutine()

Methods

  • AutoMigrate() error - automigrate (creates) the session table
  • DriverName(db *sql.DB) string - finds the driver name from database
  • EnableDebug(debug bool) - enables / disables the debug option
  • SessionExpiryGoroutine() error - deletes the expired session keys

Usage

sessionKey  := "ABCDEFG"
sessionExpireSeconds = 2*60*60

session := NewSession().
  SetKey(sessionKey).
  SetValue(sessionValue).
  SetUserID(userID).
  SetUserAgent(r.UserAgent()).
  SetIPAddress(r.RemoteAddr).
  SetExpiresAt(carbon.Now(carbon.UTC).AddSeconds(sessionExpireSeconds).ToDateTimeString(carbon.UTC))

// Create new
err := sessionStore.SessionCreate(session)

// Get session value, or default if not found
session, err := sessionStore.SessionFindByKey(sessionKey)

// Update session
session.SetValue(newSessionValue)
session.SetExpiresAt(carbon.Now(carbon.UTC).AddMinutes(60).ToDateTimeString(carbon.UTC))
err := sessionStore.SessionUpdate(session)

// Delete session
err := sessionStore.SessionDeleteByKey(sessionKey)

Changelog

2025.01.05 - Added "SessionExtend" method

2024.12.11 - Removed old API, extended interface

2024.09.08 - Added options (UserID, UserAgent, IPAddress)

2024.01.03 - Added "Extend" method

2023.08.03 - Renamed "SetJSON", "GetJSON" methods to "SetAny", "GetAny"

2023.08.03 - Added "SetMap", "GetMap", "MergeMap" methods

2022.12.06 - Changed store setup to use struct

2022.01.01 - Added "Has" method

2021.12.15 - Added LICENSE

2021.12.15 - Added test badge

2021.12.15 - Added SetJSON GetJSON

2021.12.14 - Added support for DB dialects

2021.12.14 - Removed GORM dependency and moved to the standard library

Documentation

Index

Constants

View Source
const (
	COLUMN_CREATED_AT      = "created_at"
	COLUMN_EXPIRES_AT      = "expires_at"
	COLUMN_ID              = "id"
	COLUMN_IP_ADDRESS      = "ip_address"
	COLUMN_SESSION_KEY     = "session_key"
	COLUMN_SESSION_VALUE   = "session_value"
	COLUMN_SOFT_DELETED_AT = "soft_deleted_at"
	COLUMN_UPDATED_AT      = "updated_at"
	COLUMN_USER_AGENT      = "user_agent"
	COLUMN_USER_ID         = "user_id"
)

Column names for the session table

View Source
const MAX_DATETIME = "9999-12-31 23:59:59"

MAX_DATETIME is a far-future datetime used as the default soft-delete sentinel.

Variables

This section is empty.

Functions

This section is empty.

Types

type NewStoreOptions

type NewStoreOptions struct {
	SessionTableName   string
	DB                 *sql.DB
	TimeoutSeconds     int64
	AutomigrateEnabled bool
	DebugEnabled       bool
	EncryptionEnabled  bool
	EncryptionKey      []byte
}

NewStoreOptions defines the options for creating a new session store.

type SessionInterface

type SessionInterface interface {
	IsExpired() bool
	IsSoftDeleted() bool

	GetID() string
	SetID(id string) SessionInterface

	GetKey() string
	SetKey(key string) SessionInterface

	GetUserID() string
	SetUserID(userID string) SessionInterface

	GetIPAddress() string
	SetIPAddress(ipAddress string) SessionInterface

	GetUserAgent() string
	SetUserAgent(userAgent string) SessionInterface

	GetValue() string
	SetValue(value string) SessionInterface

	GetExpiresAt() string
	GetExpiresAtCarbon() *carbon.Carbon
	SetExpiresAt(expiresAt string) SessionInterface

	GetCreatedAt() string
	GetCreatedAtCarbon() *carbon.Carbon
	SetCreatedAt(createdAt string) SessionInterface

	GetUpdatedAt() string
	GetUpdatedAtCarbon() *carbon.Carbon
	SetUpdatedAt(updatedAt string) SessionInterface

	GetSoftDeletedAt() string
	GetSoftDeletedAtCarbon() *carbon.Carbon
	SetSoftDeletedAt(deletedAt string) SessionInterface
}

SessionInterface defines the interface for a session record.

func NewSession

func NewSession() SessionInterface

NewSession creates a new session.

func NewSessionFromExistingData

func NewSessionFromExistingData(data map[string]string) SessionInterface

NewSessionFromExistingData creates a new session from a raw column map (e.g. query results).

type SessionOptionsInterface

type SessionOptionsInterface interface {
	HasUserID() bool
	GetUserID() string
	SetUserID(userID string)

	HasIPAddress() bool
	GetIPAddress() string
	SetIPAddress(ipAddress string)

	HasUserAgent() bool
	GetUserAgent() string
	SetUserAgent(userAgent string)
}

SessionOptionsInterface is an interface for session options

func NewSessionOptions

func NewSessionOptions() SessionOptionsInterface

NewSessionOptions creates a new session options

func SessionOptions

func SessionOptions() SessionOptionsInterface

SessionOptions shortcut for NewSessionOptions

type SessionQueryInterface

type SessionQueryInterface interface {
	Validate() error

	HasCreatedAtGte() bool
	CreatedAtGte() string
	SetCreatedAtGte(createdAtGte string) SessionQueryInterface

	HasCreatedAtLte() bool
	CreatedAtLte() string
	SetCreatedAtLte(createdAtLte string) SessionQueryInterface

	HasExpiresAtGte() bool
	ExpiresAtGte() string
	SetExpiresAtGte(expiresAtGte string) SessionQueryInterface

	HasExpiresAtLte() bool
	ExpiresAtLte() string
	SetExpiresAtLte(expiresAtLte string) SessionQueryInterface

	HasID() bool
	ID() string
	SetID(id string) SessionQueryInterface

	HasIDIn() bool
	IDIn() []string
	SetIDIn(idIn []string) SessionQueryInterface

	HasKey() bool
	Key() string
	SetKey(key string) SessionQueryInterface

	HasUserID() bool
	UserID() string
	SetUserID(userID string) SessionQueryInterface

	HasUserIpAddress() bool
	UserIpAddress() string
	SetUserIpAddress(userIpAddress string) SessionQueryInterface

	HasUserAgent() bool
	UserAgent() string
	SetUserAgent(userAgent string) SessionQueryInterface

	HasOffset() bool
	Offset() int
	SetOffset(offset int) SessionQueryInterface

	HasLimit() bool
	Limit() int
	SetLimit(limit int) SessionQueryInterface

	HasSortOrder() bool
	SortOrder() string
	SetSortOrder(sortOrder string) SessionQueryInterface

	HasOrderBy() bool
	OrderBy() string
	SetOrderBy(orderBy string) SessionQueryInterface

	HasSoftDeletedIncluded() bool
	SoftDeletedIncluded() bool
	SetSoftDeletedIncluded(withSoftDeleted bool) SessionQueryInterface
}

SessionQueryInterface defines the interface for session query operations.

func NewSessionQuery

func NewSessionQuery() SessionQueryInterface

NewSessionQuery creates a new session query.

func SessionQuery

func SessionQuery() SessionQueryInterface

SessionQuery is a shortcut for NewSessionQuery.

type StoreInterface

type StoreInterface interface {
	// GetSessionTableName returns the session table name
	GetSessionTableName() string
	// SetSessionTableName sets the session table name
	SetSessionTableName(sessionTableName string)
	// GetTimeoutSeconds returns the session timeout in seconds
	GetTimeoutSeconds() int64
	// SetTimeoutSeconds sets the session timeout in seconds
	SetTimeoutSeconds(timeoutSeconds int64)

	// MigrateDown drops the session table
	MigrateDown(ctx context.Context, tx ...*sql.Tx) error
	// MigrateUp creates the session table
	MigrateUp(ctx context.Context, tx ...*sql.Tx) error

	EnableDebug(debug bool)
	SessionExpiryGoroutine(ctx context.Context) error
	GetDB() *sql.DB

	// Old API
	Set(ctx context.Context, key string, value string, seconds int64, options SessionOptionsInterface) error
	Get(ctx context.Context, key string, defaultValue string, options SessionOptionsInterface) (string, error)
	GetMap(ctx context.Context, key string, defaultValue map[string]any, options SessionOptionsInterface) (map[string]any, error)
	GetAny(ctx context.Context, key string, defaultValue any, options SessionOptionsInterface) (any, error)
	Delete(ctx context.Context, key string, options SessionOptionsInterface) error
	Extend(ctx context.Context, key string, seconds int64, options SessionOptionsInterface) error
	Has(ctx context.Context, key string, options SessionOptionsInterface) (bool, error)
	MergeMap(ctx context.Context, key string, value map[string]any, seconds int64, options SessionOptionsInterface) error
	SetAny(ctx context.Context, key string, value any, seconds int64, options SessionOptionsInterface) error
	SetMap(ctx context.Context, key string, value map[string]any, seconds int64, options SessionOptionsInterface) error

	// New API
	SessionCount(ctx context.Context, query SessionQueryInterface) (int64, error)
	SessionCreate(ctx context.Context, session SessionInterface) error
	SessionDelete(ctx context.Context, session SessionInterface) error
	SessionDeleteByID(ctx context.Context, sessionID string) error
	SessionExtend(ctx context.Context, session SessionInterface, seconds int64) error
	SessionFindByID(ctx context.Context, sessionID string, options ...SessionOptionsInterface) (SessionInterface, error)
	SessionFindByKey(ctx context.Context, sessionKey string, options ...SessionOptionsInterface) (SessionInterface, error)
	SessionList(ctx context.Context, query SessionQueryInterface) ([]SessionInterface, error)
	SessionSoftDelete(ctx context.Context, session SessionInterface) error
	SessionSoftDeleteByID(ctx context.Context, sessionID string) error
	SessionUpdate(ctx context.Context, session SessionInterface) error
}

func NewStore

func NewStore(opts NewStoreOptions) (StoreInterface, error)

NewStore creates a new session store.

Jump to

Keyboard shortcuts

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