Login form handling

This commit is contained in:
bronku 2025-03-21 20:37:25 +01:00
parent 8b5ac8c19f
commit e235e3d8a8

View file

@ -1,27 +1,51 @@
package auth package auth
import ( import (
_ "embed"
"fmt" "fmt"
"net/http" "net/http"
) )
//go:embed login.html
var loginPage string
//go:embed wrongPassword.html
var wrongPassword string
type Authenticator struct { type Authenticator struct {
} }
func (a *Authenticator) Authenticate(in http.HandlerFunc) http.HandlerFunc { func (a *Authenticator) login(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost {
if r.URL.String() == "/loginok" { 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{ c := http.Cookie{
Name: "token", Name: "token",
Value: "good", Value: "good",
} }
http.SetCookie(w, &c) http.SetCookie(w, &c)
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/", http.StatusFound)
return }
}
func (a *Authenticator) Authenticate(in http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.String() == "/login" { if r.URL.String() == "/login" {
w.Header().Set("content-type", "text/html") a.login(w, r)
fmt.Fprint(w, "<a href='/loginok'>Login</a>")
return return
} }
if _, err := r.Cookie("token"); err != nil { if _, err := r.Cookie("token"); err != nil {