session

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

README

Session Management

Go Lint Go Test Release Drafter

Session implements a session management pattern following the OWASP security guidelines. Session data is stored on the server, and a randomly-generated unique session token (or session ID) is communicated to and from the client in a session cookie. This package is based on alexedwards/scs.

Why go-session

We wanted to provide a package that was more extensible, flexible, and has additional features. By using sound coding patterns, our package allows you to easily substitute one middleware for another, for example for different HTTP servers such as Echo, Fiber, and Gin. You may also extend on existing one to provide more features. We also added the ability to customize every new session. If you would like to contribute, please open an issue with a feature request, or a PR directly if you think you have a fantastic new feature.

Usage

From your terminal, run:

$ go get github.com/inquisico/go-session
Code example
import (
    "github.com/alexedwards/scs/v2"
    "github.com/alexedwards/scs/v2/memstore"
    "github.com/inquisico/go-session"
    "github.com/inquisico/go-session/middleware"
    "github.com/inquisico/go-session/store"
)

func main() {
    sessionManager := session.NewManager(
        session.WithDefaultTTL(time.Second), // Optional
        session.WithDefaultIdleTimeout(200*time.Millisecond), // Optional
        session.WithStore(store.NewWrapper(memstore.New())) // Optional (note: you will need to wrap the stores when using stores from github.com/alexedwards/scs)
    )

    cookieConfig := scs.SessionCookie{
        Name:     "session",
        Domain:   "",
        HttpOnly: true,
        Path:     "/",
        Persist:  true,
        Secure:   false,
        SameSite: http.SameSiteLaxMode,
    }

    middleware := middleware.NewHTTPSessionManager(
        sessionManager,
        session.WithErrorFunc(errorFunc), // Optional
        session.WithCookieConfig(cookieConfig), // Optional
    )

    // Put `middleware` into your http server
    // See: https://www.alexedwards.net/blog/making-and-using-middleware
    // ...
}

Creating your own store

The interface for store can be found in store/store.go. You can implement your own store that implements that interface. See go-session/store for examples.

Compatible session stores

Inquisico managed session stores can be found at go-session/store. If you require a more extensive set of seesion stores, you may check out more compatible session stores for your desired store.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnmodified = errors.New("unmodified")
)

Functions

This section is empty.

Types

type Manager

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

Manager holds the configuration settings for your sessions.

func NewManager

func NewManager(opts ...ManagerOption) *Manager

NewManager returns a new session manager with the default options. It is safe for concurrent use.

func (*Manager) Clear

func (s *Manager) 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 (*Manager) Commit

func (s *Manager) 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.

Most applications will use the LoadAndSave() middleware and will not need to use this method.

func (*Manager) Deadline

func (s *Manager) 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 (*Manager) Destroy

func (s *Manager) Destroy(ctx context.Context, options ...Option) 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 (*Manager) Exists

func (s *Manager) Exists(ctx context.Context, key string) bool

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

func (*Manager) Get

func (s *Manager) Get(ctx context.Context, key string) interface{}

Get returns the value for a given key from the session data. The return value has the type interface{} 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 (*Manager) GetBool

func (s *Manager) 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 (*Manager) GetBytes

func (s *Manager) 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 (*Manager) GetFloat

func (s *Manager) GetFloat(ctx context.Context, key string) float64

GetFloat 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 (*Manager) GetInt

func (s *Manager) 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 (*Manager) GetInt32

func (s *Manager) 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 (*Manager) GetInt64

func (s *Manager) 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 (*Manager) GetString

func (s *Manager) 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 (*Manager) GetTime

func (s *Manager) 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 (*Manager) Iterate

func (s *Manager) Iterate(ctx context.Context, fn func(context.Context) error) error

Iterate retrieves all active (i.e. not expired) sessions from the store and executes the provided function fn for each session. If the session store being used does not support iteration then Iterate will panic.

func (*Manager) Keys

func (s *Manager) 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 (*Manager) Load

func (s *Manager) Load(ctx context.Context, token string, options ...Option) (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.

Most applications will use the LoadAndSave() middleware and will not need to use this method.

func (*Manager) MergeSession

func (s *Manager) 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 (*Manager) Pop

func (s *Manager) Pop(ctx context.Context, key string) interface{}

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 interface{} so will usually need to be type asserted before you can use it.

func (*Manager) PopBool

func (s *Manager) 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 (*Manager) PopBytes

func (s *Manager) 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 (*Manager) PopFloat

func (s *Manager) PopFloat(ctx context.Context, key string) float64

PopFloat 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 (*Manager) PopInt

func (s *Manager) 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 (*Manager) PopString

func (s *Manager) 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 (*Manager) PopTime

func (s *Manager) 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 (*Manager) Put

func (s *Manager) Put(ctx context.Context, key string, val interface{})

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 (*Manager) RememberMe

func (s *Manager) 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 SessionManager.Cookie.Persist = false (the default is true) and you are using the standard LoadAndSave() middleware.

func (*Manager) Remove

func (s *Manager) 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 (*Manager) RenewToken

func (s *Manager) RenewToken(ctx context.Context, options ...Option) error

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 (*Manager) Save

func (s *Manager) Save(ctx context.Context) (string, time.Time, error)

Save checks if the session data has been Modified or Destroyed, and commit it if the requirements are met. If the token is Unmodified, an UnmodifiedErr will be returned

Most applications will use the LoadAndSave() middleware and will not need to use this method.

func (*Manager) SetDeadline

func (s *Manager) SetDeadline(ctx context.Context, expiry 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 (*Manager) Status

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

Status returns the current status of the session data.

func (*Manager) Token

func (s *Manager) 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.

type ManagerOption

type ManagerOption func(*Manager)

func WithCodec

func WithCodec(codec scs.Codec) ManagerOption

func WithDefaultIdleTimeout

func WithDefaultIdleTimeout(duration time.Duration) ManagerOption

func WithDefaultTTL

func WithDefaultTTL(duration time.Duration) ManagerOption

func WithStore

func WithStore(store store.Store) ManagerOption

type Option

type Option func(*sessionData)

func WithDeadline

func WithDeadline(deadline time.Time) Option

func WithTTL

func WithTTL(duration time.Duration) Option

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
)

Directories

Path Synopsis
redis Module

Jump to

Keyboard shortcuts

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