Documentation
¶
Overview ¶
Package session provides session storage and management functionality.
Index ¶
- Constants
- func AddAMR(session *fibersession.Session, method string)
- func Authenticate(session *fibersession.Session) error
- func CreateCookie(config Config, sessionID string) *fiber.Cookie
- func GetAMR(session *fibersession.Session) []string
- func GetCreatedAt(session *fibersession.Session) time.Time
- func GetEmail(session *fibersession.Session) string
- func GetLastAccess(session *fibersession.Session) time.Time
- func GetPhone(session *fibersession.Session) string
- func GetScopes(session *fibersession.Session) []string
- func GetUserID(session *fibersession.Session) string
- func HasAMR(session *fibersession.Session, method string) bool
- func HasScope(session *fibersession.Session, scope string) bool
- func IsAuthenticated(session *fibersession.Session) bool
- func SetAMR(session *fibersession.Session, amr []string)
- func SetEmail(session *fibersession.Session, email string)
- func SetPhone(session *fibersession.Session, phone string)
- func SetScopes(session *fibersession.Session, scopes []string)
- func SetUserID(session *fibersession.Session, userID string)
- func Unauthenticate(session *fibersession.Session) error
- func UpdateLastAccess(session *fibersession.Session)
- type Config
- func (c Config) Validate() error
- func (c Config) WithCookieDomain(domain string) Config
- func (c Config) WithCookieName(name string) Config
- func (c Config) WithCookiePath(path string) Config
- func (c Config) WithExpiration(exp time.Duration) Config
- func (c Config) WithHTTPOnly(httpOnly bool) Config
- func (c Config) WithKeyPrefix(prefix string) Config
- func (c Config) WithSameSite(sameSite string) Config
- func (c Config) WithSecure(secure bool) Config
- type KVManager
- func (m *KVManager) Create(ctx context.Context, data map[string]interface{}, ttl time.Duration) (string, error)
- func (m *KVManager) Delete(ctx context.Context, id string) error
- func (m *KVManager) Exists(ctx context.Context, id string) (bool, error)
- func (m *KVManager) Get(ctx context.Context, id string) (*KVSessionRecord, error)
- func (m *KVManager) Refresh(ctx context.Context, id string, ttl time.Duration) error
- func (m *KVManager) Set(ctx context.Context, id string, data map[string]interface{}, ttl time.Duration) error
- type KVSessionRecord
- type Manager
- func (m *Manager) CreateSession(id string) *SessionData
- func (m *Manager) DeleteSession(id string) error
- func (m *Manager) FiberSessionConfig() fibersession.Config
- func (m *Manager) GetConfig() Config
- func (m *Manager) GetStorage() Storage
- func (m *Manager) LoadSession(id string) (*SessionData, error)
- func (m *Manager) SaveSession(session *SessionData) error
- func (m *Manager) TouchSession(session *SessionData) error
- type MemoryStorage
- type RedisStorage
- func (s *RedisStorage) Close() error
- func (s *RedisStorage) Delete(key string) error
- func (s *RedisStorage) Exists(key string) (bool, error)
- func (s *RedisStorage) Expire(key string, exp time.Duration) error
- func (s *RedisStorage) Get(key string) ([]byte, error)
- func (s *RedisStorage) GetClient() *redis.Client
- func (s *RedisStorage) GetKeyPrefix() string
- func (s *RedisStorage) GetTTL(key string) (time.Duration, error)
- func (s *RedisStorage) Reset() error
- func (s *RedisStorage) Set(key string, val []byte, exp time.Duration) error
- type RedisStore
- func (s *RedisStore) Create(ctx context.Context, data map[string]interface{}, ttl time.Duration) (string, error)
- func (s *RedisStore) Delete(ctx context.Context, id string) error
- func (s *RedisStore) Exists(ctx context.Context, id string) (bool, error)
- func (s *RedisStore) Get(ctx context.Context, id string) (*KVSessionRecord, error)
- func (s *RedisStore) Set(ctx context.Context, id string, data map[string]interface{}, ttl time.Duration) error
- type SessionData
- func (s *SessionData) AddAMR(method string)
- func (s *SessionData) AddScope(scope string)
- func (s *SessionData) DeleteValue(key string)
- func (s *SessionData) GetValue(key string) (interface{}, bool)
- func (s *SessionData) HasAMR(method string) bool
- func (s *SessionData) HasScope(scope string) bool
- func (s *SessionData) IsAuthenticated() bool
- func (s *SessionData) IsExpired() bool
- func (s *SessionData) SetValue(key string, value interface{})
- func (s *SessionData) Touch()
- type Storage
- type StorageConfig
- func (c StorageConfig) WithKeyPrefix(prefix string) StorageConfig
- func (c StorageConfig) WithMemoryGCInterval(interval time.Duration) StorageConfig
- func (c StorageConfig) WithRedisAddr(addr string) StorageConfig
- func (c StorageConfig) WithRedisClient(client *redis.Client) StorageConfig
- func (c StorageConfig) WithRedisDB(db int) StorageConfig
- func (c StorageConfig) WithRedisPassword(password string) StorageConfig
- func (c StorageConfig) WithType(t StorageType) StorageConfig
- type StorageType
- type Store
Constants ¶
const ( KeyAuthenticated = "authenticated" KeyUserID = "user_id" KeyEmail = "email" KeyPhone = "phone" KeyAMR = "amr" KeyScopes = "scopes" KeyCreatedAt = "created_at" KeyLastAccess = "last_access" )
SessionKeys defines common session key names.
Variables ¶
This section is empty.
Functions ¶
func AddAMR ¶
func AddAMR(session *fibersession.Session, method string)
AddAMR adds an authentication method reference to a fiber session.
func Authenticate ¶
func Authenticate(session *fibersession.Session) error
Authenticate marks a fiber session as authenticated.
func CreateCookie ¶
CreateCookie creates a fiber.Cookie for session sharing across domains.
func GetAMR ¶
func GetAMR(session *fibersession.Session) []string
GetAMR gets the authentication methods references from a fiber session.
func GetCreatedAt ¶
func GetCreatedAt(session *fibersession.Session) time.Time
GetCreatedAt gets the session creation timestamp from a fiber session.
func GetEmail ¶
func GetEmail(session *fibersession.Session) string
GetEmail gets the email from a fiber session.
func GetLastAccess ¶
func GetLastAccess(session *fibersession.Session) time.Time
GetLastAccess gets the last access timestamp from a fiber session.
func GetPhone ¶
func GetPhone(session *fibersession.Session) string
GetPhone gets the phone from a fiber session.
func GetScopes ¶
func GetScopes(session *fibersession.Session) []string
GetScopes gets the authorization scopes from a fiber session.
func GetUserID ¶
func GetUserID(session *fibersession.Session) string
GetUserID gets the user ID from a fiber session.
func HasAMR ¶
func HasAMR(session *fibersession.Session, method string) bool
HasAMR checks if a fiber session has a specific authentication method.
func HasScope ¶
func HasScope(session *fibersession.Session, scope string) bool
HasScope checks if a fiber session has a specific scope.
func IsAuthenticated ¶
func IsAuthenticated(session *fibersession.Session) bool
IsAuthenticated checks if a fiber session is authenticated.
func SetAMR ¶
func SetAMR(session *fibersession.Session, amr []string)
SetAMR sets the authentication methods references in a fiber session.
func SetEmail ¶
func SetEmail(session *fibersession.Session, email string)
SetEmail sets the email in a fiber session.
func SetPhone ¶
func SetPhone(session *fibersession.Session, phone string)
SetPhone sets the phone in a fiber session.
func SetScopes ¶
func SetScopes(session *fibersession.Session, scopes []string)
SetScopes sets the authorization scopes in a fiber session.
func SetUserID ¶
func SetUserID(session *fibersession.Session, userID string)
SetUserID sets the user ID in a fiber session.
func Unauthenticate ¶
func Unauthenticate(session *fibersession.Session) error
Unauthenticate destroys a fiber session. Note: session.Destroy() requires a valid context (ctx). If session has been previously saved, the context may be released. This function handles nil session gracefully.
func UpdateLastAccess ¶
func UpdateLastAccess(session *fibersession.Session)
UpdateLastAccess updates the last access timestamp in a fiber session.
Types ¶
type Config ¶
type Config struct {
// Expiration is the session expiration duration.
// Default: 24 hours
Expiration time.Duration
// CookieName is the name of the session cookie.
// Default: "session_id"
CookieName string
// CookieDomain is the domain for the session cookie.
// If empty, the cookie will be set for the current domain only.
// Default: "" (empty)
CookieDomain string
// CookiePath is the path for the session cookie.
// Default: "/"
CookiePath string
// Secure indicates if the cookie should only be sent over HTTPS.
// Default: true
Secure bool
// HTTPOnly indicates if the cookie should be inaccessible to JavaScript.
// Default: true
HTTPOnly bool
// SameSite controls the SameSite attribute of the cookie.
// Allowed values: "Strict", "Lax", "None", "Disabled"
// Default: "Lax"
SameSite string
// KeyPrefix is the prefix for session keys in storage.
// Default: "session:"
KeyPrefix string
}
Config represents session configuration options.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible default values.
func (Config) Validate ¶
Validate validates the configuration and returns an error if invalid. Note: This method uses a value receiver, so it cannot modify the config. Use DefaultConfig() with builder methods to ensure valid configuration.
func (Config) WithCookieDomain ¶
WithCookieDomain sets the session cookie domain.
func (Config) WithCookieName ¶
WithCookieName sets the session cookie name.
func (Config) WithCookiePath ¶
WithCookiePath sets the session cookie path.
func (Config) WithExpiration ¶
WithExpiration sets the session expiration duration.
func (Config) WithHTTPOnly ¶
WithHTTPOnly sets whether the cookie should be inaccessible to JavaScript.
func (Config) WithKeyPrefix ¶
WithKeyPrefix sets the prefix for session keys in storage.
func (Config) WithSameSite ¶
WithSameSite sets the SameSite attribute of the cookie. Allowed values: "Strict", "Lax", "None", "Disabled"
func (Config) WithSecure ¶
WithSecure sets whether the cookie should only be sent over HTTPS.
type KVManager ¶ added in v1.1.0
type KVManager struct {
// contains filtered or unexported fields
}
KVManager wraps a Store and provides default TTL and a high-level API. Use NewKVManager(store, defaultTTL) then Create/Get/Set/Delete/Exists/Refresh.
func NewKVManager ¶ added in v1.1.0
NewKVManager returns a KVManager that uses the given store and default TTL.
func (*KVManager) Create ¶ added in v1.1.0
func (m *KVManager) Create(ctx context.Context, data map[string]interface{}, ttl time.Duration) (string, error)
Create creates a new session and returns its ID.
func (*KVManager) Exists ¶ added in v1.1.0
Exists reports whether a session exists for the given ID.
func (*KVManager) Get ¶ added in v1.1.0
Get returns the session for the given ID, or an error if not found/expired.
type KVSessionRecord ¶ added in v1.1.0
type KVSessionRecord struct {
ID string `json:"id"`
Data map[string]interface{} `json:"data"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
KVSessionRecord is a generic key-value session record for server-side sessions (e.g. Herald). It is not tied to Fiber; use SessionData and Storage for Fiber session backends.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager provides high-level session management operations.
func NewManager ¶
NewManager creates a new session Manager with the given storage and configuration.
func (*Manager) CreateSession ¶
func (m *Manager) CreateSession(id string) *SessionData
CreateSession creates a new session and returns its data.
func (*Manager) DeleteSession ¶
DeleteSession removes a session from storage.
func (*Manager) FiberSessionConfig ¶
func (m *Manager) FiberSessionConfig() fibersession.Config
FiberSessionConfig returns a fiber/v2/middleware/session.Config configured to use the Manager's storage.
func (*Manager) GetStorage ¶
GetStorage returns the underlying storage.
func (*Manager) LoadSession ¶
func (m *Manager) LoadSession(id string) (*SessionData, error)
LoadSession loads a session from storage.
func (*Manager) SaveSession ¶
func (m *Manager) SaveSession(session *SessionData) error
SaveSession saves a session to storage.
func (*Manager) TouchSession ¶
func (m *Manager) TouchSession(session *SessionData) error
TouchSession updates the last access time and extends expiration.
type MemoryStorage ¶
type MemoryStorage struct {
// contains filtered or unexported fields
}
MemoryStorage implements Storage interface using in-memory map. This is useful for development and testing, but not suitable for production with multiple server instances as sessions won't be shared.
func NewMemoryStorage ¶
func NewMemoryStorage(keyPrefix string, gcInterval time.Duration) *MemoryStorage
NewMemoryStorage creates a new in-memory storage. The gcInterval parameter specifies how often to run garbage collection to clean up expired entries. If gcInterval is 0, garbage collection is disabled.
func (*MemoryStorage) Close ¶
func (s *MemoryStorage) Close() error
Close stops the garbage collector and releases resources.
func (*MemoryStorage) Delete ¶
func (s *MemoryStorage) Delete(key string) error
Delete removes the value for the given key. It returns no error if the storage does not contain the key.
func (*MemoryStorage) Get ¶
func (s *MemoryStorage) Get(key string) ([]byte, error)
Get retrieves the value for the given key. Returns nil, nil if the key does not exist or has expired.
func (*MemoryStorage) Len ¶
func (s *MemoryStorage) Len() int
Len returns the number of entries in the storage (including expired ones).
func (*MemoryStorage) Reset ¶
func (s *MemoryStorage) Reset() error
Reset removes all keys with the configured prefix.
type RedisStorage ¶
type RedisStorage struct {
// contains filtered or unexported fields
}
RedisStorage implements Storage interface using Redis. This is suitable for production with multiple server instances as sessions are shared via Redis.
func NewRedisStorage ¶
func NewRedisStorage(client *redis.Client, keyPrefix string) *RedisStorage
NewRedisStorage creates a new Redis storage for sessions. The client parameter should be a valid Redis client. The keyPrefix is prepended to all session keys.
func NewRedisStorageFromConfig ¶
func NewRedisStorageFromConfig(addr, password string, db int, keyPrefix string) (*RedisStorage, error)
NewRedisStorageFromConfig creates a new Redis storage using configuration. This is a convenience function that creates both the Redis client and storage.
func (*RedisStorage) Close ¶
func (s *RedisStorage) Close() error
Close closes the Redis client connection.
func (*RedisStorage) Delete ¶
func (s *RedisStorage) Delete(key string) error
Delete removes the value for the given key. It returns no error if the storage does not contain the key.
func (*RedisStorage) Exists ¶
func (s *RedisStorage) Exists(key string) (bool, error)
Exists checks if a key exists in Redis.
func (*RedisStorage) Expire ¶
func (s *RedisStorage) Expire(key string, exp time.Duration) error
Expire sets a new expiration on a key.
func (*RedisStorage) Get ¶
func (s *RedisStorage) Get(key string) ([]byte, error)
Get retrieves the value for the given key. Returns nil, nil if the key does not exist.
func (*RedisStorage) GetClient ¶
func (s *RedisStorage) GetClient() *redis.Client
GetClient returns the underlying Redis client. This can be useful for advanced operations not covered by the Storage interface.
func (*RedisStorage) GetKeyPrefix ¶
func (s *RedisStorage) GetKeyPrefix() string
GetKeyPrefix returns the key prefix used by this storage.
func (*RedisStorage) GetTTL ¶
func (s *RedisStorage) GetTTL(key string) (time.Duration, error)
GetTTL returns the remaining TTL for a key. Returns -2 if the key does not exist, -1 if the key has no expiration.
func (*RedisStorage) Reset ¶
func (s *RedisStorage) Reset() error
Reset removes all keys with the configured prefix.
type RedisStore ¶ added in v1.1.0
type RedisStore struct {
// contains filtered or unexported fields
}
RedisStore implements Store using Redis. Keys are prefixed with keyPrefix.
func NewRedisStore ¶ added in v1.1.0
func NewRedisStore(client *redis.Client, keyPrefix string) *RedisStore
NewRedisStore creates a Redis-backed Store. keyPrefix is prepended to all keys (e.g. "otp:session:").
func (*RedisStore) Create ¶ added in v1.1.0
func (s *RedisStore) Create(ctx context.Context, data map[string]interface{}, ttl time.Duration) (string, error)
Create creates a new session and returns its ID.
func (*RedisStore) Delete ¶ added in v1.1.0
func (s *RedisStore) Delete(ctx context.Context, id string) error
Delete removes the session for the given ID.
func (*RedisStore) Exists ¶ added in v1.1.0
Exists reports whether a session exists for the given ID.
func (*RedisStore) Get ¶ added in v1.1.0
func (s *RedisStore) Get(ctx context.Context, id string) (*KVSessionRecord, error)
Get returns the session for the given ID, or nil and error if not found/expired.
type SessionData ¶
type SessionData struct {
// ID is the unique session identifier.
ID string `json:"id"`
// UserID is the authenticated user's ID.
UserID string `json:"user_id,omitempty"`
// Email is the authenticated user's email.
Email string `json:"email,omitempty"`
// Phone is the authenticated user's phone number.
Phone string `json:"phone,omitempty"`
// Authenticated indicates if the session is authenticated.
Authenticated bool `json:"authenticated"`
// Data is a map for storing arbitrary session data.
Data map[string]interface{} `json:"data,omitempty"`
// CreatedAt is when the session was created.
CreatedAt time.Time `json:"created_at"`
// ExpiresAt is when the session expires.
ExpiresAt time.Time `json:"expires_at"`
// LastAccessedAt is when the session was last accessed.
LastAccessedAt time.Time `json:"last_accessed_at"`
// AMR (Authentication Methods References) records how the user authenticated.
AMR []string `json:"amr,omitempty"`
// Scopes are the authorization scopes for this session.
Scopes []string `json:"scopes,omitempty"`
}
SessionData represents the data stored in a session.
func NewSessionData ¶
func NewSessionData(id string, expiration time.Duration) *SessionData
NewSessionData creates a new SessionData with the given ID and expiration.
func (*SessionData) AddAMR ¶
func (s *SessionData) AddAMR(method string)
AddAMR adds an authentication method reference.
func (*SessionData) AddScope ¶
func (s *SessionData) AddScope(scope string)
AddScope adds an authorization scope.
func (*SessionData) DeleteValue ¶
func (s *SessionData) DeleteValue(key string)
DeleteValue removes a value from the session data map.
func (*SessionData) GetValue ¶
func (s *SessionData) GetValue(key string) (interface{}, bool)
GetValue gets a value from the session data map.
func (*SessionData) HasAMR ¶
func (s *SessionData) HasAMR(method string) bool
HasAMR checks if the session has a specific authentication method.
func (*SessionData) HasScope ¶
func (s *SessionData) HasScope(scope string) bool
HasScope checks if the session has a specific scope.
func (*SessionData) IsAuthenticated ¶
func (s *SessionData) IsAuthenticated() bool
IsAuthenticated returns true if the session is authenticated and not expired.
func (*SessionData) IsExpired ¶
func (s *SessionData) IsExpired() bool
IsExpired checks if the session has expired.
func (*SessionData) SetValue ¶
func (s *SessionData) SetValue(key string, value interface{})
SetValue sets a value in the session data map.
func (*SessionData) Touch ¶
func (s *SessionData) Touch()
Touch updates the last accessed time to now.
type Storage ¶
type Storage interface {
// Get retrieves the value for the given key.
// Returns nil, nil if the key does not exist.
Get(key string) ([]byte, error)
// Set stores the given value for the given key along with an expiration value.
// If expiration is 0, the value never expires.
// Empty key or value will be ignored without an error.
Set(key string, val []byte, exp time.Duration) error
// Delete removes the value for the given key.
// It returns no error if the storage does not contain the key.
Delete(key string) error
// Reset removes all keys with the configured prefix.
Reset() error
// Close closes the storage connection.
Close() error
}
Storage is the interface for session storage backends. This interface is compatible with fiber.Storage interface.
func MustNewStorage ¶
func MustNewStorage(cfg StorageConfig) Storage
MustNewStorage creates a new Storage instance or panics if an error occurs. This is useful for initialization in main() where errors should be fatal.
func NewStorage ¶
func NewStorage(cfg StorageConfig) (Storage, error)
NewStorage creates a new Storage instance based on the configuration. It automatically selects the appropriate storage backend based on the Type field.
func NewStorageFromEnv ¶
func NewStorageFromEnv(redisEnabled bool, redisAddr, redisPassword string, redisDB int, keyPrefix string) (Storage, error)
NewStorageFromEnv creates a Storage based on environment-like configuration. If redisEnabled is true, it creates a Redis storage; otherwise, it creates a memory storage. This is a convenience function for common use cases.
type StorageConfig ¶
type StorageConfig struct {
// Type is the storage backend type.
Type StorageType
// KeyPrefix is the prefix for session keys.
KeyPrefix string
// RedisAddr is the Redis server address (for Redis storage).
RedisAddr string
// RedisPassword is the Redis password (for Redis storage).
RedisPassword string
// RedisDB is the Redis database number (for Redis storage).
RedisDB int
// RedisClient is an existing Redis client (for Redis storage).
// If provided, RedisAddr, RedisPassword, and RedisDB are ignored.
RedisClient *redis.Client
// MemoryGCInterval is the garbage collection interval for memory storage.
// Default: 10 minutes. Set to 0 to disable GC.
MemoryGCInterval time.Duration
}
StorageConfig represents configuration for creating a storage backend.
func DefaultStorageConfig ¶
func DefaultStorageConfig() StorageConfig
DefaultStorageConfig returns a StorageConfig with default values.
func (StorageConfig) WithKeyPrefix ¶
func (c StorageConfig) WithKeyPrefix(prefix string) StorageConfig
WithKeyPrefix sets the key prefix.
func (StorageConfig) WithMemoryGCInterval ¶
func (c StorageConfig) WithMemoryGCInterval(interval time.Duration) StorageConfig
WithMemoryGCInterval sets the memory storage garbage collection interval.
func (StorageConfig) WithRedisAddr ¶
func (c StorageConfig) WithRedisAddr(addr string) StorageConfig
WithRedisAddr sets the Redis address.
func (StorageConfig) WithRedisClient ¶
func (c StorageConfig) WithRedisClient(client *redis.Client) StorageConfig
WithRedisClient sets an existing Redis client.
func (StorageConfig) WithRedisDB ¶
func (c StorageConfig) WithRedisDB(db int) StorageConfig
WithRedisDB sets the Redis database number.
func (StorageConfig) WithRedisPassword ¶
func (c StorageConfig) WithRedisPassword(password string) StorageConfig
WithRedisPassword sets the Redis password.
func (StorageConfig) WithType ¶
func (c StorageConfig) WithType(t StorageType) StorageConfig
WithType sets the storage type.
type StorageType ¶
type StorageType string
StorageType represents the type of storage backend.
const ( // StorageTypeMemory uses in-memory storage. StorageTypeMemory StorageType = "memory" // StorageTypeRedis uses Redis storage. StorageTypeRedis StorageType = "redis" )
type Store ¶ added in v1.1.0
type Store interface {
Create(ctx context.Context, data map[string]interface{}, ttl time.Duration) (id string, err error)
Get(ctx context.Context, id string) (*KVSessionRecord, error)
Set(ctx context.Context, id string, data map[string]interface{}, ttl time.Duration) error
Delete(ctx context.Context, id string) error
Exists(ctx context.Context, id string) (bool, error)
}
Store is a generic KV session store for server-side sessions. Used by services like Herald that need Create/Get/Set/Delete/Exists with TTL.