2018-12-06 21:42:01 +01:00
|
|
|
package gorilla
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
|
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
// CreateCookieSessionStore creates and returns a new cookie session store
|
|
|
|
// with random authentication and encryption keys
|
2019-05-13 09:09:28 +02:00
|
|
|
func CreateCookieSessionStore(authKeySize, encryptKeySize int, defaultOptions *sessions.Options) (sessions.Store, error) {
|
2020-02-12 22:06:16 +01:00
|
|
|
authenticationKey, err := GenerateRandomBytes(authKeySize)
|
2018-12-06 21:42:01 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "error while generating cookie authentication key")
|
|
|
|
}
|
2020-02-12 22:06:16 +01:00
|
|
|
|
|
|
|
encryptionKey, err := GenerateRandomBytes(encryptKeySize)
|
2018-12-06 21:42:01 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "error while generating cookie encryption key")
|
|
|
|
}
|
2020-02-12 22:06:16 +01:00
|
|
|
|
2018-12-06 21:42:01 +01:00
|
|
|
store := sessions.NewCookieStore(authenticationKey, encryptionKey)
|
2019-05-13 09:09:28 +02:00
|
|
|
store.Options = defaultOptions
|
2020-02-12 22:06:16 +01:00
|
|
|
|
2018-12-06 21:42:01 +01:00
|
|
|
return store, nil
|
|
|
|
}
|
|
|
|
|
2020-02-12 22:06:16 +01:00
|
|
|
func GenerateRandomBytes(n int) ([]byte, error) {
|
2018-12-06 21:42:01 +01:00
|
|
|
b := make([]byte, n)
|
|
|
|
_, err := rand.Read(b)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return b, nil
|
|
|
|
}
|