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-mysql
Usage ¶
To get a store you just need a sql.DB struct or a dsn string, you need to specify the TableName, that is the name of the table where your sessions will be saved in the database. You can put even a TableName 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
mysqlStore, err := mysqlstore.NewMysqlStore(db, "TableName",
[]mysqlstore.KeyPair{{AuthenticationKey: []byte(os.Getenv("SESSION_AUTH_KEY")), EncryptionKey: []byte(os.Getenv("SESSION_ENC_KEY"))}}
)
if err != nil {
panic(fmt.Sprintf("Failed to get a mysqlstore: %s", err.Error()))
}
Then you can use the store in a handle like this:
func myHandler(w http.ResponseWriter, r *http.Request) {
session, err := mysqlStore.Get(r, "CookieName") // Get a session
if err != nil {
if !(errors.Is(err, mysqlstore.ErrSessionExpired) || errors.Is(err, mysqlstore.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
// Save it before we write to the response/return from the handler.
err := mysqlStore.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 MysqlStoreOption WithCleanupInterval():
mysqlStore, err := mysqlstore.NewMysqlStore(db, "TableName",
[]mysqlstore.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 MysqlStoreOption, refer to the documentation to see how they change the behavior of the store.
Index ¶
- Variables
- type KeyPair
- type MySqlStoreError
- type MysqlStore
- func (store *MysqlStore) Close()
- func (store *MysqlStore) Delete(r *http.Request, w http.ResponseWriter, session *sessions.Session)
- func (store *MysqlStore) Get(r *http.Request, name string) (*sessions.Session, error)
- func (store *MysqlStore) New(r *http.Request, name string) (*sessions.Session, error)
- func (store *MysqlStore) Save(r *http.Request, w http.ResponseWriter, s *sessions.Session) error
- func (store *MysqlStore) SetMaxAge(maxAge int)
- type MysqlStoreOption
- func WithCleanupInterval(interval time.Duration) MysqlStoreOption
- func WithDomain(domain string) MysqlStoreOption
- func WithHttpOnly(httpOnly bool) MysqlStoreOption
- func WithMaxAge(maxAge int) MysqlStoreOption
- func WithPartitioned(isPartitioned bool) MysqlStoreOption
- func WithPath(path string) MysqlStoreOption
- func WithSameSite(sameSite http.SameSite) MysqlStoreOption
- func WithSecure(secure bool) MysqlStoreOption
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.") ErrFailedToEncodeCookie = errors.New("Failed to encode the cookie.") 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.") ErrFailedToPrepareStmt = errors.New("There was an error while trying to parse the sql prepared statement.") ErrFailedToUpdateSession = errors.New("Failed to update a sessionData in the database.") ErrLoadingSessionDataFromDb = errors.New("Failed to load session data from the database.") ErrNoParseTimeParameter = errors.New("You need the parseTime=true parameter in the DSN string.") 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 MySqlStoreError ¶
type MySqlStoreError struct {
// contains filtered or unexported fields
}
MySqlStoreError provides a custom wrapper for encapsulating the function name with a error
func (MySqlStoreError) Error ¶
func (e MySqlStoreError) Error() string
Error Implement the Error interface, it return a string like this:
funcName: errorMessage
func (MySqlStoreError) Unwrap ¶
func (e MySqlStoreError) Unwrap() error
Implement the Unwrap interface Unwrap implement the Unwrap interface, used to unwrape error after a errors.Join
type MysqlStore ¶
type MysqlStore struct {
Codecs []securecookie.Codec
Options *sessions.Options // default configuration
// contains filtered or unexported fields
}
MysqlStore provides session data from a mysql database
func NewMysqlStore ¶
func NewMysqlStore(db *sql.DB, tableName string, keys []KeyPair, opts ...MysqlStoreOption) (*MysqlStore, error)
NewMysqlStore creates a new MysqlStore that can be used to retrieve and save user sessions from a database. IMPORTANT: When passing the database connection make sure to have the option parseTime set to true, otherwise you may have problems.
func NewMysqlStoreFromDsn ¶
func NewMysqlStoreFromDsn(dsn string, tableName string, keys []KeyPair, opts ...MysqlStoreOption) (*MysqlStore, error)
NewMysqlStoreFromDsn creates a new MysqlStore that can be used to retrieve and save user sessions from a database, it uses a dsn string to create a connection to the database. IMPORTANT: The dsn string should contain the parameter parseTime=true otherwise you may have problems.
func (*MysqlStore) Close ¶
func (store *MysqlStore) Close()
Close stop the cleanup goroutine and closes the database connection
func (*MysqlStore) Delete ¶
func (store *MysqlStore) 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 (*MysqlStore) 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 (*MysqlStore) 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 (*MysqlStore) Save ¶
func (store *MysqlStore) Save(r *http.Request, w http.ResponseWriter, s *sessions.Session) error
Save stores the session data in the database
func (*MysqlStore) SetMaxAge ¶ added in v0.1.3
func (store *MysqlStore) SetMaxAge(maxAge int)
SetMaxAge sets the maxAge parameter for the cookie
type MysqlStoreOption ¶
type MysqlStoreOption func(*MysqlStore)
A list of MysqlStoreOption can be used when creating a MysqlStore when using NewMysqlStore or NewMysqlStoreFromDsn
func WithCleanupInterval ¶
func WithCleanupInterval(interval time.Duration) MysqlStoreOption
WithCleanupInterval returns a MysqlStoreOption 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) MysqlStoreOption
WithDomain returns a MysqlStoreOption 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) MysqlStoreOption
WithHttpOnly returns a MysqlStoreOption 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) MysqlStoreOption
WithMaxAge returns a MysqlStoreOption 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 ¶ added in v0.1.4
func WithPartitioned(isPartitioned bool) MysqlStoreOption
WithPartitioned returns a MysqlStoreOption that allows to enable or disable the the Partitioned attribute in a cookie
func WithPath ¶
func WithPath(path string) MysqlStoreOption
WithPath returns a MysqlStoreOption 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) MysqlStoreOption
WithSameSite returns a MysqlStoreOption 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) MysqlStoreOption
WithSecure returns a MysqlStoreOption that allows to change the secure parameter of the session cookie that is provided by default when creating a new session