diff --git a/http/handler/private.go b/http/handler/private.go new file mode 100644 index 0000000..aa11f33 --- /dev/null +++ b/http/handler/private.go @@ -0,0 +1,20 @@ +package handler + +import ( + "net/http" + + "github.com/Teajey/rsvp" + + lishwist "lishwist/core" + "lishwist/http/session" +) + +type Private interface { + ServeHTTP(*lishwist.Session, *session.Session, http.Header, *http.Request) rsvp.Response +} + +type PrivateFunc func(*lishwist.Session, *session.Session, http.Header, *http.Request) rsvp.Response + +func (f PrivateFunc) ServeHTTP(app *lishwist.Session, s *session.Session, h http.Header, r *http.Request) rsvp.Response { + return f(app, s, h, r) +} diff --git a/http/middleware/prefix.go b/http/middleware/prefix.go new file mode 100644 index 0000000..ccc7fde --- /dev/null +++ b/http/middleware/prefix.go @@ -0,0 +1,22 @@ +package middleware + +import ( + "net/http" + "strings" + + "github.com/Teajey/rsvp" +) + +func PrefixMovedPermanently(before, after string) rsvp.HandlerFunc { + return func(h http.Header, r *http.Request) rsvp.Response { + suffix := strings.TrimPrefix(r.RequestURI, before) + return rsvp.MovedPermanently(after + suffix) + } +} + +func PrefixPermanentRedirect(before, after string) rsvp.HandlerFunc { + return func(h http.Header, r *http.Request) rsvp.Response { + suffix := strings.TrimPrefix(r.RequestURI, before) + return rsvp.PermanentRedirect(after + suffix) + } +} diff --git a/http/mux/private.go b/http/mux/private.go index dce4616..5ccaa64 100644 --- a/http/mux/private.go +++ b/http/mux/private.go @@ -6,10 +6,10 @@ import ( "github.com/Teajey/rsvp" + lishwist "lishwist/core" "lishwist/http/handler" + "lishwist/http/response" "lishwist/http/session" - "lishwist/http/templates" - "lishwist/http/templates/text" ) type Private struct { @@ -17,11 +17,15 @@ type Private struct { store *session.Store } -func newPrivate(store *session.Store) *Private { +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.HtmlTemplate = templates.Template - mux.Config.TextTemplate = text.Template - return &Private{ + mux.Config = cfg + return Private{ inner: mux, store: store, } @@ -31,28 +35,54 @@ func (m *Private) ServeHTTP(w http.ResponseWriter, r *http.Request) { m.inner.ServeHTTP(w, r) } -func (m *Private) GetSession(r *http.Request) *session.Session { - innerSession, _ := m.store.Get(r, "lishwist_user") - return session.New(innerSession) +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) Handle(pattern string, handler handler.Public) { - m.inner.Std.HandleFunc(pattern, rsvp.MiddlewareBeforeWriteResponse(m.inner.Config, rsvp.MiddleHandlerFunc(func(w http.ResponseWriter, r *http.Request) rsvp.Response { - session := m.GetSession(r) +func saveWrittenSession(hnd handler.PublicFunc) func(s *session.Session, w http.ResponseWriter, r *http.Request) rsvp.Response { + return func(s *session.Session, w http.ResponseWriter, r *http.Request) rsvp.Response { + response := hnd(s, w.Header(), r) - response := handler.ServeHTTP(session, w.Header(), r) - - if session.WasWritten() { - err := session.Save(r, w) + if s.WasWritten() { + err := s.Save(r, w) if err != nil { log.Printf("Failed to save session: %s\n", err) } } return response + } +} + +func (m *Private) handleWithSession(pattern string, hnd handler.PublicFunc) { + m.inner.Std.HandleFunc(pattern, rsvp.MiddlewareBeforeWriteResponse(m.inner.Config, rsvp.MiddleHandlerFunc(func(w http.ResponseWriter, r *http.Request) rsvp.Response { + s := m.GetSession(r) + return saveWrittenSession(hnd)(s, w, r) }))) } -func (m *Private) HandleFunc(pattern string, handler handler.PublicFunc) { +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) } diff --git a/http/mux/public.go b/http/mux/public.go new file mode 100644 index 0000000..17f0cd9 --- /dev/null +++ b/http/mux/public.go @@ -0,0 +1,26 @@ +package mux + +import ( + "lishwist/http/handler" + "lishwist/http/session" + + "github.com/Teajey/rsvp" +) + +type Public struct { + Private +} + +func newPublic(store *session.Store, cfg *rsvp.Config) Public { + return Public{ + newPrivate(store, cfg), + } +} + +func (m *Public) Handle(pattern string, handler handler.Public) { + m.handleWithSession(pattern, handler.ServeHTTP) +} + +func (m *Public) HandleFunc(pattern string, handler handler.PublicFunc) { + m.Handle(pattern, handler) +} diff --git a/http/mux/serve.go b/http/mux/serve.go index bcaf9ea..18ec428 100644 --- a/http/mux/serve.go +++ b/http/mux/serve.go @@ -3,36 +3,72 @@ package mux import ( "net/http" - "lishwist/http/handler" + "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 - Public *Private - Private *Private + rsvpCfg rsvp.Config + Public Public + Private Private } -func (s *Serve) ServeHTTP(w http.ResponseWriter, r *http.Request) { - session, _ := s.store.Get(r, "lishwist_user") - _, inSession := session.Values["sessionKey"] +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 { - s.Private.ServeHTTP(w, r) - } else { - s.Public.ServeHTTP(w, r) + 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 := saveWrittenSession(func(s *session.Session, h http.Header, r *http.Request) rsvp.Response { + return routing.LoginWithCreds(username, password, s, h, r) + }) + + return sessionWriter(s, w, r) + })) + + handler(w, r) } func New(store *session.Store) *Serve { - return &Serve{ + cfg := *rsvp.DefaultConfig() + cfg.HtmlTemplate = templates.Template + cfg.TextTemplate = text.Template + sv := Serve{ store: store, - Public: newPrivate(store), - Private: newPrivate(store), + rsvpCfg: cfg, + Public: newPublic(store, &cfg), + Private: newPrivate(store, &cfg), } + return &sv } -func (r *Serve) HandleFunc(pattern string, handler handler.PublicFunc) { - r.Public.HandleFunc(pattern, handler) - r.Private.HandleFunc(pattern, handler) +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) + }) } diff --git a/http/routing/context.go b/http/routing/context.go index e410ddd..4fb0f0c 100644 --- a/http/routing/context.go +++ b/http/routing/context.go @@ -1,35 +1 @@ package routing - -import ( - "log" - "net/http" - - "github.com/Teajey/rsvp" - - lishwist "lishwist/core" - "lishwist/http/handler" - "lishwist/http/response" - "lishwist/http/session" -) - -func ExpectAppSession(next func(*lishwist.Session, *session.Session, http.Header, *http.Request) rsvp.Response) handler.PublicFunc { - return func(session *session.Session, h http.Header, r *http.Request) rsvp.Response { - sessionKey, ok := session.GetValue("sessionKey").(string) - 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(appSession, session, h, r) - } -} diff --git a/http/routing/login.go b/http/routing/login.go index e50e10a..e5aced8 100644 --- a/http/routing/login.go +++ b/http/routing/login.go @@ -36,17 +36,18 @@ func Login(s *session.Session, h http.Header, r *http.Request) rsvp.Response { } func LoginPost(session *session.Session, h http.Header, r *http.Request) rsvp.Response { - username, password, ok := r.BasicAuth() - if !ok { - err := r.ParseForm() - if err != nil { - return response.Error(http.StatusBadRequest, "Failed to parse form") - } - - username = r.Form.Get("username") - password = r.Form.Get("password") + err := r.ParseForm() + if err != nil { + return response.Error(http.StatusBadRequest, "Failed to parse form") } + username := r.Form.Get("username") + password := r.Form.Get("password") + + return LoginWithCreds(username, password, session, h, r) +} + +func LoginWithCreds(username, password string, session *session.Session, h http.Header, r *http.Request) rsvp.Response { login := props.NewLogin(username, password) resp := rsvp.SeeOther(r.URL.Path, login) diff --git a/http/routing/logout.go b/http/routing/logout.go index 5a35440..16f92df 100644 --- a/http/routing/logout.go +++ b/http/routing/logout.go @@ -1,15 +1,16 @@ package routing import ( + lishwist "lishwist/core" "lishwist/http/session" "net/http" "github.com/Teajey/rsvp" ) -func LogoutPost(session *session.Session, h http.Header, r *http.Request) rsvp.Response { - session.Options().MaxAge = 0 - session.ClearValues() +func LogoutPost(app *lishwist.Session, s *session.Session, h http.Header, r *http.Request) rsvp.Response { + s.Options().MaxAge = 0 + s.ClearValues() return rsvp.SeeOther("/", "Logout successful") } diff --git a/http/routing/not_found.go b/http/routing/not_found.go index 875cf38..c9a1f75 100644 --- a/http/routing/not_found.go +++ b/http/routing/not_found.go @@ -3,12 +3,13 @@ package routing import ( "net/http" + lishwist "lishwist/core" "lishwist/http/response" "lishwist/http/session" "github.com/Teajey/rsvp" ) -func NotFound(s *session.Session, h http.Header, r *http.Request) rsvp.Response { +func NotFound(app *lishwist.Session, s *session.Session, h http.Header, r *http.Request) rsvp.Response { return response.Error(http.StatusNotFound, "Page not found") } diff --git a/http/server/server.go b/http/server/server.go index 73d188a..b0cf247 100644 --- a/http/server/server.go +++ b/http/server/server.go @@ -3,32 +3,15 @@ package server import ( "encoding/gob" "net/http" - "strings" - - "github.com/Teajey/rsvp" "lishwist/http/env" - "lishwist/http/handler" + "lishwist/http/middleware" "lishwist/http/mux" "lishwist/http/props" "lishwist/http/routing" "lishwist/http/session" ) -func prefixMovedPermanently(before, after string) handler.PublicFunc { - return func(s *session.Session, h http.Header, r *http.Request) rsvp.Response { - suffix := strings.TrimPrefix(r.RequestURI, before) - return rsvp.MovedPermanently(after + suffix) - } -} - -func prefixPermanentRedirect(before, after string) handler.PublicFunc { - return func(s *session.Session, h http.Header, r *http.Request) rsvp.Response { - suffix := strings.TrimPrefix(r.RequestURI, before) - return rsvp.PermanentRedirect(after + suffix) - } -} - func Create(useSecureCookies bool) *mux.Serve { gob.Register(&props.Register{}) gob.Register(&props.Login{}) @@ -50,28 +33,28 @@ func Create(useSecureCookies bool) *mux.Serve { r.Public.HandleFunc("POST /", routing.LoginPost) r.Public.HandleFunc("POST /register", routing.RegisterPost) - r.Private.HandleFunc("GET /events", routing.ExpectAppSession(routing.EventList)) - r.Private.HandleFunc("GET /account", routing.ExpectAppSession(routing.Account)) - r.Private.HandleFunc("GET /health", routing.ExpectAppSession(routing.Health)) + r.Private.HandleFunc("GET /events", routing.EventList) + r.Private.HandleFunc("GET /account", routing.Account) + r.Private.HandleFunc("GET /health", routing.Health) r.Private.HandleFunc("GET /", routing.NotFound) - r.Private.HandleFunc("GET /groups", routing.ExpectAppSession(routing.Groups)) - r.Private.HandleFunc("GET /groups/{groupReference}", routing.ExpectAppSession(routing.Group)) - r.Private.HandleFunc("GET /lists/{userReference}", routing.ExpectAppSession(routing.ForeignWishlist)) - r.Private.HandleFunc("GET /users", routing.ExpectAppSession(routing.Users)) - r.Private.HandleFunc("GET /users/{userReference}", routing.ExpectAppSession(routing.User)) - r.Private.HandleFunc("GET /{$}", routing.ExpectAppSession(routing.Home)) - r.Private.HandleFunc("POST /account", routing.ExpectAppSession(routing.AccountPost)) - r.Private.HandleFunc("POST /groups/{groupReference}", routing.ExpectAppSession(routing.GroupPost)) - r.Private.HandleFunc("POST /lists/{userReference}", routing.ExpectAppSession(routing.ForeignWishlistPost)) + r.Private.HandleFunc("GET /groups", routing.Groups) + r.Private.HandleFunc("GET /groups/{groupReference}", routing.Group) + r.Private.HandleFunc("GET /lists/{userReference}", routing.ForeignWishlist) + r.Private.HandleFunc("GET /users", routing.Users) + r.Private.HandleFunc("GET /users/{userReference}", routing.User) + r.Private.HandleFunc("GET /{$}", routing.Home) + r.Private.HandleFunc("POST /account", routing.AccountPost) + r.Private.HandleFunc("POST /groups/{groupReference}", routing.GroupPost) + r.Private.HandleFunc("POST /lists/{userReference}", routing.ForeignWishlistPost) r.Private.HandleFunc("POST /logout", routing.LogoutPost) - r.Private.HandleFunc("POST /users/{userReference}", routing.ExpectAppSession(routing.UserPost)) - r.Private.HandleFunc("POST /{$}", routing.ExpectAppSession(routing.HomePost)) + r.Private.HandleFunc("POST /users/{userReference}", routing.UserPost) + r.Private.HandleFunc("POST /{$}", routing.HomePost) // Deprecated - r.HandleFunc("GET /group/{groupReference}", prefixMovedPermanently("/group/", "/groups/")) - r.HandleFunc("GET /list/{groupReference}", prefixMovedPermanently("/list/", "/lists/")) - r.HandleFunc("POST /group/{groupReference}", prefixPermanentRedirect("/group/", "/groups/")) - r.HandleFunc("POST /list/{groupReference}", prefixPermanentRedirect("/list/", "/lists/")) + r.HandleFunc("GET /group/{groupReference}", middleware.PrefixMovedPermanently("/group/", "/groups/")) + r.HandleFunc("GET /list/{groupReference}", middleware.PrefixMovedPermanently("/list/", "/lists/")) + r.HandleFunc("POST /group/{groupReference}", middleware.PrefixPermanentRedirect("/group/", "/groups/")) + r.HandleFunc("POST /list/{groupReference}", middleware.PrefixPermanentRedirect("/list/", "/lists/")) return r } diff --git a/http/session/session.go b/http/session/session.go index d1f69e3..28c9984 100644 --- a/http/session/session.go +++ b/http/session/session.go @@ -55,8 +55,18 @@ func (s *Session) RemoveValue(key any) { s.written = true } -func (s *Session) GetValue(key any) any { - return s.inner.Values[key] +func (s *Session) GetValue(key any) (any, bool) { + val, ok := s.inner.Values[key] + return val, ok +} + +func (s *Session) GetString(key any) (string, bool) { + val, ok := s.GetValue(key) + if !ok { + return "", false + } + str, ok := val.(string) + return str, ok } func (s *Session) ClearValues() {