session

package module
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2023 License: MIT Imports: 15 Imported by: 4

README

session

codecov Go Report Card GoDoc

Session Middleware for Golang

Example with Middleware

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/moonrhythm/session"
    "github.com/moonrhythm/session/store"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/" {
            http.NotFound(w, r)
            return
        }

        s, _ := session.Get(r.Context(), "sess")
        cnt := s.GetInt("counter")
        cnt++
        s.Set("counter", cnt)
        w.Header().Set("Content-Type", "text/html")
        fmt.Fprintf(w, "Couter: %d<br><a href=\"/reset\">Reset</a>", cnt)
    })
    mux.HandleFunc("/reset", func(w http.ResponseWriter, r *http.Request) {
        s, _ := session.Get(r.Context(), "sess")
        s.Del("counter")
        http.Redirect(w, r, "/", http.StatusFound)
    })

    h := session.Middleware(session.Config{
        Domain:   "localhost",
        HTTPOnly: true,
        Secret:   []byte("testsecret1234"),
        MaxAge:   time.Minute,
        Path:     "/",
        Secure:   session.PreferSecure,
        Store:    new(store.Memory),
    })(mux)
    // equals to
    // h := session.New(session.Config{...}).Middleware()(mux)

    log.Fatal(http.ListenAndServe(":8080", h))
}

Example with Manager

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/moonrhythm/session"
    "github.com/moonrhythm/session/store"
)

func main() {
    mux := http.NewServeMux()

    m := session.New(session.Config{
        Domain:   "localhost",
        HTTPOnly: true,
        Secret:   []byte("testsecret1234"),
        MaxAge:   time.Minute,
        Path:     "/",
        Secure:   session.PreferSecure,
        Store:    new(store.Memory),
    })

    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/" {
            http.NotFound(w, r)
            return
        }

        s, _ := m.Get(r, "sess")
        cnt := s.GetInt("counter")
        cnt++
        s.Set("counter", cnt)
        m.Save(r.Context(), w, s)
        w.Header().Set("Content-Type", "text/html")
        fmt.Fprintf(w, "Couter: %d<br><a href=\"/reset\">Reset</a>", cnt)
    })
    mux.HandleFunc("/reset", func(w http.ResponseWriter, r *http.Request) {
        s, _ := m.Get(r, "sess")
        s.Del("counter")
        m.Save(r.Context(), w, s)
        http.Redirect(w, r, "/", http.StatusFound)
    })

    log.Fatal(http.ListenAndServe(":8080", mux))
}

See more examples

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is the error when session not found
	// store must return ErrNotFound if session data not exists
	ErrNotFound = errors.New("session: not found")
)

Errors

View Source
var (
	ErrNotPassMiddleware = errors.New("session: request not pass middleware")
)

Errors

View Source
var (
	HijackedTime = 5 * time.Minute
)

Global Session Config

Functions

func Middleware

func Middleware(config Config) func(http.Handler) http.Handler

Middleware is the Manager middleware wrapper

New(config).Middleware()

Types

type Config

type Config struct {
	Store Store

	// Secret is the salt for hash session id before put to store
	Secret []byte

	// Keys is the keys to sign session id
	Keys [][]byte

	// Cookie config
	Domain   string
	HTTPOnly bool
	Path     string
	MaxAge   time.Duration
	Secure   Secure
	SameSite http.SameSite

	// IdleTimeout is the ttl for storage,
	// if IdleTimeout is zero, it will use MaxAge
	IdleTimeout time.Duration

	// DeleteOldSession deletes the old session from store when regenerate,
	// better not to delete old session to avoid user loss session when unstable network
	DeleteOldSession bool

	// Resave forces session to save to store even if session was not modified
	Resave bool

	// ResaveAfter is the time to wait before resave since last timestamp
	ResaveAfter time.Duration

	// Rolling, set cookie every responses
	Rolling bool

	// Proxy, also checks X-Forwarded-Proto when use prefer secure
	Proxy bool

	// DisablaHashID disables hash session id when save to store
	DisableHashID bool

	// GenerateID is session id generator
	GenerateID func() string
}

Config is the session manager config

type Data added in v0.5.0

type Data map[string]interface{}

Data stores session data

func (Data) Clone added in v0.5.0

func (data Data) Clone() Data

Clone clones session data

type Flash added in v0.13.0

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

Flash type

func (*Flash) Add added in v0.13.0

func (f *Flash) Add(key string, value interface{})

Add adds value to flash

func (*Flash) Changed added in v0.13.0

func (f *Flash) Changed() bool

Changed returns true if value changed

func (*Flash) Clear added in v0.13.0

func (f *Flash) Clear()

Clear deletes all data

func (*Flash) Clone added in v0.13.0

func (f *Flash) Clone() *Flash

Clone clones flash

func (*Flash) Count added in v0.13.0

func (f *Flash) Count() int

Count returns count of flash's keys

func (*Flash) Del added in v0.13.0

func (f *Flash) Del(key string)

Del deletes key from flash

func (*Flash) Get added in v0.13.0

func (f *Flash) Get(key string) interface{}

Get gets value from flash

func (*Flash) GetBool added in v0.13.0

func (f *Flash) GetBool(key string) bool

GetBool gets bool from flash

func (*Flash) GetFloat32 added in v0.13.0

func (f *Flash) GetFloat32(key string) float32

GetFloat32 gets float32 from flash

func (*Flash) GetFloat64 added in v0.13.0

func (f *Flash) GetFloat64(key string) float64

GetFloat64 gets float64 from flash

func (*Flash) GetInt added in v0.13.0

func (f *Flash) GetInt(key string) int

GetInt gets int from flash

func (*Flash) GetInt64 added in v0.13.0

func (f *Flash) GetInt64(key string) int64

GetInt64 gets int64 from flash

func (*Flash) GetString added in v0.13.0

func (f *Flash) GetString(key string) string

GetString gets string from flash

func (*Flash) Has added in v0.13.0

func (f *Flash) Has(key string) bool

Has checks is flash has a given key

func (*Flash) Set added in v0.13.0

func (f *Flash) Set(key string, value interface{})

Set sets value to flash

func (*Flash) Values added in v0.13.0

func (f *Flash) Values(key string) []interface{}

Values returns slice of given key

type Manager added in v0.2.0

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

Manager is the session manager

func New added in v0.2.0

func New(config Config) *Manager

New creates new session manager

func (*Manager) Destroy added in v0.13.0

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

Destroy deletes session from store

func (*Manager) Get added in v0.2.0

func (m *Manager) Get(r *http.Request, name string) (*Session, error)

Get retrieves session from request

func (*Manager) Middleware added in v0.4.0

func (m *Manager) Middleware() func(http.Handler) http.Handler

Middleware injects session manager into request's context.

All data changed before write response writer's header will be save.

func (*Manager) Regenerate added in v0.13.0

func (m *Manager) Regenerate(ctx context.Context, s *Session) error

Regenerate regenerates session id use when change user access level to prevent session fixation

func (*Manager) Renew added in v0.13.0

func (m *Manager) Renew(ctx context.Context, s *Session) error

Renew clears session data and regenerate new session id

func (*Manager) Save added in v0.2.0

func (m *Manager) Save(ctx context.Context, w http.ResponseWriter, s *Session) error

Save saves session to store and set cookie to response

Save must be called before response header was written

type Secure

type Secure int

Secure config

const (
	NoSecure     Secure = iota
	PreferSecure        // if request is https will set secure cookie
	ForceSecure         // always set secure cookie
)

Secure values

type Session

type Session struct {

	// cookie config
	Name     string
	Domain   string
	Path     string
	HTTPOnly bool
	MaxAge   time.Duration
	Secure   bool
	SameSite http.SameSite
	Rolling  bool
	// contains filtered or unexported fields
}

Session type

func Get

func Get(ctx context.Context, name string) (*Session, error)

Get gets session from context

func (*Session) Changed added in v0.4.0

func (s *Session) Changed() bool

Changed returns is session data changed

func (*Session) Del

func (s *Session) Del(key string)

Del deletes data from session

func (*Session) Destroy added in v0.0.4

func (s *Session) Destroy() error

Destroy destroys session from store

Can use only with middleware

func (*Session) Flash added in v0.3.0

func (s *Session) Flash() *Flash

Flash returns flash from session,

func (*Session) Get

func (s *Session) Get(key string) interface{}

Get gets data from session

func (*Session) GetBool added in v0.5.0

func (s *Session) GetBool(key string) bool

GetBool gets bool from session

func (*Session) GetFloat32 added in v0.5.0

func (s *Session) GetFloat32(key string) float32

GetFloat32 gets float32 from session

func (*Session) GetFloat64 added in v0.5.0

func (s *Session) GetFloat64(key string) float64

GetFloat64 gets float64 from session

func (*Session) GetInt added in v0.5.0

func (s *Session) GetInt(key string) int

GetInt gets int from session

func (*Session) GetInt64 added in v0.5.0

func (s *Session) GetInt64(key string) int64

GetInt64 gets int64 from session

func (*Session) GetString added in v0.5.0

func (s *Session) GetString(key string) string

GetString gets string from session

func (*Session) Hijacked added in v0.4.0

func (s *Session) Hijacked() bool

Hijacked checks is session was hijacked

func (*Session) ID added in v0.4.0

func (s *Session) ID() string

ID returns session id or hashed session id if enable hash id

func (*Session) IsNew added in v0.5.0

func (s *Session) IsNew() bool

IsNew checks is new session

func (*Session) Pop added in v0.4.0

func (s *Session) Pop(key string) interface{}

Pop gets data from session then delete it

func (*Session) PopBool added in v0.5.0

func (s *Session) PopBool(key string) bool

PopBool pops bool from session

func (*Session) PopFloat32 added in v0.5.0

func (s *Session) PopFloat32(key string) float32

PopFloat32 pops float32 from session

func (*Session) PopFloat64 added in v0.5.0

func (s *Session) PopFloat64(key string) float64

PopFloat64 pops float64 from session

func (*Session) PopInt added in v0.5.0

func (s *Session) PopInt(key string) int

PopInt pops int from session

func (*Session) PopInt64 added in v0.5.0

func (s *Session) PopInt64(key string) int64

PopInt64 pops int64 from session

func (*Session) PopString added in v0.5.0

func (s *Session) PopString(key string) string

PopString pops string from session

func (*Session) Regenerate added in v0.5.0

func (s *Session) Regenerate() error

Regenerate regenerates session id use when change user access level to prevent session fixation

Can use only with middleware

func (*Session) Renew added in v0.3.2

func (s *Session) Renew() error

Renew clear all data in current session and regenerate session id

Can use only with middleware

func (*Session) Set

func (s *Session) Set(key string, value interface{})

Set sets data to session

type Store

type Store interface {
	Get(ctx context.Context, key string) (Data, error)
	Set(ctx context.Context, key string, value Data, opt StoreOption) error
	Del(ctx context.Context, key string) error
}

Store interface

type StoreCoder added in v0.14.0

type StoreCoder interface {
	NewEncoder(w io.Writer) StoreEncoder
	NewDecoder(r io.Reader) StoreDecoder
}

StoreCoder interface

var DefaultStoreCoder StoreCoder = defaultStoreCoder{}

DefaultStoreCoder is the default store coder

type StoreDecoder added in v0.14.0

type StoreDecoder interface {
	Decode(e interface{}) error
}

StoreDecoder interface

type StoreEncoder added in v0.14.0

type StoreEncoder interface {
	Encode(e interface{}) error
}

StoreEncoder interface

type StoreOption added in v0.5.0

type StoreOption struct {
	TTL time.Duration
}

StoreOption type

Directories

Path Synopsis
example
echo Module
http Module
package store contains store implementations
package store contains store implementations

Jump to

Keyboard shortcuts

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