package mux import ( "net/http" "github.com/Teajey/rsvp" lishwist "lishwist/core" "lishwist/http/routing" "lishwist/http/session" "lishwist/http/templates" "lishwist/http/templates/text" ) type Serve struct { store *session.Store rsvpCfg rsvp.Config Public Public Private Private } func (m *Serve) GetSession(r *http.Request) *session.Session { innerSession, _ := m.store.Get(r, "lishwist_user") return session.New(innerSession) } func (m *Serve) ServeHTTP(w http.ResponseWriter, r *http.Request) { innerSession, _ := m.store.Get(r, "lishwist_user") s := session.New(innerSession) _, inSession := s.GetString("sessionKey") if inSession { m.Private.ServeHTTP(w, r) return } username, password, ok := r.BasicAuth() if !ok { m.Public.ServeHTTP(w, r) return } handler := rsvp.MiddlewareBeforeWriteResponse(&m.rsvpCfg, rsvp.MiddleHandlerFunc(func(w http.ResponseWriter, r *http.Request) rsvp.Response { sessionWriter := s.SaveIfWrittenMiddleware(func(s *session.Session, h http.Header, r *http.Request) rsvp.Response { return routing.LoginWithCreds(username, password, s, h, r) }) return sessionWriter(w, r) })) handler(w, r) } func New(store *session.Store) *Serve { cfg := *rsvp.DefaultConfig() cfg.HtmlTemplate = templates.Template cfg.TextTemplate = text.Template sv := Serve{ store: store, rsvpCfg: cfg, Public: newPublic(store, &cfg), Private: newPrivate(store, &cfg), } return &sv } func (m *Serve) HandleFunc(pattern string, hnd rsvp.HandlerFunc) { m.Public.HandleFunc(pattern, func(s *session.Session, h http.Header, r *http.Request) rsvp.Response { return hnd(h, r) }) m.Private.HandleFunc(pattern, func(app *lishwist.Session, s *session.Session, h http.Header, r *http.Request) rsvp.Response { return hnd(h, r) }) }