goweb/session/gorilla/service.go

53 lines
1.5 KiB
Go
Raw Normal View History

2018-12-06 15:18:05 +01:00
package gorilla
import (
"net/http"
"github.com/gorilla/securecookie"
"forge.cadoles.com/wpetit/goweb/service/session"
"github.com/gorilla/sessions"
"github.com/pkg/errors"
)
// SessionService is an implementation of service.Session
// based on the github.com/gorilla/sessions
type SessionService struct {
sessionName string
store sessions.Store
defaultOptions *sessions.Options
}
// Get returns a Session associated with the given HTTP request
func (s *SessionService) Get(w http.ResponseWriter, r *http.Request) (session.Session, error) {
sess, err := s.store.Get(r, s.sessionName)
if err != nil {
multiErr, ok := err.(securecookie.MultiError)
if !ok || multiErr.Error() != securecookie.ErrMacInvalid.Error() {
return nil, errors.Wrap(err, "error while retrieving the session from the request")
}
}
if err != nil {
defaultOptions := s.defaultOptionsCopy()
sess.Options = &defaultOptions
if err := sess.Save(r, w); err != nil {
return nil, errors.Wrap(err, "error while saving session")
}
}
return NewSession(sess), nil
}
func (s *SessionService) defaultOptionsCopy() sessions.Options {
return *s.defaultOptions
}
// NewSessionService returns a new SessionService backed
// by the given Store
func NewSessionService(sessionName string, store sessions.Store, defaultOptions *sessions.Options) *SessionService {
return &SessionService{
sessionName: sessionName,
store: store,
defaultOptions: defaultOptions,
}
}