sessions

package
v0.4.7 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2024 License: Apache-2.0 Imports: 15 Imported by: 3

Documentation

Overview

Package sessions manages users sessions

Index

Constants

View Source
const (
	UserIDKey         = "userID"
	ExternalUserIDKey = "externalUserID"
	SessionNameKey    = "name"
	UserTypeKey       = "userType"
	UsernameKey       = "username"
	EmailKey          = "email"
	WebAuthnKey       = "webauthn"
)

Variables

View Source
var (
	DefaultCookieName = "__Host-datum"
	DevCookieName     = "temporary-cookie"
)
View Source
var DebugCookieConfig = &CookieConfig{
	Path:     "/",
	MaxAge:   defaultMaxAge,
	HTTPOnly: true,
	Secure:   false,
	SameSite: http.SameSiteLaxMode,
}

DebugCookieConfig configures http.Cookie creation for debugging

View Source
var DebugOnlyCookieConfig = CookieConfig{
	Name:     DevCookieName,
	Path:     "/",
	MaxAge:   600,
	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

View Source
var DefaultCookieConfig = &CookieConfig{
	Path:     "/",
	Domain:   "",
	MaxAge:   defaultMaxAge,
	HTTPOnly: true,
	Secure:   true,
	SameSite: http.SameSiteStrictMode,
}

DefaultCookieConfig configures http.Cookie creation for production (AKA default secure valutes are set)

View Source
var (
	// ErrInvalidSession is returned when the session is invalid
	ErrInvalidSession = errors.New("invalid session provided")
)
View Source
var SessionContextKey = &ContextKey{"SessionContextKey"}

SessionContextKey is the context key for the user claims

Functions

func ContextWithToken

func ContextWithToken(ctx context.Context, token *oauth2.Token) context.Context

ContextWithToken returns a copy of ctx that stores the Token

func ContextWithUserID

func ContextWithUserID(ctx context.Context, userID string) context.Context

ContextWithUserID returns a copy of ctx that stores the user ID

func CookieExpired

func CookieExpired(cookie *http.Cookie) bool

CookieExpired checks to see if a cookie is expired

func GenerateSessionID

func GenerateSessionID() string

GenerateSessionID returns a random ulid

func GetCookie

func GetCookie(r *http.Request, cookieName string) (*http.Cookie, error)

GetCookie function retrieves a specific cookie from an HTTP request

func LoadAndSave

func LoadAndSave(sm Store[map[string]any], opts ...Option) echo.MiddlewareFunc

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

func NewDevSessionCookie(session string) *http.Cookie

NewDevSessionCookie creates a cookie from a session id using the dev cookie name

func NewSessionCookie

func NewSessionCookie(session string) *http.Cookie

NewSessionCookie creates a cookie from a session id

func OhAuthTokenFromContext

func OhAuthTokenFromContext(ctx context.Context) (*oauth2.Token, error)

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

func SessionToken(ctx context.Context) map[string]any

SessionToken returns the session token from the context maybe, unclear if this works

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

func UserIDFromContext

func UserIDFromContext(ctx context.Context) (string, error)

UserIDFromContext returns the user ID from the ctx this function assumes the session data is stored in a string map

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"`
}

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
	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

func NewSession[T any](store Store[T], name string) *Session[T]

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]) Get

func (s *Session[T]) Get(key string) T

Get returns the state value for the given key.

func (*Session[T]) GetKey

func (s *Session[T]) GetKey() string

GetKey returns the first key

func (*Session[T]) GetOk

func (s *Session[T]) GetOk(key string) (T, bool)

GetOk returns the state value for the given key and whether they key exists.

func (*Session[T]) Name

func (s *Session[T]) Name() string

Name returns the name of the session.

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).

func (*Session[T]) Set

func (s *Session[T]) Set(key string, value T)

Set sets a key/value pair in the session state.

func (*Session[T]) SetName

func (s *Session[T]) SetName(name string)

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) 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
}

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.

Jump to

Keyboard shortcuts

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