From 5b4251fd39c43e4cfed27e032a4efb2bbba28e38 Mon Sep 17 00:00:00 2001 From: sanine Date: Sun, 14 May 2023 20:12:06 -0500 Subject: add auth & pages --- login.go | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 login.go (limited to 'login.go') diff --git a/login.go b/login.go new file mode 100644 index 0000000..d8db817 --- /dev/null +++ b/login.go @@ -0,0 +1,98 @@ +package main + +import ( + "strings" + "net/http" + "sanine.net/git/phlox/page" + "sanine.net/git/phlox/config" + "sanine.net/git/phlox/auth" + log "github.com/sirupsen/logrus" +) + + +func Login( + w http.ResponseWriter, + r *http.Request, + users map[string]config.User, + s *auth.Sessions, + pages page.Pages, +) { + if r.Method == "POST" { + LoginPostHandler(w, r, users, s, pages) + } else { + LoginGetHandler(w, r, s, pages) + } +} + + +func Logout( + w http.ResponseWriter, + r *http.Request, + s *auth.Sessions, +) { + if authenticateRequest(r, s) { + cookie, _ := r.Cookie("phlox-session") + s.DeleteSession(cookie.Value) + } + + w.Header().Add("Location", "/phlox/login") + w.WriteHeader(http.StatusTemporaryRedirect) +} + + +func LoginPostHandler( + w http.ResponseWriter, + r *http.Request, + users map[string]config.User, + s *auth.Sessions, + pages page.Pages, +) { + loggedIn := authenticateRequest(r, s) + if loggedIn { + pages.ServeLoggedIn(w) + return + } + + r.ParseForm() + username := r.Form.Get("username") + password := strings.TrimSpace(r.Form.Get("password")) + + user, ok := users[username] + if !ok { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("bad username or password")) + } + + ok = auth.AuthenticateUser(user, password) + if !ok { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("bad username or password")) + } + + session, err := s.NewSession() + if err != nil { + pages.ServeError500(w) + log.Error(err) + } + + http.SetCookie(w, &http.Cookie{ + Name: "phlox-session", + Value: session, + SameSite: http.SameSiteLaxMode, + }) + pages.ServeLoggedIn(w) +} + + +func LoginGetHandler( + w http.ResponseWriter, + r *http.Request, + s *auth.Sessions, + pages page.Pages, +) { + if authenticateRequest(r, s) { + pages.ServeLoggedIn(w) + } else { + pages.ServeLogin(w) + } +} -- cgit v1.2.1