77 lines
2.1 KiB
Go
77 lines
2.1 KiB
Go
package mux
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/Teajey/rsvp"
|
|
|
|
lishwist "lishwist/core"
|
|
"lishwist/http/handler"
|
|
"lishwist/http/response"
|
|
"lishwist/http/session"
|
|
)
|
|
|
|
type Private struct {
|
|
inner *rsvp.ServeMux
|
|
store *session.Store
|
|
}
|
|
|
|
func (m *Private) GetSession(r *http.Request) *session.Session {
|
|
innerSession, _ := m.store.Get(r, "lishwist_user")
|
|
return session.New(innerSession)
|
|
}
|
|
|
|
func newPrivate(store *session.Store, cfg *rsvp.Config) Private {
|
|
mux := rsvp.NewServeMux()
|
|
mux.Config = cfg
|
|
return Private{
|
|
inner: mux,
|
|
store: store,
|
|
}
|
|
}
|
|
|
|
func (m *Private) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
m.inner.ServeHTTP(w, r)
|
|
}
|
|
|
|
func expectAppSession(next handler.Private) handler.PublicFunc {
|
|
return func(session *session.Session, h http.Header, r *http.Request) rsvp.Response {
|
|
sessionKey, ok := session.GetString("sessionKey")
|
|
if !ok {
|
|
log.Printf("Failed to get key from session\n")
|
|
return response.Error(http.StatusInternalServerError, "Something went wrong.")
|
|
}
|
|
|
|
appSession, err := lishwist.SessionFromKey(sessionKey)
|
|
if err != nil {
|
|
log.Printf("Failed to get session by key %v: %s\n", sessionKey, err)
|
|
return response.Error(http.StatusInternalServerError, "Something went wrong.")
|
|
}
|
|
if appSession == nil {
|
|
log.Printf("Session not found under key: %s\n", sessionKey)
|
|
return response.Error(http.StatusInternalServerError, "Something went wrong.")
|
|
}
|
|
|
|
return next.ServeHTTP(appSession, session, h, r)
|
|
}
|
|
}
|
|
|
|
func (m *Private) handleWithSession(pattern string, hnd handler.PublicFunc) {
|
|
getSessionMiddleware := rsvp.MiddleHandlerFunc(func(w http.ResponseWriter, r *http.Request) rsvp.Response {
|
|
s := m.GetSession(r)
|
|
saveIfWritten := s.SaveIfWrittenMiddleware(hnd)
|
|
return saveIfWritten(w, r)
|
|
})
|
|
beforeWrite := rsvp.MiddlewareBeforeWriteResponse(m.inner.Config, getSessionMiddleware)
|
|
m.inner.Std.HandleFunc(pattern, beforeWrite)
|
|
}
|
|
|
|
func (m *Private) Handle(pattern string, handler handler.Private) {
|
|
m.handleWithSession(pattern, expectAppSession(handler))
|
|
}
|
|
|
|
func (m *Private) HandleFunc(pattern string, handler handler.PrivateFunc) {
|
|
m.Handle(pattern, handler)
|
|
}
|