session

package
v0.0.0-...-1ef12ea Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Codec

type Codec interface {
	Encode(deadline time.Time, values map[string]any) ([]byte, error)
	Decode([]byte) (deadline time.Time, values map[string]any, err error)
}

type Config

type Config struct {
	// IdleTimeout controls the maximum length of time a session can be inactive
	// before it expires. For example, some applications may wish to set this so
	// there is a timeout after 20 minutes of inactivity. By default IdleTimeout
	// is not set and there is no inactivity timeout.
	IdleTimeout time.Duration `env:"IDLE_TIMEOUT" json:"idleTimeout,omitempty,format:units" yaml:"idleTimeout,omitempty"`

	// Lifetime controls the maximum length of time that a session is valid for
	// before it expires. The lifetime is an 'absolute expiry' which is set when
	// the session is first created and does not change. The default value is 24
	// hours.
	Lifetime time.Duration `env:"LIFETIME" json:"lifetime,omitempty,format:units" yaml:"lifetime,omitempty"`

	// HashTokenInStore controls to store the session token or a hashed version in the store.
	HashTokenInStore bool `env:"HASH_TOKEN_IN_STORE" json:"hashTokenInStore,omitempty" yaml:"hashTokenInStore,omitempty"`

	// Cookie contains the configuration settings for session cookies.
	Cookie Cookie `envPrefix:"COOKIE_" json:"cookie,omitempty" yaml:"cookie,omitempty"`
}

func (*Config) SetDefaults

func (c *Config) SetDefaults()
type Cookie struct {
	Name        string   `env:"NAME" json:"name,omitempty" yaml:"name,omitempty"`
	Domain      string   `env:"DOMAIN" json:"domain,omitempty" yaml:"domain,omitempty"`
	Path        string   `env:"PATH" json:"path,omitempty" yaml:"path,omitempty"`
	Persist     bool     `env:"PERSIST" json:"persist,omitempty" yaml:"persist,omitempty"`
	Secure      bool     `env:"SECURE" json:"secure,omitempty" yaml:"secure,omitempty"`
	Partitioned bool     `env:"PARTITIONED" json:"partitioned,omitempty" yaml:"partitioned,omitempty"`
	SameSite    SameSite `env:"SAME_SITE" json:"sameSite,omitempty" yaml:"sameSite,omitempty"`
}

func (*Cookie) SetDefaults

func (c *Cookie) SetDefaults()

type GobCodec

type GobCodec struct{}

func NewGobCodec

func NewGobCodec() GobCodec

func (GobCodec) Decode

func (GobCodec) Decode(b []byte) (time.Time, map[string]any, error)

func (GobCodec) Encode

func (GobCodec) Encode(deadline time.Time, values map[string]any) ([]byte, error)

type SameSite

type SameSite string
const (
	SameSiteDefault SameSite = "default"
	SameSiteLax     SameSite = "lax"
	SameSiteStrict  SameSite = "strict"
	SameSiteNone    SameSite = "none"
)

func (SameSite) HTTP

func (s SameSite) HTTP() http.SameSite

func (SameSite) String

func (s SameSite) String() string

type Session

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

func New

func New(cfg Config, store Store) *Session

func NewWithCodec

func NewWithCodec(cfg Config, store Store, codec Codec) *Session

func (*Session) Clear

func (s *Session) Clear(ctx context.Context) error

Clear removes all data for the current session. The session token and lifetime are unaffected. If there is no data in the current session this is a no-op.

func (*Session) Commit

func (s *Session) Commit(ctx context.Context) (string, time.Time, error)

Commit saves the session data to the session store and returns the session token and expiry time.

func (*Session) Deadline

func (s *Session) Deadline(ctx context.Context) time.Time

Deadline returns the 'absolute' expiry time for the session. Please note that if you are using an idle timeout, it is possible that a session will expire due to non-use before the returned deadline.

func (*Session) Destroy

func (s *Session) Destroy(ctx context.Context) error

Destroy deletes the session data from the session store and sets the session status to Destroyed. Any further operations in the same request cycle will result in a new session being created.

func (*Session) Get

func (s *Session) Get(ctx context.Context, key string) any

Get returns the value for a given key from the session data. The return value has the type any so will usually need to be type asserted before you can use it. For example:

foo, ok := session.Get(r, "foo").(string)
if !ok {
	return errors.New("type assertion to string failed")
}

Also see the GetString(), GetInt(), GetBytes() and other helper methods which wrap the type conversion for common types.

func (*Session) GetBool

func (s *Session) GetBool(ctx context.Context, key string) bool

GetBool returns the bool value for a given key from the session data. The zero value for a bool (false) is returned if the key does not exist or the value could not be type asserted to a bool.

func (*Session) GetBytes

func (s *Session) GetBytes(ctx context.Context, key string) []byte

GetBytes returns the byte slice ([]byte) value for a given key from the session data. The zero value for a slice (nil) is returned if the key does not exist or could not be type asserted to []byte.

func (*Session) GetFloat32

func (s *Session) GetFloat32(ctx context.Context, key string) float32

GetFloat32 returns the float64 value for a given key from the session data. The zero value for an float64 (0) is returned if the key does not exist or the value could not be type asserted to a float64.

func (*Session) GetFloat64

func (s *Session) GetFloat64(ctx context.Context, key string) float64

GetFloat64 returns the float64 value for a given key from the session data. The zero value for an float64 (0) is returned if the key does not exist or the value could not be type asserted to a float64.

func (*Session) GetInt

func (s *Session) GetInt(ctx context.Context, key string) int

GetInt returns the int value for a given key from the session data. The zero value for an int (0) is returned if the key does not exist or the value could not be type asserted to an int.

func (*Session) GetInt16

func (s *Session) GetInt16(ctx context.Context, key string) int16

GetInt16 returns the int value for a given key from the session data. The zero value for an int16 (0) is returned if the key does not exist or the value could not be type asserted to an int32.

func (*Session) GetInt32

func (s *Session) GetInt32(ctx context.Context, key string) int32

GetInt32 returns the int value for a given key from the session data. The zero value for an int32 (0) is returned if the key does not exist or the value could not be type asserted to an int32.

func (*Session) GetInt64

func (s *Session) GetInt64(ctx context.Context, key string) int64

GetInt64 returns the int64 value for a given key from the session data. The zero value for an int64 (0) is returned if the key does not exist or the value could not be type asserted to an int64.

func (*Session) GetInt8

func (s *Session) GetInt8(ctx context.Context, key string) int8

GetInt8 returns the int value for a given key from the session data. The zero value for an int8 (0) is returned if the key does not exist or the value could not be type asserted to an int32.

func (*Session) GetRune

func (s *Session) GetRune(ctx context.Context, key string) rune

GetRune returns the rune value for a given key from the session data. The zero value for a rune (0) is returned if the key does not exist or the value could not be type asserted to a rune.

func (*Session) GetString

func (s *Session) GetString(ctx context.Context, key string) string

GetString returns the string value for a given key from the session data. The zero value for a string ("") is returned if the key does not exist or the value could not be type asserted to a string.

func (*Session) GetTime

func (s *Session) GetTime(ctx context.Context, key string) time.Time

GetTime returns the time.Time value for a given key from the session data. The zero value for a time.Time object is returned if the key does not exist or the value could not be type asserted to a time.Time. This can be tested with the time.IsZero() method.

func (*Session) GetUInt

func (s *Session) GetUInt(ctx context.Context, key string) uint

GetUInt returns the uint value for a given key from the session data. The zero value for an uint (0) is returned if the key does not exist or the value could not be type asserted to an uint.

func (*Session) Has

func (s *Session) Has(ctx context.Context, key string) bool

Has returns true if the given key is present in the session data.

func (*Session) Keys

func (s *Session) Keys(ctx context.Context) []string

Keys returns a slice of all key names present in the session data, sorted alphabetically. If the data contains no data then an empty slice will be returned.

func (*Session) Load

func (s *Session) Load(ctx context.Context, token string) (context.Context, error)

Load retrieves the session data for the given token from the session store, and returns a new context.Context containing the session data. If no matching token is found then this will create a new session.

func (*Session) MergeSession

func (s *Session) MergeSession(ctx context.Context, token string) error

MergeSession is used to merge in data from a different session in case strict session tokens are lost across an oauth or similar redirect flows. Use Clear() if no values of the new session are to be used.

func (*Session) Pop

func (s *Session) Pop(ctx context.Context, key string) any

Pop acts like a one-time Get. It returns the value for a given key from the session data and deletes the key and value from the session data. The session data status will be set to Modified. The return value has the type any so will usually need to be type asserted before you can use it.

func (*Session) PopBool

func (s *Session) PopBool(ctx context.Context, key string) bool

PopBool returns the bool value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for a bool (false) is returned if the key does not exist or the value could not be type asserted to a bool.

func (*Session) PopBytes

func (s *Session) PopBytes(ctx context.Context, key string) []byte

PopBytes returns the byte slice ([]byte) value for a given key and then deletes it from the from the session data. The session data status will be set to Modified. The zero value for a slice (nil) is returned if the key does not exist or could not be type asserted to []byte.

func (*Session) PopFloat32

func (s *Session) PopFloat32(ctx context.Context, key string) float32

PopFloat32 returns the float32 value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for an float32 (0) is returned if the key does not exist or the value could not be type asserted to a float32.

func (*Session) PopFloat64

func (s *Session) PopFloat64(ctx context.Context, key string) float64

PopFloat64 returns the float64 value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for an float64 (0) is returned if the key does not exist or the value could not be type asserted to a float64.

func (*Session) PopInt

func (s *Session) PopInt(ctx context.Context, key string) int

PopInt returns the int value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for an int (0) is returned if the key does not exist or the value could not be type asserted to an int.

func (*Session) PopInt16

func (s *Session) PopInt16(ctx context.Context, key string) int16

PopInt16 returns the int16 value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for an int16 (0) is returned if the key does not exist or the value could not be type asserted to an int16.

func (*Session) PopInt32

func (s *Session) PopInt32(ctx context.Context, key string) int32

PopInt32 returns the int32 value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for an int32 (0) is returned if the key does not exist or the value could not be type asserted to an int32.

func (*Session) PopInt64

func (s *Session) PopInt64(ctx context.Context, key string) int64

PopInt64 returns the int64 value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for an int64 (0) is returned if the key does not exist or the value could not be type asserted to an int64.

func (*Session) PopInt8

func (s *Session) PopInt8(ctx context.Context, key string) int8

PopInt8 returns the int8 value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for an int8 (0) is returned if the key does not exist or the value could not be type asserted to an int8.

func (*Session) PopRune

func (s *Session) PopRune(ctx context.Context, key string) rune

PopRune returns the rune value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for a rune (0) is returned if the key does not exist or the value could not be type asserted to a rune.

func (*Session) PopString

func (s *Session) PopString(ctx context.Context, key string) string

PopString returns the string value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for a string ("") is returned if the key does not exist or the value could not be type asserted to a string.

func (*Session) PopTime

func (s *Session) PopTime(ctx context.Context, key string) time.Time

PopTime returns the time.Time value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for a time.Time object is returned if the key does not exist or the value could not be type asserted to a time.Time.

func (*Session) PopUInt

func (s *Session) PopUInt(ctx context.Context, key string) uint

PopUInt returns the uint value for a given key and then deletes it from the session data. The session data status will be set to Modified. The zero value for an uint (0) is returned if the key does not exist or the value could not be type asserted to an uint.

func (*Session) Put

func (s *Session) Put(ctx context.Context, key string, val any)

Put adds a key and corresponding value to the session data. Any existing value for the key will be replaced. The session data status will be set to Modified.

func (*Session) ReadSessionCookie

func (s *Session) ReadSessionCookie(r *http.Request) (*http.Request, error)

ReadSessionCookie reads the session cookie from the HTTP request and loads the session data into the request context. If the cookie is invalid, it returns an error. The session data is stored in the request context under the key defined by the session's contextKey.

func (*Session) RememberMe

func (s *Session) RememberMe(ctx context.Context, val bool)

RememberMe controls whether the session cookie is persistent (i.e whether it is retained after a user closes their browser). RememberMe only has an effect if you have set config.Cookie.Persist = false.

func (*Session) Remove

func (s *Session) Remove(ctx context.Context, key string)

Remove deletes the given key and corresponding value from the session data. The session data status will be set to Modified. If the key is not present this operation is a no-op.

func (*Session) RenewToken

func (s *Session) RenewToken(ctx context.Context) error

RenewToken updates the session data to have a new session token while retaining the current session data. The session lifetime is also reset and the session data status will be set to Modified.

The old session token and accompanying data are deleted from the session store.

To mitigate the risk of session fixation attacks, it's important that you call RenewToken before making any changes to privilege levels (e.g. login and logout operations). See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change for additional information.

func (*Session) SetDeadline

func (s *Session) SetDeadline(ctx context.Context, expire time.Time)

SetDeadline updates the 'absolute' expiry time for the session. Please note that if you are using an idle timeout, it is possible that a session will expire due to non-use before the set deadline.

func (*Session) SetToken

func (s *Session) SetToken(ctx context.Context, token string)

func (*Session) Status

func (s *Session) Status(ctx context.Context) Status

Status returns the current status of the session data.

func (*Session) Token

func (s *Session) Token(ctx context.Context) string

Token returns the session token. Please note that this will return the empty string "" if it is called before the session has been committed to the store.

func (*Session) WriteSessionCookie

func (s *Session) WriteSessionCookie(ctx context.Context, w http.ResponseWriter, token string, expiry time.Time)

WriteSessionCookie writes a cookie to the HTTP response with the provided token as the cookie value and expiry as the cookie expiry time. The expiry time will be included in the cookie only if the session is set to persist or has had RememberMe(true) called on it. If expiry is an empty time.Time struct (so that it's IsZero() method returns true) the cookie will be marked with a historical expiry time and negative max-age (so the browser deletes it).

type Status

type Status int

Status represents the state of the session data during a request cycle.

const (
	// Unmodified indicates that the session data hasn't been changed in the
	// current request cycle.
	Unmodified Status = iota

	// Modified indicates that the session data has been changed in the current
	// request cycle.
	Modified

	// Destroyed indicates that the session data has been destroyed in the
	// current request cycle.
	Destroyed
)

type Store

type Store interface {
	// Delete should remove the session token and corresponding data from the
	// session store. If the token does not exist then Delete should be a no-op
	// and return nil (not an error).
	Delete(ctx context.Context, token string) (err error)

	// Find should return the data for a session token from the store. If the
	// session token is not found or is expired, the found return value should
	// be false (and the err return value should be nil). Similarly, tampered
	// or malformed tokens should result in a found return value of false and a
	// nil err value. The err return value should be used for system errors only.
	Find(ctx context.Context, token string) (data []byte, found bool, err error)

	// Commit should add the session token and data to the store, with the given
	// expiry time. If the session token already exists, then the data and
	// expiry time should be overwritten.
	Commit(ctx context.Context, token string, data []byte, expiry time.Time) (err error)
}

Store is the interface for session stores.

Jump to

Keyboard shortcuts

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