package handlers
import (
"net/http"
"net/url"
"text/template"
"context"
"wyo.town/netzah/bsdauth"
"wyo.town/netzah/session"
)
var loginTmpl = template.Must(template.New("login").Parse(`
Login
`))
func LoginGET(w http.ResponseWriter, r *http.Request) {
_ = loginTmpl.Execute(w, struct{ Next string }{
Next: r.URL.Query().Get("next"),
})
}
func LoginPOST(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "bad form", http.StatusBadRequest)
return
}
user := r.Form.Get("username")
pass := r.Form.Get("password")
ok, _ := bsdauth.Authenticate(user, pass, "auth-myapp")
if !ok {
http.Error(w, "invalid credentials", http.StatusUnauthorized)
return
}
if err := session.Manager.RenewToken(r.Context()); err != nil {
http.Error(w, "server error", http.StatusInternalServerError)
return
}
session.Manager.Put(r.Context(), "user", user)
// Prefer ?next=... when present, but guard against open redirects.
next := r.Form.Get("next")
if next == "" {
next = "/"
} else {
u, err := url.Parse(next)
if err != nil || u.IsAbs() || len(u.Host) > 0 {
next = "/"
}
// Optional: only allow same-site paths
if u.Path == "" || u.Path[0] != '/' {
next = "/"
}
}
http.Redirect(w, r, next, http.StatusSeeOther) // PRG pattern
}
func LogoutPOST(w http.ResponseWriter, r *http.Request) {
_ = session.Manager.Destroy(r.Context())
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
func Dashboard(w http.ResponseWriter, r *http.Request) {
user := session.Manager.GetString(r.Context(), "user")
w.Write([]byte("Hello, " + user + "!"))
}
// Helper to stash values if you ever need it
func withUser(ctx context.Context, user string) context.Context {
return context.WithValue(ctx, struct{ k string }{"user"}, user)
}