105 lines
2.5 KiB
Go
105 lines
2.5 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 *http.ServeMux
|
|
store *session.Store
|
|
rsvp rsvp.Config
|
|
}
|
|
|
|
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 := http.NewServeMux()
|
|
return Private{
|
|
inner: mux,
|
|
store: store,
|
|
rsvp: cfg,
|
|
}
|
|
}
|
|
|
|
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, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
|
|
sessionKey, ok := session.GetString("sessionKey")
|
|
if !ok {
|
|
log.Printf("Failed to get key from session\n")
|
|
return response.Error("Something went wrong.").StatusInternalServerError()
|
|
}
|
|
|
|
appSession, err := lishwist.SessionFromKey(sessionKey)
|
|
if err != nil {
|
|
log.Printf("Failed to get session by key %v: %s\n", sessionKey, err)
|
|
return response.Error("Something went wrong.").StatusInternalServerError()
|
|
}
|
|
if appSession == nil {
|
|
log.Printf("Session not found under key: %s\n", sessionKey)
|
|
return response.Error("Something went wrong.").StatusInternalServerError()
|
|
}
|
|
|
|
return next.ServeHTTP(appSession, session, w, r)
|
|
}
|
|
}
|
|
|
|
type sessionResponseWriter struct {
|
|
http.ResponseWriter
|
|
s *session.Session
|
|
r *http.Request
|
|
}
|
|
|
|
func (w sessionResponseWriter) WriteHeader(statusCode int) {
|
|
if w.s.WasWritten() {
|
|
err := w.s.Save(w.r, w)
|
|
if err != nil {
|
|
log.Printf("Failed to save session: %s", err)
|
|
}
|
|
}
|
|
|
|
w.ResponseWriter.WriteHeader(statusCode)
|
|
}
|
|
|
|
func (m *Private) handleWithSession(pattern string, next handler.PublicFunc) {
|
|
getSessionMiddleware := func(w http.ResponseWriter, r *http.Request) {
|
|
s := m.GetSession(r)
|
|
|
|
rw := sessionResponseWriter{
|
|
ResponseWriter: w,
|
|
s: s,
|
|
r: r,
|
|
}
|
|
|
|
err := rsvp.Write(rw, r, m.rsvp, rsvp.HandlerFunc(func(w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
|
|
return next(s, w, r)
|
|
}))
|
|
if err != nil {
|
|
log.Printf("rsvp failed to write a response: %s", err)
|
|
}
|
|
}
|
|
m.inner.HandleFunc(pattern, getSessionMiddleware)
|
|
}
|
|
|
|
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)
|
|
}
|