Documentation ¶
Overview ¶
Package sessions manages users sessions
Index ¶
- Constants
- Variables
- func ContextWithToken(ctx context.Context, token *oauth2.Token) context.Context
- func ContextWithUserID(ctx context.Context, userID string) context.Context
- func CookieExpired(cookie *http.Cookie) bool
- func GenerateSessionID() string
- func GetCookie(r *http.Request, cookieName string) (*http.Cookie, error)
- func LoadAndSave(sm Store[map[string]any], opts ...Option) echo.MiddlewareFunc
- func LoadAndSaveWithConfig(config SessionConfig) echo.MiddlewareFunc
- func NewCookie(name, value string, config *CookieConfig) *http.Cookie
- func NewDevSessionCookie(session string) *http.Cookie
- func NewSessionCookie(session string) *http.Cookie
- func OhAuthTokenFromContext(ctx context.Context) (*oauth2.Token, error)
- func RemoveCookie(w http.ResponseWriter, cookieName string, v CookieConfig)
- func SessionToken(ctx context.Context) (string, error)
- func SetCookie(w http.ResponseWriter, value string, cookieName string, v CookieConfig)
- func SetCookieB64(w http.ResponseWriter, body []byte, cookieName string, v CookieConfig) string
- func UserIDFromContext(ctx context.Context) (string, error)
- type Config
- type ContextKey
- type CookieConfig
- type Option
- type PersistentStore
- type Session
- func (s *Session[T]) Destroy(w http.ResponseWriter)
- func (s *Session[T]) Get(key string) T
- func (s *Session[T]) GetKey() string
- func (s *Session[T]) GetOk(key string) (T, bool)
- func (s *Session[T]) Name() string
- func (s *Session[T]) Save(w http.ResponseWriter) error
- func (s *Session[T]) Set(key string, value T)
- func (s *Session[T]) SetName(name string)
- type SessionConfig
- type Store
Constants ¶
const ( UserIDKey = "userID" ExternalUserIDKey = "externalUserID" SessionNameKey = "name" UserTypeKey = "userType" UsernameKey = "username" EmailKey = "email" WebAuthnKey = "webauthn" )
Variables ¶
var ( DefaultCookieName = "__Secure-SessionId" DevCookieName = "temporary-cookie" )
var DebugCookieConfig = &CookieConfig{ Path: "/", MaxAge: defaultMaxAgeSeconds, HTTPOnly: true, Secure: false, SameSite: http.SameSiteLaxMode, }
DebugCookieConfig configures http.Cookie creation for debugging
var DebugOnlyCookieConfig = CookieConfig{ Name: DevCookieName, Path: "/", MaxAge: defaultMaxAgeSeconds, HTTPOnly: true, Secure: false, SameSite: http.SameSiteLaxMode, }
DebugOnlyCookieConfig is different in that it's not a receiver and the name is set, so it can be called directly
var DefaultCookieConfig = &CookieConfig{ Path: "/", Domain: "", MaxAge: defaultMaxAgeSeconds, HTTPOnly: true, Secure: true, SameSite: http.SameSiteStrictMode, }
DefaultCookieConfig configures http.Cookie creation for production (AKA default secure values are set)
var ( // ErrInvalidSession is returned when the session is invalid ErrInvalidSession = errors.New("invalid session provided") )
var SessionContextKey = &ContextKey{"SessionContextKey"}
SessionContextKey is the context key for the user claims
Functions ¶
func ContextWithToken ¶
ContextWithToken returns a copy of ctx that stores the Token
func ContextWithUserID ¶
ContextWithUserID returns a copy of ctx that stores the user ID
func CookieExpired ¶
CookieExpired checks to see if a cookie is expired
func LoadAndSave ¶
LoadAndSave is a middleware function that loads and saves session data using a provided session manager. It takes a `SessionManager` as input and returns a middleware function that can be used with an Echo framework application
func LoadAndSaveWithConfig ¶
func LoadAndSaveWithConfig(config SessionConfig) echo.MiddlewareFunc
LoadAndSaveWithConfig is a middleware that loads and saves session data using a provided session manager configuration It takes a `SessionConfig` struct as input, which contains the skipper function and the session manager
func NewCookie ¶
func NewCookie(name, value string, config *CookieConfig) *http.Cookie
NewCookie returns a new chocolate chip http.Cookie with the given name, value, and properties from config
func NewDevSessionCookie ¶
NewDevSessionCookie creates a cookie from a session id using the dev cookie name
func NewSessionCookie ¶
NewSessionCookie creates a cookie from a session id
func OhAuthTokenFromContext ¶
OhAuthTokenFromContext returns the Token from the ctx
func RemoveCookie ¶
func RemoveCookie(w http.ResponseWriter, cookieName string, v CookieConfig)
RemoveCookie function removes a cookie from the HTTP response
func SessionToken ¶
SessionToken returns the encoded session token
func SetCookie ¶
func SetCookie(w http.ResponseWriter, value string, cookieName string, v CookieConfig)
SetCookie function sets a cookie with the given value and name
func SetCookieB64 ¶
func SetCookieB64(w http.ResponseWriter, body []byte, cookieName string, v CookieConfig) string
SetCookieB64 function sets a base64-encoded cookie with the given name and value in the HTTP response
Types ¶
type Config ¶
type Config struct { // SigningKey must be a 16, 32, or 64 character string used to encode the cookie SigningKey string `json:"signingKey" koanf:"signingKey" default:"my-signing-secret"` // EncryptionKey must be a 16, 32, or 64 character string used to encode the cookie EncryptionKey string `json:"encryptionKey" koanf:"encryptionKey" default:"encryptionsecret"` // Domain is the domain for the cookie, leave empty to use the default value of the server Domain string `json:"domain" koanf:"domain" default:""` }
Config contains the configuration for the session store
type ContextKey ¶
type ContextKey struct {
// contains filtered or unexported fields
}
ContextKey is the key name for the additional context
type CookieConfig ¶
type CookieConfig struct { Name string // Cookie domain/path scope (leave zeroed for requested resource scope) // Defaults to the domain name of the responding server when unset Domain string // Defaults to the path of the responding URL when unset Path string // MaxAge=0 means no 'Max-Age' attribute specified. // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'. // MaxAge>0 means Max-Age attribute present and given in seconds MaxAge int // cookie may only be transferred over HTTPS. Recommend true Secure bool // browser should prohibit non-HTTP (i.e. javascript) cookie access. Recommend true HTTPOnly bool // prohibit sending in cross-site requests with SameSiteLaxMode or SameSiteStrictMode SameSite http.SameSite }
CookieConfig configures http.Cookie creation
type Option ¶
type Option func(opts *SessionConfig)
Option allows users to optionally supply configuration to the session middleware.
func WithBeforeFunc ¶
func WithBeforeFunc(before middleware.BeforeFunc) Option
WithBeforeFunc allows the user to specify a function to happen before the middleware
func WithLogger ¶
func WithLogger(l *zap.SugaredLogger) Option
WithLogger allows the user to specify a zap logger for the middleware
func WithPersistence ¶
func WithPersistence(client *redis.Client) Option
WithPersistence allows the user to specify a redis client for the middleware to persist sessions
func WithSkipperFunc ¶
func WithSkipperFunc(skipper middleware.Skipper) Option
WithSkipperFunc allows the user to specify a skipper function for the middleware
type PersistentStore ¶
type PersistentStore interface { Exists(ctx context.Context, key string) (int64, error) GetSession(ctx context.Context, key string) (string, error) StoreSession(ctx context.Context, key, value string) error StoreSessionWithExpiration(ctx context.Context, key, value string, ttl time.Duration) error DeleteSession(ctx context.Context, key string) error }
PersistentStore is defining an interface for session store
func NewStore ¶
func NewStore(client *redis.Client) PersistentStore
NewStore returns a new Store that stores to a persistent backend (redis)
type Session ¶
type Session[T any] struct { // contains filtered or unexported fields }
Session represents state values maintained in a sessions Store
func NewSession ¶
NewSession returns a new Session.
func (*Session[T]) Destroy ¶
func (s *Session[T]) Destroy(w http.ResponseWriter)
Destroy destroys the session. Identical to calling store.Destroy(w, session.name).
func (*Session[T]) GetOk ¶
GetOk returns the state value for the given key and whether they key exists.
func (*Session[T]) Save ¶
func (s *Session[T]) Save(w http.ResponseWriter) error
Save adds or updates the session. Identical to calling store.Save(w, session).
type SessionConfig ¶
type SessionConfig struct { // Skipper is a function that determines whether a particular request should be skipped or not Skipper middleware.Skipper // BeforeFunc defines a function which is executed just before the middleware BeforeFunc middleware.BeforeFunc // SessionManager is responsible for managing the session cookies. It handles the creation, retrieval, and deletion of // session cookies for each user session SessionManager Store[map[string]any] // CookieConfig contains the cookie settings for sessions CookieConfig *CookieConfig // RedisStore is used to store and retrieve session data in a persistent manner such as to a redis backend RedisStore PersistentStore // RedisClient establishes a connection to a Redis server and perform operations such as storing and retrieving data RedisClient *redis.Client // Logger is used to log errors in the middleware Logger *zap.SugaredLogger }
SessionConfig is used to configure session management
func NewSessionConfig ¶
func NewSessionConfig(sm Store[map[string]any], opts ...Option) (c SessionConfig)
NewSessionConfig creates a new session config with options
func (*SessionConfig) CreateAndStoreSession ¶
func (sc *SessionConfig) CreateAndStoreSession(ctx echo.Context, userID string) error
CreateAndStoreSession creates the session values with user ID and sets the cookie stores the session in the persistent store (redis)
func (*SessionConfig) SaveAndStoreSession ¶
func (sc *SessionConfig) SaveAndStoreSession(ctx context.Context, w http.ResponseWriter, sessionMap map[string]any, userID string) (context.Context, error)
SaveAndStoreSession saves the session to the cookie and to the persistent store (redis) with the provided map of values
type Store ¶
type Store[T any] interface { // New returns a new named Session New(name string) *Session[T] // Get a named Session from the request Get(req *http.Request, name string) (*Session[T], error) // Save writes a Session to the ResponseWriter Save(w http.ResponseWriter, session *Session[T]) error // Destroy removes (expires) a named Session Destroy(w http.ResponseWriter, name string) // GetSessionIDFromCookie returns the key, which should be the sessionID, in the map GetSessionIDFromCookie(sess *Session[T]) string // GetSessionDataFromCookie returns the value stored map GetSessionDataFromCookie(sess *Session[T]) any // EncodeCookie encodes the cookie EncodeCookie(session *Session[T]) (string, error) }
func NewCookieStore ¶
func NewCookieStore[T any](config *CookieConfig, keyPairs ...[]byte) Store[T]
NewCookieStore returns a new Store that signs and optionally encrypts session state in http cookies.