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
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, "<a href='/loginok'>Login</a>")
a.login(w, r)
return
}
if _, err := r.Cookie("token"); err != nil {