session

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2021 License: MIT Imports: 7 Imported by: 0

README

Introduction:

This package wraps around the gorilla/sessions package to provide some addition tooling used in typical use cases and simplify the implementation of sessions for simple apps.

Details:

The point of this package is to provide the boilerplate functionality for starting and interacting with sessions. While gorrilla/sessions itself provides the underlying tools to work with sessions, this package further simplifies the usage of sessions while also reducing the ability to customize the implementation of your sessions store. This package was designed for a very simple use case: to get started with sessions quickly.

The session data is stored in a cookie. The data is encrypted and hashed to prevent viewing and tampering of the data outside of your server that is managing the sessions. If you use a load balancer in front of your website/app, you will need to make sure it is session-aware.

There is no dependency on a filesystem or database; all session information is stored in your website/app's memory and in the browser cookie. This provides pros in that it is very simple to get started; however the cons are that there is no server side validation outside of ensure the cookie's contents haven't changed (i.e.: the cookie expiration hasn't been changed). Furthermore, there is a limit to how much data you would want to store in a cookie and ideally you simply store a session ID in the session and refer back to a database for further information.

Getting Started:

  1. Get a default configuraiton with NewConfig() or DefaultConfig(). NewConfig() requires you to store the configuration elsewhere in your app and pass it around as needed while DefaultConfig() stores the configuration, and thus your session store, globally so you can access the session configuration without needing to pass around a variable.
  2. Initialize the session store using Init(). This will allow sessions to be created and data to be stored.
  3. Now you can add and read data from the session based on the request using AddValue() and GetValue().

Typical Use Case:

  1. Call DefaultConfig(), modify the configuration as needed, and call Init() in your main.go's init() prior to initializing any HTTP routers.
  2. Within your HTTP handler function for handling user logins, after successfully authenticating a user, use AddValue(w, r, "user_session_id", "2554") where 2554 references a session in your database table. A cookie will now exist for the user.
  3. Within other HTTP handler functions, use GetValue(r, "user_session_id") to look up the session ID, and use it to look up your user's data in your database.
  4. Typically you would call Extend(w, r) on each HTTP endpoint as well to "keep a user logged in". This would most likely be performed in some middleware after validating the session is still active and valid.

Documentation

Overview

Package session provides tooling for storing of user session data in cookies for handling user sessions. This package provides some boilerplate around the gorilla/sessions package to provide some common functionality that is typically reused in web apps.

Data stored in a sessions is stored in a cookie. The cookie data is encrypted and hashed to prevent tampering and viewing of the data client side. This data can be read, altered, and added to as needed on the server side using this package. While gorilla/sessions allows for alternative "stores", ex.: storing sessions on disk, we only support cookies since this is typically how sessions are handled.

To use, you will need to initialize your session store using NewConfig() or DefaultConfig() and then call Init(). Once this has been done, you can get a session for a request using GetSession(), add data to the session using AddValue(), and read data from the session in subsequent requests using GetValue().

We allow storing the session config globally using the package-level config variable, or you can store your Config elsewhere and pass it to requests. Most use cases will store the config in the package-level config variable just for ease of use.

Index

Constants

This section is empty.

Variables

View Source
var (
	//ErrAuthKeyWrongSize is returned when user provided an AuthKey value that isn't 64 characters.
	ErrAuthKeyWrongSize = errors.New("session: auth key is invalid, must be exactly 64 characters")

	//ErrEncyptKeyWrongSize is returned when user provided an EncryptKey value that isn't 32 characters.
	ErrEncyptKeyWrongSize = errors.New("session: encrypt key is invalid, must be exactly 32 characters")

	//ErrLifetimeTooShort is returned when user provided a MaxAge value less that 1 second.
	ErrMaxAgeTooShort = errors.New("session: max age is invalid, must be greater than 1 second")

	//ErrKeyNotFound is returned when a desired key is not found in the session.
	ErrKeyNotFound = errors.New("session: key not found in session data")
)

errors

Functions

func AddSessionID

func AddSessionID(w http.ResponseWriter, r *http.Request, value int64) error

AddSessionID adds the session ID value to the session using the session ID key and the default package level config. We assume session IDs are provided as integers.

func AddToken

func AddToken(w http.ResponseWriter, r *http.Request, value string) error

AddToken adds the token value to the session using the token key and the default package level config. We assume user IDs are provided as integers.

func AddUserID

func AddUserID(w http.ResponseWriter, r *http.Request, value int64) error

AddUserID adds the user ID value to the session using the user ID key and the default package level config. We assume user IDs are provided as integers.

func AddUsername

func AddUsername(w http.ResponseWriter, r *http.Request, value string) error

AddUsername adds the username value to the session using the username key and the default package level config.

func AddValue

func AddValue(w http.ResponseWriter, r *http.Request, key, value string) (err error)

AddValue adds a key-value pair to a session using the default package level config.

func CookieName

func CookieName(cookieName string)

CookieName sets the CookieName field on the package level config.

func DefaultConfig

func DefaultConfig()

DefaultConfig initializes the package level config with some defaults set. This wraps NewConfig() and saves the config to the package.

func Destroy

func Destroy(w http.ResponseWriter, r *http.Request) (err error)

Destroy deletes a session using the default package level config.

func Domain

func Domain(domain string)

Domain sets the Domain field on the package level config.

func Extend

func Extend(w http.ResponseWriter, r *http.Request) (err error)

Extend handles expiration for sessions using the package level config.

func GetSession

func GetSession(r *http.Request) (*sessions.Session, error)

GetSession returns the session using the default package level config.

func GetSessionID

func GetSessionID(r *http.Request) (value int64, err error)

GetSessionID looks up the sessionID key from the session using the default package level confing.

func GetToken

func GetToken(r *http.Request) (value string, err error)

GetToken looks up the token key from the session using the default package level confing.

func GetUserID

func GetUserID(r *http.Request) (value int64, err error)

GetUserID looks up the userID key from the session using the default package level confing.

func GetUsername

func GetUsername(r *http.Request) (value string, err error)

GetUsername looks up the username key from the session using the default package level config.

func GetValue

func GetValue(r *http.Request, key string) (value string, err error)

GetValue retrieves a value for a key in the session using the default package level config.

func HTTPOnly

func HTTPOnly(yes bool)

HTTPOnly sets the HTTPOnly field on the package level config.

func Init

func Init() (err error)

Init initializes the session using the defaul package level config.

func Keys

func Keys(authKey, encryptkey string)

Keys sets the AuthKey and EncryptKey fields on the package level config.

func MaxAge

func MaxAge(maxAge time.Duration)

MaxAge sets the MaxAge field on the package level config.

func Path

func Path(path string)

Path sets the Path field on the package level config.

func SameSite

func SameSite(sameSite http.SameSite)

SameSite sets the SameSite field on the package level config.

func Secure

func Secure(yes bool)

Secure sets the Secure field on the package level config.

Types

type Config

type Config struct {
	//Domain is the domain to serve the cookie under. The default is ".".
	Domain string

	//Path is the path off the domain to serve the cookie under. The default is "/"
	//so that the cookie is served on any path for the domain.
	Path string

	//MaxAge is the time until the session cookie will expire.
	MaxAge time.Duration

	//HTTPOnly stops client side scripts form having access to the cookie. The default
	//value is true. There really is not need for client side scripts to access the cookie
	//since it will be encrypted anyway.
	HTTPOnly bool

	//Secure sets the cookie that stores the session data to only be served over HTTPS.
	//The default value is false since we want to support HTTP requests as well.
	Secure bool

	//SameSite sets the SameSite value for the cookie to reduce leaking information during
	//requests. This is a privacy setting. The default is http.SameSiteStrictMode.
	SameSite http.SameSite

	//CookieName is the name of the cookie used for storing session data. The default is
	//"session_cookie".
	CookieName string

	//AuthKey is a 64 character long string used for authenticating the cookie stored value.
	//If this is not provided, a random value is assigned upon app start up.
	AuthKey string

	//EncryptKey is a 32 character long string used for encrypting the cookie stored value. If
	//this is not provided, a random value is assigned upon app start up. This makes the cookie
	//stored value unusable by anthing (i.e: client side scripts) other than your app.
	EncryptKey string
	// contains filtered or unexported fields
}

Config is the set of configuration settings for working with templates.

func GetConfig

func GetConfig() (c *Config)

GetConfig returns the current state of the package level config.

func NewConfig

func NewConfig() *Config

NewConfig returns a config for managing your session setup with some defaults set.

func (*Config) AddSessionID

func (c *Config) AddSessionID(w http.ResponseWriter, r *http.Request, value int64) error

AddSessionID adds the session ID value to the session using the session ID key. We assume session IDs are provided as integers.

func (*Config) AddToken

func (c *Config) AddToken(w http.ResponseWriter, r *http.Request, value string) error

AddToken adds the token value to the session using the token key. We assume user IDs are provided as integers.

func (*Config) AddUserID

func (c *Config) AddUserID(w http.ResponseWriter, r *http.Request, value int64) error

AddUserID adds the user ID value to the session using the user ID key. We assume user IDs are provided as integers.

func (*Config) AddUsername

func (c *Config) AddUsername(w http.ResponseWriter, r *http.Request, value string) error

AddUsername adds the username value to the session using the username key.

func (*Config) AddValue

func (c *Config) AddValue(w http.ResponseWriter, r *http.Request, key, value string) (err error)

AddValue adds a key-value pair to a session.

func (*Config) Destroy

func (c *Config) Destroy(w http.ResponseWriter, r *http.Request) (err error)

Destroy delete a session for a request. This is typically used when you log a user out.

func (*Config) Extend

func (c *Config) Extend(w http.ResponseWriter, r *http.Request) (err error)

Extend extends the expiration of a session and cookie. This is typically used for keeping a used logged in by reseting the expiration each time a user visits a page.

func (*Config) GetAllValues

func (c *Config) GetAllValues(r *http.Request) (kv map[string]string, err error)

GetAllValues retrieves all key value pairs stored in the session.

func (*Config) GetSession

func (c *Config) GetSession(r *http.Request) (*sessions.Session, error)

GetSession returns an existing session for a request or a new session if none existed. The field IsNew of the returned sessions.Session will be true if session was just created.

func (*Config) GetSessionID

func (c *Config) GetSessionID(r *http.Request) (value int64, err error)

GetSessionID looks up the sessionID key from the session. We assume session IDs are integers and try to convert the value stored in the session accordingly.

func (*Config) GetToken

func (c *Config) GetToken(r *http.Request) (value string, err error)

GetToken looks up the token key from the session.

func (*Config) GetUserID

func (c *Config) GetUserID(r *http.Request) (value int64, err error)

GetUserID looks up the userID key from the session. We assume user IDs are integers and try to convert the value stored in the session accordingly.

func (*Config) GetUsername

func (c *Config) GetUsername(r *http.Request) (value string, err error)

GetUsername looks up the username key from the session.

func (*Config) GetValue

func (c *Config) GetValue(r *http.Request, key string) (value string, err error)

GetValue retrieves the value stored for a key in the session.

func (*Config) Init

func (c *Config) Init() (err error)

Init initializes the session store for the given config.

Jump to

Keyboard shortcuts

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