Documentation
¶
Overview ¶
Package session provides session management middleware for Fiber. This middleware handles user sessions, including storing session data in the store.
Index ¶
- Variables
- func DefaultErrorHandler(c fiber.Ctx, err error)
- func New(config ...Config) fiber.Handler
- type Config
- type Middleware
- func (m *Middleware) Delete(key any)
- func (m *Middleware) Destroy() error
- func (m *Middleware) Fresh() bool
- func (m *Middleware) Get(key any) any
- func (m *Middleware) ID() string
- func (m *Middleware) Keys() []any
- func (m *Middleware) Regenerate() error
- func (m *Middleware) Reset() error
- func (m *Middleware) Set(key, value any)
- func (m *Middleware) Store() *Store
- type Session
- func (s *Session) Delete(key any)
- func (s *Session) Destroy() error
- func (s *Session) Fresh() bool
- func (s *Session) Get(key any) any
- func (s *Session) ID() string
- func (s *Session) Keys() []any
- func (s *Session) Regenerate() error
- func (s *Session) Release()
- func (s *Session) Reset() error
- func (s *Session) Save() error
- func (s *Session) Set(key, val any)
- func (s *Session) SetIdleTimeout(idleTimeout time.Duration)
- type Store
Constants ¶
This section is empty.
Variables ¶
var ( ErrEmptySessionID = errors.New("session ID cannot be empty") ErrSessionAlreadyLoadedByMiddleware = errors.New("session already loaded by middleware") ErrSessionIDNotFoundInStore = errors.New("session ID not found in session store") )
ErrEmptySessionID is an error that occurs when the session ID is empty.
var ConfigDefault = Config{ IdleTimeout: 30 * time.Minute, KeyGenerator: utils.SecureToken, Extractor: extractors.FromCookie("session_id"), CookieSameSite: "Lax", }
ConfigDefault provides the default configuration.
var ( // ErrTypeAssertionFailed occurs when a type assertion fails. ErrTypeAssertionFailed = errors.New("failed to type-assert to *Middleware") )
Functions ¶
func DefaultErrorHandler ¶
DefaultErrorHandler logs the error and sends a 500 status code.
Parameters:
- c: The Fiber context.
- err: The error to handle.
Usage:
DefaultErrorHandler(c, err)
Types ¶
type Config ¶
type Config struct {
// Storage interface for storing session data.
//
// Optional. Default: memory.New()
Storage fiber.Storage
// Store defines the session store.
//
// Required.
Store *Store
// Next defines a function to skip this middleware when it returns true.
// Optional. Default: nil
Next func(c fiber.Ctx) bool
// ErrorHandler defines a function to handle errors.
//
// Optional. Default: nil
ErrorHandler func(fiber.Ctx, error)
// KeyGenerator generates the session key.
//
// Optional. Default: utils.SecureToken
KeyGenerator func() string
// CookieDomain defines the domain of the session cookie.
//
// Optional. Default: ""
CookieDomain string
// CookiePath defines the path of the session cookie.
//
// Optional. Default: ""
CookiePath string
// CookieSameSite specifies the SameSite attribute of the cookie.
//
// Optional. Default: "Lax"
CookieSameSite string
// Extractor is used to extract the session ID from the request.
// See: https://docs.gofiber.io/guide/extractors
//
// Optional. Default: extractors.FromCookie("session_id")
Extractor extractors.Extractor
// IdleTimeout defines the maximum duration of inactivity before the session expires.
//
// Note: The idle timeout is updated on each `Save()` call. If a middleware handler is used, `Save()` is called automatically.
//
// Optional. Default: 30 * time.Minute
IdleTimeout time.Duration
// AbsoluteTimeout defines the maximum duration of the session before it expires.
//
// If set to 0, the session will not have an absolute timeout, and will expire after the idle timeout.
//
// Optional. Default: 0
AbsoluteTimeout time.Duration
// CookieSecure specifies if the session cookie should be secure.
//
// Optional. Default: false
CookieSecure bool
// CookieHTTPOnly specifies if the session cookie should be HTTP-only.
//
// Optional. Default: false
CookieHTTPOnly bool
// CookieSessionOnly determines if the cookie should expire when the browser session ends.
//
// If true, the cookie will be deleted when the browser is closed.
// Note: This will not delete the session data from the store.
//
// Optional. Default: false
CookieSessionOnly bool
}
Config defines the configuration for the session middleware.
type Middleware ¶
type Middleware struct {
Session *Session
// contains filtered or unexported fields
}
Middleware holds session data and configuration.
func FromContext ¶
func FromContext(c fiber.Ctx) *Middleware
FromContext returns the Middleware from the Fiber context.
Parameters:
- c: The Fiber context.
Returns:
- *Middleware: The middleware object if found; otherwise, nil.
Usage:
m := session.FromContext(c)
func (*Middleware) Delete ¶
func (m *Middleware) Delete(key any)
Delete removes a key-value pair from the session.
Parameters:
- key: The key to delete.
Usage:
m.Delete("key")
func (*Middleware) Destroy ¶
func (m *Middleware) Destroy() error
Destroy destroys the session.
Returns:
- error: An error if the destruction fails.
Usage:
err := m.Destroy()
func (*Middleware) Fresh ¶
func (m *Middleware) Fresh() bool
Fresh checks if the session is fresh.
Returns:
- bool: True if the session is fresh; otherwise, false.
Usage:
isFresh := m.Fresh()
func (*Middleware) Get ¶
func (m *Middleware) Get(key any) any
Get retrieves a value from the session by key.
Parameters:
- key: The key to retrieve.
Returns:
- any: The value associated with the key.
Usage:
value := m.Get("key")
func (*Middleware) ID ¶
func (m *Middleware) ID() string
ID returns the session ID.
Returns:
- string: The session ID.
Usage:
id := m.ID()
func (*Middleware) Keys ¶
func (m *Middleware) Keys() []any
Keys returns all keys in the current session.
Returns:
- []any: A slice of all keys in the session.
Usage:
keys := m.Keys()
func (*Middleware) Regenerate ¶
func (m *Middleware) Regenerate() error
Regenerate generates a new session ID while preserving session data.
This method is commonly used after authentication to prevent session fixation attacks. Unlike Reset(), this method preserves all existing session data.
Returns:
- error: An error if the regeneration fails.
Usage:
err := m.Regenerate()
func (*Middleware) Reset ¶
func (m *Middleware) Reset() error
Reset resets the session.
Returns:
- error: An error if the reset fails.
Usage:
err := m.Reset()
func (*Middleware) Set ¶
func (m *Middleware) Set(key, value any)
Set sets a key-value pair in the session.
Parameters:
- key: The key to set.
- value: The value to set.
Usage:
m.Set("key", "value")
func (*Middleware) Store ¶
func (m *Middleware) Store() *Store
Store returns the session store.
Returns:
- *Store: The session store.
Usage:
store := m.Store()
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents a user session.
func (*Session) Delete ¶
Delete removes the key-value pair from the session.
Parameters:
- key: The key to delete.
Usage:
s.Delete("key")
func (*Session) Destroy ¶
Destroy deletes the session from storage and expires the session cookie.
Returns:
- error: An error if the destruction fails.
Usage:
err := s.Destroy()
func (*Session) Fresh ¶
Fresh returns whether the session is new
Returns:
- bool: True if the session is fresh; otherwise, false.
Usage:
isFresh := s.Fresh()
func (*Session) Get ¶
Get returns the value associated with the given key.
Parameters:
- key: The key to retrieve.
Returns:
- any: The value associated with the key.
Usage:
value := s.Get("key")
func (*Session) Keys ¶
Keys retrieves all keys in the current session.
Returns:
- []any: A slice of all keys in the session.
Usage:
keys := s.Keys()
func (*Session) Regenerate ¶
Regenerate generates a new session id and deletes the old one from storage.
Returns:
- error: An error if the regeneration fails.
Usage:
err := s.Regenerate()
func (*Session) Release ¶
func (s *Session) Release()
Release releases the session back to the pool.
This function should be called after the session is no longer needed. This function is used to reduce the number of allocations and to improve the performance of the session store.
The session should not be used after calling this function.
Important: The Release function should only be used when accessing the session directly, for example, when you have called func (s *Session) Get(ctx) to get the session. It should not be used when using the session with a *Middleware handler in the request call stack, as the middleware will still need to access the session.
Usage:
sess := session.Get(ctx) defer sess.Release()
func (*Session) Reset ¶
Reset generates a new session id, deletes the old one from storage, and resets the associated data.
Returns:
- error: An error if the reset fails.
Usage:
err := s.Reset()
func (*Session) Save ¶
Save saves the session data and updates the cookie
Note: If the session is being used in the handler, calling Save will have no effect and the session will automatically be saved when the handler returns.
Returns:
- error: An error if the save operation fails.
Usage:
err := s.Save()
func (*Session) Set ¶
Set updates or creates a new key-value pair in the session.
Parameters:
- key: The key to set.
- val: The value to set.
Usage:
s.Set("key", "value")
func (*Session) SetIdleTimeout ¶
SetIdleTimeout used when saving the session on the next call to `Save()`.
Parameters:
- idleTimeout: The duration for the idle timeout.
Usage:
s.SetIdleTimeout(time.Hour)
type Store ¶
type Store struct {
Config
}
Store manages session data using the configured storage backend.
func NewStore ¶
NewStore creates a new session store with the provided configuration.
Parameters:
- config: Variadic parameter to override default config.
Returns:
- *Store: The session store.
Usage:
store := session.NewStore()
func NewWithStore ¶
NewWithStore creates session middleware with an optional custom store.
Parameters:
- config: Variadic parameter to override default config.
Returns:
- fiber.Handler: The Fiber handler for the session middleware.
- *Store: The session store.
Usage:
handler, store := session.NewWithStore()
func (*Store) Delete ¶
Delete deletes a session by its ID.
Parameters:
- id: The unique identifier of the session.
Returns:
- error: An error if the deletion fails or if the session ID is empty.
Usage:
err := store.Delete(id)
if err != nil {
// handle error
}
func (*Store) Get ¶
Get will get/create a session.
This function will return an ErrSessionAlreadyLoadedByMiddleware if the session is already loaded by the middleware.
Parameters:
- c: The Fiber context.
Returns:
- *Session: The session object.
- error: An error if the session retrieval fails or if the session is already loaded by the middleware.
Usage:
sess, err := store.Get(c)
if err != nil {
// handle error
}
func (*Store) GetByID ¶
GetByID retrieves a session by its ID from the storage. If the session is not found, it returns nil and an error.
Unlike session middleware methods, this function does not automatically:
Load the session into the request context.
Save the session data to the storage or update the client cookie.
Important Notes:
The session object returned by GetByID does not have a context associated with it.
When using this method alongside session middleware, there is a potential for collisions, so be mindful of interactions between manually retrieved sessions and middleware-managed sessions.
If you modify a session returned by GetByID, you must call session.Save() to persist the changes.
When you are done with the session, you should call session.Release() to release the session back to the pool.
Parameters:
- id: The unique identifier of the session.
Returns:
- *Session: The session object if found; otherwise, nil.
- error: An error if the session retrieval fails or if the session ID is empty.
Usage:
sess, err := store.GetByID(id)
if err != nil {
// handle error
}
func (*Store) RegisterType ¶
RegisterType registers a custom type for encoding/decoding into any storage provider.
Parameters:
- i: The custom type to register.
Usage:
store.RegisterType(MyCustomType{})