From afa1b65563df31161af30a78f2c4702d00acfc6d Mon Sep 17 00:00:00 2001 From: Jason Streifling Date: Sat, 28 Sep 2024 13:22:53 +0200 Subject: [PATCH] Moved getSession to frontend/sessions.go --- cmd/frontend/sessions.go | 21 +++++++++++++++++++++ cmd/frontend/verification.go | 29 ----------------------------- 2 files changed, 21 insertions(+), 29 deletions(-) delete mode 100644 cmd/frontend/verification.go diff --git a/cmd/frontend/sessions.go b/cmd/frontend/sessions.go index 3a53a28..d88e595 100644 --- a/cmd/frontend/sessions.go +++ b/cmd/frontend/sessions.go @@ -1,11 +1,13 @@ package frontend import ( + "errors" "fmt" "html/template" "log" "net/http" + "github.com/gorilla/sessions" b "streifling.com/jason/cpolis/cmd/backend" ) @@ -26,6 +28,25 @@ func saveSession(w http.ResponseWriter, r *http.Request, s *b.CookieStore, u *b. return nil } +// getSession is used for verifying that the user is logged in and returns their session and an error. +func getSession(w http.ResponseWriter, r *http.Request, c *b.Config, s *b.CookieStore) (*sessions.Session, error) { + msg := "Keine gültige Session. Bitte erneut anmelden." + tmpl, tmplErr := template.ParseFiles(c.WebDir+"/templates/index.html", c.WebDir+"/templates/login.html") + + session, err := s.Get(r, "cookie") + if err != nil { + template.Must(tmpl, tmplErr).ExecuteTemplate(w, "page-content", msg) + return nil, err + } + + if session.IsNew { + template.Must(tmpl, tmplErr).ExecuteTemplate(w, "page-content", msg) + return session, errors.New("error: no existing session") + } + + return session, nil +} + func HomePage(c *b.Config, db *b.DB, s *b.CookieStore) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { numRows, err := db.CountEntries("users") diff --git a/cmd/frontend/verification.go b/cmd/frontend/verification.go deleted file mode 100644 index 9a62da5..0000000 --- a/cmd/frontend/verification.go +++ /dev/null @@ -1,29 +0,0 @@ -package frontend - -import ( - "errors" - "html/template" - "net/http" - - "github.com/gorilla/sessions" - b "streifling.com/jason/cpolis/cmd/backend" -) - -// getSession is used for verifying that the user is logged in and returns their session and an error. -func getSession(w http.ResponseWriter, r *http.Request, c *b.Config, s *b.CookieStore) (*sessions.Session, error) { - msg := "Keine gültige Session. Bitte erneut anmelden." - tmpl, tmplErr := template.ParseFiles(c.WebDir+"/templates/index.html", c.WebDir+"/templates/login.html") - - session, err := s.Get(r, "cookie") - if err != nil { - template.Must(tmpl, tmplErr).ExecuteTemplate(w, "page-content", msg) - return nil, err - } - - if session.IsNew { - template.Must(tmpl, tmplErr).ExecuteTemplate(w, "page-content", msg) - return session, errors.New("error: no existing session") - } - - return session, nil -}