sessions

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2024 License: MIT Imports: 3 Imported by: 99

README

sessions

GoDoc Workflow Sponsors Mastodon

Package sessions provides minimalist Go sessions, backed by securecookie or database stores.

Features
  • Store provides an interface for managing a user Session
    • May be implemented by custom session database backends
  • Session stores a typed value (via generics)
  • Session provides convenient key/value Set, Get, and GetOk methods
  • NewCookieStore implements a Store backed by client-side cookies (signed and optionally encrypted)

Docs

Read GoDoc

Usage

Create a Store for managing Session's. NewCookieStore returns a Store that signs and optionally encrypts cookies to support user sessions.

A Session stores a map of key/value pairs (e.g. "userID": "a1b2c3"). Starting with v0.4.0, sessions uses Go generics to allow specifying a type for stored values. Previously, values were type interface{} or any, which required type assertions.

import (
  "github.com/dghubble/sessions"
)

func NewServer() (http.Handler) {
  ...
  // client-side cookies
  store := sessions.NewCookieStore[string](
    sessions.DefaultCookieConfig,
    // use a 32 byte or 64 byte hash key
    []byte("signing-secret"),
    // use a 32 byte (AES-256) encryption key
    []byte("encryption-secret")
  )
  ...
  server.sessions = store
}

Issue a session cookie from a handler (e.g. login handler).

func (s server) Login() http.Handler {
  fn := func(w http.ResponseWriter, req *http.Request) {
    // create a session
    session := s.sessions.New("my-app")
    // add user-id to session
    session.Set("user-id", "a1b2c3")
    // save the session to the response
    if err := session.Save(w); err != nil {
      // handle error
    }
    ...
  }
  return http.HandlerFunc(fn)
}

Access the session and its values (e.g. require authentication).

func (s server) RequireLogin() http.Handler {
  fn := func(w http.ResponseWriter, req *http.Request) {
    session, err := s.sessions.Get("my-app")
    if err != nil {
      http.Error(w, "missing session", http.StatusUnauthorized)
      return
    }

    userID, present := session.GetOk("user-id")
    if !present {
      http.Error(w, "missing user-id", http.StatusUnauthorized)
      return
    }

    fmt.Fprintf(w, `<p>Welcome %d!</p>
    <form action="/logout" method="post">
    <input type="submit" value="Logout">
    </form>`, userID)
  }
  return http.HandlerFunc(fn)
}

Delete a session when a user logs out.

func (s server) Logout() http.Handler {
  fn := func(w http.ResponseWriter, req *http.Request) {
    if req.Method == "POST" {
      s.sessions.Destroy(w, "my-app")
    }
    http.Redirect(w, req, "/", http.StatusFound)
  }
  return http.HandlerFunc(fn)
}

License

MIT License

Documentation

Overview

Package sessions provides minimalist Go sessions, backed by a securecookie Store.

Index

Constants

This section is empty.

Variables

View Source
var DebugCookieConfig = &CookieConfig{
	Path:     "/",
	MaxAge:   defaultMaxAge,
	HTTPOnly: true,
	Secure:   false,
	SameSite: http.SameSiteLaxMode,
}

DebugCookieConfig configures http.Cookie creation for debugging. It does NOT require cookies be sent over HTTPS so it should only be used in development. Prefer DefaultCookieConfig.

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

DefaultCookieConfig configures http.Cookie creation for production.

Functions

This section is empty.

Types

type CookieConfig added in v0.3.0

type CookieConfig struct {
	// 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 Session

type Session[V any] struct {
	// contains filtered or unexported fields
}

Session represents state values maintained in a sessions Store.

func NewSession

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

NewSession returns a new Session.

func (*Session[V]) Destroy

func (s *Session[V]) Destroy(w http.ResponseWriter)

Destroy destroys the session. Identical to calling store.Destroy(w, session.name).

func (*Session[V]) Get added in v0.3.0

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

Get returns the state value for the given key.

func (*Session[V]) GetOk added in v0.3.0

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

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

func (*Session[V]) Name

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

Name returns the name of the session.

func (*Session[V]) Save

func (s *Session[V]) Save(w http.ResponseWriter) error

Save adds or updates the session. Identical to calling store.Save(w, session).

func (*Session[V]) Set added in v0.3.0

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

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

type Store

type Store[V any] interface {
	// New returns a new named Session
	New(name string) *Session[V]
	// Get a named Session from the request
	Get(req *http.Request, name string) (*Session[V], error)
	// Save writes a Session to the ResponseWriter
	Save(w http.ResponseWriter, session *Session[V]) error
	// Destroy removes (expires) a named Session
	Destroy(w http.ResponseWriter, name string)
}

A Store manages creating, accessing, writing, and expiring Sessions.

func NewCookieStore

func NewCookieStore[V any](config *CookieConfig, keyPairs ...[]byte) Store[V]

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