session

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2025 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrJWTSigningKey           = utils.Error("JWT signing key is required")
	ErrInvalidSigningAlgorithm = utils.Error("JWT signing algorithm is invalid")
)
View Source
const (
	// DefaultSessionCookieName is the default cookie name for storing sessions
	DefaultSessionCookieName = "blueprint_session"

	// DefaultSessionExpiration is the default expiration time for sessions (30 minutes)
	DefaultSessionExpiration = 1800

	// DefaultSessionIdleTimeout is the default idle timeout for sessions (15 minutes)
	DefaultSessionIdleTimeout = 900

	// DefaultSecure sets the Secure flag on session cookies
	DefaultSecure = true

	// DefaultHttpOnly sets the HttpOnly flag on session cookies
	DefaultHttpOnly = true

	// DefaultSameSite sets the SameSite policy for session cookies
	DefaultSameSite = int(http.SameSiteStrictMode)

	// DefaultCleanupInterval sets how often the session cleanup runs
	DefaultCleanupInterval = 300 // 5 min

	// ContextSessionKey is the key used to store the session in the gin.Context
	ContextSessionKey = "session"

	ErrInvalidExpirationSeconds      = utils.Error("session expiration seconds must be a positive integer")
	ErrInvalidIdleTimeoutSeconds     = utils.Error("session idle timeout seconds must be a positive integer")
	ErrInvalidSameSite               = utils.Error("invalid sameSite value")
	ErrInvalidCleanupIntervalSeconds = utils.Error("session cleanup interval seconds must be a positive integer")
	ErrSessionNotFound               = utils.Error("session not found")
	ErrSessionExpired                = utils.Error("session expired")
)

Variables

View Source
var (
	ErrJWTInvalid  = errors.New("invalid JWT token")
	ErrJWTExpired  = errors.New("JWT token expired")
	ErrJWTNotFound = errors.New("JWT token not found")
)

JWT-related errors

Functions

func Delete

func Delete(c *gin.Context, key string)

Delete removes a value from the session

func Flash

func Flash(c *gin.Context, key string, value interface{})

Flash sets a one-time message in the session The message will be available for the current request and the next request

func FlashString

func FlashString(c *gin.Context, key, value string)

FlashString sets a one-time string message in the session

func GetBool

func GetBool(c *gin.Context, key string) (bool, bool)

GetBool retrieves a bool value from the session

func GetFlash

func GetFlash(c *gin.Context, key string) (interface{}, bool)

GetFlash gets a flash message from the session and removes it

func GetFlashString

func GetFlashString(c *gin.Context, key string) (string, bool)

GetFlashString gets a flash string message from the session and removes it

func GetInt

func GetInt(c *gin.Context, key string) (int, bool)

GetInt retrieves an int value from the session

func GetString

func GetString(c *gin.Context, key string) (string, bool)

GetString retrieves a string value from the session

func GetValue

func GetValue(c *gin.Context, key string) (interface{}, bool)

GetValue retrieves a value from the session

func Has

func Has(c *gin.Context, key string) bool

Has checks if a key exists in the session

func MarshallSessionData

func MarshallSessionData(session *SessionData) (string, error)

MarshallSessionData converts a session data object to JSON

func Set

func Set(c *gin.Context, key string, value interface{})

Set stores a value in the session

Types

type Claims

type Claims struct {
	jwt.RegisteredClaims
	Data map[string]interface{} `json:"data,omitempty"`
}

Claims is a custom JWT claims type

type Config

type Config struct {
	CookieName             string `json:"cookieName"`             // CookieName is the name of the cookie used to store the session ID
	ExpirationSeconds      int    `json:"expirationSeconds"`      // Expiration is the maximum lifetime of a session
	IdleTimeoutSeconds     int    `json:"idleTimeoutSeconds"`     // IdleTimeoutSeconds is the maximum time a session can be inactive
	Secure                 bool   `json:"secure"`                 // Secure sets the Secure flag on cookies (should be true in production)
	HttpOnly               bool   `json:"httpOnly"`               // HttpOnly sets the HttpOnly flag on cookies (should be true)
	SameSite               int    `json:"sameSite"`               // SameSite sets the SameSite policy for cookies
	Domain                 string `json:"domain"`                 // Domain sets the domain for the cookie
	Path                   string `json:"path"`                   // Path sets the path for the cookie
	CleanupIntervalSeconds int    `json:"cleanupIntervalSeconds"` // CleanupIntervalSeconds sets how often the session cleanup runs
}

Config holds configuration for the session store

func NewConfig

func NewConfig() *Config

NewConfig returns a default session configuration

func (*Config) Validate

func (c *Config) Validate() error

type JWTConfig

type JWTConfig struct {
	SigningKey        []byte            `json:"signingKey"`        // SigningKey is the key used to sign JWT tokens; if json, base64-encoded key
	SigningAlgorithm  string            `json:"signingAlgorithm"`  // SigningAlgorithm, one of HS256, HS384, HS512
	ExpirationSeconds int               `json:"expirationSeconds"` // ExpirationSeconds
	Issuer            string            `json:"issuer"`            // Issuer is the issuer of the token
	Audience          string            `json:"audience"`          // Audience is the audience of the token
	SigningMethod     jwt.SigningMethod `json:"-"`                 // SigningMethod is the method used to sign the token; filled on Validate()
	Expiration        time.Duration     `json:"-"`                 // Expiration is the expiration time for tokens; filled on Validate()
}

JWTConfig holds configuration for JWT tokens

func NewJWTConfig

func NewJWTConfig() *JWTConfig

NewJWTConfig returns a default JWT configuration

func (*JWTConfig) Validate

func (c *JWTConfig) Validate() error

Validate the JWT configuration

type JWTManager

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

JWTManager manages JWT tokens

func NewJWTManager

func NewJWTManager(config *JWTConfig, logger *log.Logger) (*JWTManager, error)

NewJWTManager creates a new JWT manager

func (*JWTManager) Generate

func (m *JWTManager) Generate(sessionID string, sessionData *SessionData) (string, error)

Generate creates a new JWT token with the given claims

func (*JWTManager) Get

func (m *JWTManager) Get(tokenString string) (*SessionData, error)

Get retrieves a session from a JWT token

func (*JWTManager) NewSession

func (m *JWTManager) NewSession() (*SessionData, string)

Generate creates a new session and ID

func (*JWTManager) Refresh

func (m *JWTManager) Refresh(tokenString string) (string, error)

Refresh refreshes a JWT token

func (*JWTManager) Set

func (m *JWTManager) Set(id string, session *SessionData) error

Set generates a new JWT token for the session data Note: The returned error contains the token string This is necessary because there's no persistent storage with JWT

func (*JWTManager) Validate

func (m *JWTManager) Validate(tokenString string) (*Claims, error)

Validate validates a JWT token and returns the claims

type JWTSessionManager

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

JWTManager manages JWT tokens for session management

func NewJWTSessionManager

func NewJWTSessionManager(manager *JWTManager) *JWTSessionManager

NewJWTSessionManager creates a new JWT session manager

func (*JWTSessionManager) Clear

func (m *JWTSessionManager) Clear(c *gin.Context)

Clear clears the current JWT session

func (*JWTSessionManager) Middleware

func (m *JWTSessionManager) Middleware() gin.HandlerFunc

Middleware returns a Gin middleware for JWT-based session management

func (*JWTSessionManager) Regenerate

func (m *JWTSessionManager) Regenerate(c *gin.Context)

Regenerate creates a new JWT token while preserving session data

type SessionData

type SessionData struct {
	Values       map[string]interface{}
	LastAccessed time.Time
	Created      time.Time
	ID           string
}

SessionData represents the session data stored in memory

func Get

func Get(c *gin.Context) *SessionData

Get returns the session from the context

func SessionDataFromClaims

func SessionDataFromClaims(claims *Claims) *SessionData

SessionDataFromClaims converts JWT claims to a SessionData object

func UnmarshallSessionData

func UnmarshallSessionData(data string) (*SessionData, error)

UnmarshallSessionData converts JSON to a session data object

type SessionManager

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

SessionManager manages sessions and provides middleware for Gin

func NewManager

func NewManager(store *Store, config *Config, logger *log.Logger) *SessionManager

NewManager creates a new session manager

func (*SessionManager) Clear

func (m *SessionManager) Clear(c *gin.Context)

Clear removes the session

func (*SessionManager) Middleware

func (m *SessionManager) Middleware() gin.HandlerFunc

Middleware returns a Gin middleware for session management

func (*SessionManager) Regenerate

func (m *SessionManager) Regenerate(c *gin.Context)

Regenerate regenerates the session ID to prevent session fixation

type Store

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

func NewStore

func NewStore(config *Config, backend kv.KV, logger *log.Logger) *Store

NewStore creates session store

func (*Store) Close

func (s *Store) Close()

Close closes the store

func (*Store) Delete

func (s *Store) Delete(id string) error

Delete removes a session from Client

func (*Store) Generate

func (s *Store) Generate() (*SessionData, string)

Generate creates a new session and returns its ID

func (*Store) Get

func (s *Store) Get(id string) (*SessionData, error)

Get retrieves a session from Client

func (*Store) Set

func (s *Store) Set(id string, session *SessionData) error

Set saves a session

func (*Store) StartCleanup

func (s *Store) StartCleanup()

StartCleanup is a no-op for Client as Client handles expiration

func (*Store) StopCleanup

func (s *Store) StopCleanup()

StopCleanup stops the cleanup goroutine

Jump to

Keyboard shortcuts

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