Refactor authentication handlers and middleware

This commit is contained in:
bronku 2025-03-28 20:33:34 +01:00
parent 024d63bb16
commit bba6e8618a
5 changed files with 67 additions and 38 deletions

View file

@ -11,9 +11,6 @@ import (
"github.com/Bronku/iroon/internal/store"
)
//go:embed templates/login.html
var loginPage string
//go:embed templates/wrongPassword.html
var wrongPassword string
@ -34,42 +31,9 @@ func New(s *store.Store) *Authenticator {
return &out
}
func (a *Authenticator) login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("content-type", "text/html")
fmt.Fprint(w, loginPage)
return
}
err := r.ParseForm()
if err != nil {
w.Header().Set("content-type", "text/html")
fmt.Fprint(w, loginPage)
return
}
login := r.PostFormValue("login")
password := r.PostFormValue("password")
if login != "admin" || password != "secret" {
w.Header().Set("content-type", "text/html")
fmt.Fprint(w, wrongPassword)
return
}
cookie, err := a.newSession(login)
// #todo: change to a some sort of internal server error
if err != nil {
w.Header().Set("content-type", "text/html")
fmt.Fprint(w, "internal server error")
return
}
http.SetCookie(w, &cookie)
http.Redirect(w, r, "/", http.StatusFound)
}
func (a *Authenticator) Middleware(in http.Handler) http.Handler {
func (a *Authenticator) ensureAuth(in http.Handler) http.Handler {
fmt.Println("ensureAuth called")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.String() == "/login" {
a.login(w, r)
return
}
c, err := r.Cookie("token")
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
@ -92,3 +56,11 @@ func (a *Authenticator) Middleware(in http.Handler) http.Handler {
in.ServeHTTP(w, r)
})
}
func (a *Authenticator) Middleware(in http.Handler) http.Handler {
handler := http.NewServeMux()
handler.HandleFunc("GET /login", getLogin)
handler.HandleFunc("POST /login", a.login)
handler.Handle("/", a.ensureAuth(in))
return handler
}