From e235e3d8a8240d9999330c1f09a34461da48d32d Mon Sep 17 00:00:00 2001 From: bronku Date: Fri, 21 Mar 2025 20:37:25 +0100 Subject: [PATCH] Login form handling --- auth/auth.go | 46 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/auth/auth.go b/auth/auth.go index eecf823..0bbb654 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -1,27 +1,51 @@ package auth import ( + _ "embed" "fmt" "net/http" ) +//go:embed login.html +var loginPage string + +//go:embed wrongPassword.html +var wrongPassword string + type Authenticator struct { } +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 + } + c := http.Cookie{ + Name: "token", + Value: "good", + } + http.SetCookie(w, &c) + http.Redirect(w, r, "/", http.StatusFound) +} + func (a *Authenticator) Authenticate(in http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/loginok" { - c := http.Cookie{ - Name: "token", - Value: "good", - } - http.SetCookie(w, &c) - http.Redirect(w, r, "/", http.StatusFound) - return - } if r.URL.String() == "/login" { - w.Header().Set("content-type", "text/html") - fmt.Fprint(w, "Login") + a.login(w, r) return } if _, err := r.Cookie("token"); err != nil {