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, Path: "/", }) 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) } }