diff options
author | sanine <sanine.not@pm.me> | 2023-05-14 20:12:06 -0500 |
---|---|---|
committer | sanine <sanine.not@pm.me> | 2023-05-14 20:12:06 -0500 |
commit | 5b4251fd39c43e4cfed27e032a4efb2bbba28e38 (patch) | |
tree | f51840d5607eba0db9262045e330a1c8b8393449 /login.go | |
parent | 9571ccc4d87907067df98edeaa78f0c167fcff43 (diff) |
add auth & pages
Diffstat (limited to 'login.go')
-rw-r--r-- | login.go | 98 |
1 files changed, 98 insertions, 0 deletions
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) + } +} |