Documentation
¶
Overview ¶
Package mysqlstore provides a store implementation for gorilla/sessions that store data in a mysql database
Installation ¶
You can install this package by running:
go get github.com/danielepintore/gorilla-sessions-postgres
Usage ¶
To get a store you just need a pgxpool.Pool struct or a connection string, you need to specify the table_name, that is the name of the table where your sessions will be saved in the database. You can put even a table_name that doesn't exist, the table will be created. Then you need to pass a list of KeyPair, the requirements for a KeyPair are the one specified by the gorilla/sessions package.
// This provides a store with the default settings for a session
// For more customization look futher examples
pg_store, err := postgresstore.NewPostgresStore(db, "table_name",
[]postgresstore.KeyPair{{AuthenticationKey: []byte(os.Getenv("SESSION_AUTH_KEY")), EncryptionKey: []byte(os.Getenv("SESSION_ENC_KEY"))}}
)
if err != nil {
panic(fmt.Sprintf("Failed to get PostgresStore: %s", err.Error()))
}
Then you can use the store in a handle like this:
func myHandler(w http.ResponseWriter, r *http.Request) {
session, err := pg_store.Get(r, "CookieName") // Get a session
if err != nil {
if !(errors.Is(err, postgresstore.ErrSessionExpired) || errors.Is(err, postgresstore.ErrNoSessionSaved)) {
// Handle errors here, remember that the Get() method will always return a session, even when
// there is a error, for example here we get in this if we'll have a new session
return
}
}
// do things with the session data
// session.Values["sessionData"] = MyData // Uses gob for encoding
// Save it before we write to the response/return from the handler.
err := pg_store.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
This package provides also a cleanup option to delete expired sessions from the database, to use this feature, while creating the store just pass the PgStoreOption WithCleanupInterval():
pg_store, err := postgresstore.NewPostgresStore(db, "table_name",
[]postgresstore.KeyPair{{AuthenticationKey: []byte(os.Getenv("SESSION_AUTH_KEY")), EncryptionKey: []byte(os.Getenv("SESSION_ENC_KEY"))}},
WithCleanupInterval(time.Minute * 15)
)
Now every 15 minutes the package will perform a check and will delete all expired sessions. There are other PgStoreOption, refer to the documentation to see how they change the behavior of the store.
Index ¶
- Variables
- type KeyPair
- type PgStoreOption
- func WithCleanupInterval(interval time.Duration) PgStoreOption
- func WithDomain(domain string) PgStoreOption
- func WithHttpOnly(httpOnly bool) PgStoreOption
- func WithMaxAge(maxAge int) PgStoreOption
- func WithPartitioned(isPartitioned bool) PgStoreOption
- func WithPath(path string) PgStoreOption
- func WithSameSite(sameSite http.SameSite) PgStoreOption
- func WithSecure(secure bool) PgStoreOption
- type PostgresStore
- func (store *PostgresStore) Close()
- func (store *PostgresStore) Delete(r *http.Request, w http.ResponseWriter, session *sessions.Session)
- func (store *PostgresStore) Get(r *http.Request, name string) (*sessions.Session, error)
- func (store *PostgresStore) New(r *http.Request, name string) (*sessions.Session, error)
- func (store *PostgresStore) Save(r *http.Request, w http.ResponseWriter, s *sessions.Session) error
- func (store *PostgresStore) SetMaxAge(maxAge int)
Constants ¶
This section is empty.
Variables ¶
var ( ErrAddingSessionTable = errors.New("There was an error while trying to add the session table to the database.") ErrDbConnectionIsNil = errors.New("The connection struct is nil!") ErrDbOpenConnection = errors.New("There was an error while opening the database connection!") ErrDbPing = errors.New("There was an error while pinging the database!") ErrFailedToDecodeCookie = errors.New("Failed to decode the cookie.") ErrFailedToDecodeSessionData = errors.New("Failed to decode session data from the database.") ErrFailedToDeleteExpiredSessions = errors.New("There was an error while trying to delete expired users sessions.") ErrFailedToDeleteSession = errors.New("Failed to delete a session.") ErrFailedToEncodeSessionData = errors.New("Failed to encode session data.") ErrFailedToInsertSession = errors.New("Failed to insert a session in the database.") ErrFailedToLoadSession = errors.New("Failed to load session.") ErrFailedToUpdateSession = errors.New("Failed to update a sessionData in the database.") ErrLoadingSessionDataFromDb = errors.New("Failed to load session data from the database.") ErrDbInvalidUrl = errors.New("You have provided an invalid database url, please check it.") ErrNoSessionSaved = errors.New("There isn't a sessions for that Id in the database.") ErrSessionExpired = errors.New("The session is expired.") )
Error definitions.
This is a list of errors that can be returned by the store.
Functions ¶
This section is empty.
Types ¶
type KeyPair ¶
A KeyPair rappresent two keys, an AuthenticationKey used for signing and a optional (can be nil) EncryptionKey for encryption
type PgStoreOption ¶
type PgStoreOption func(*PostgresStore)
A list of PgStoreOption can be used when creating a PostgresStore when using NewPostgresStore or NewPgStoreFromUrl
func WithCleanupInterval ¶
func WithCleanupInterval(interval time.Duration) PgStoreOption
WithCleanupInterval returns a PgStoreOption that allows to enable and set the cleanup interval, the cleanup interval is the time between each scan to remove exipired sessions from the database
func WithDomain ¶
func WithDomain(domain string) PgStoreOption
WithDomain returns a PgStoreOption that allows to change the domain parameter of the session cookie that is provided by default when creating a new session
func WithHttpOnly ¶
func WithHttpOnly(httpOnly bool) PgStoreOption
WithHttpOnly returns a PgStoreOption that allows to change the httpOnly parameter of the session cookie that is provided by default when creating a new session
func WithMaxAge ¶
func WithMaxAge(maxAge int) PgStoreOption
WithMaxAge returns a PgStoreOption that allows to change the maxAge parameter of the session cookie that is provided by default when creating a new session MaxAge=0 means no Max-Age attribute specified and the cookie will be deleted after the browser session ends. MaxAge<0 means delete cookie immediately. MaxAge>0 means Max-Age attribute present and given in seconds.
func WithPartitioned ¶
func WithPartitioned(isPartitioned bool) PgStoreOption
WithPartitioned returns a PgStoreOption that allows to enable or disable the the Partitioned attribute in a cookie
func WithPath ¶
func WithPath(path string) PgStoreOption
WithPath returns a PgStoreOption that allows to change the path parameter of the session cookie that is provided by default when creating a new session
func WithSameSite ¶
func WithSameSite(sameSite http.SameSite) PgStoreOption
WithSameSite returns a PgStoreOption that allows to change the sameSite parameter of the session cookie that is provided by default when creating a new session
func WithSecure ¶
func WithSecure(secure bool) PgStoreOption
WithSecure returns a PgStoreOption that allows to change the secure parameter of the session cookie that is provided by default when creating a new session
type PostgresStore ¶
type PostgresStore struct {
Codecs []securecookie.Codec
Options *sessions.Options // default configuration
// contains filtered or unexported fields
}
PostgresStore provides session data from a postgres database
func NewPgStoreFromUrl ¶
func NewPgStoreFromUrl(url string, tableName string, keys []KeyPair, opts ...PgStoreOption) (*PostgresStore, error)
NewPgStoreFromUrl creates a new PostgresStore that can be used to retrieve and save user sessions from a database, it uses the db url string to create a connection.
func NewPostgresStore ¶
func NewPostgresStore(db *pgxpool.Pool, tableName string, keys []KeyPair, opts ...PgStoreOption) (*PostgresStore, error)
NewPostgresStore creates a new PostgresStore that can be used to retrieve and save user sessions from a database.
func (*PostgresStore) Close ¶
func (store *PostgresStore) Close()
Close stop the cleanup goroutine and closes the database connection
func (*PostgresStore) Delete ¶
func (store *PostgresStore) Delete(r *http.Request, w http.ResponseWriter, session *sessions.Session)
Delete change the session options in order that it will be deleted when calling [Save]
func (*PostgresStore) Get ¶
Get should return a cached session. Get returns a session for the given name after adding it to the registry.
It returns a new session if the sessions doesn't exist. Access IsNew on the session to check if it is an existing session or a new one.
It returns a new session and an error if the session exists but could not be decoded or is expired.
func (*PostgresStore) New ¶
New should create and return a new session.
Note that New should never return a nil session, even in the case of an error if using the Registry infrastructure to cache the session. New returns a session for the given name without adding it to the registry.
The difference between New() and Get() is that calling New() twice will decode the session data twice, while Get() registers and reuses the same decoded session after the first call
func (*PostgresStore) Save ¶
func (store *PostgresStore) Save(r *http.Request, w http.ResponseWriter, s *sessions.Session) error
Save stores the session data in the database
func (*PostgresStore) SetMaxAge ¶
func (store *PostgresStore) SetMaxAge(maxAge int)
SetMaxAge sets the maxAge parameter for the cookie