package handlers
import (
"net/http"
"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, nil)
}
func LoginPOST(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse credentials
if err := r.ParseForm(); err != nil {
http.Error(w, "bad form", http.StatusBadRequest)
return
}
user := r.Form.Get("username")
pass := r.Form.Get("password")
// One-time BSD Auth (OpenBSD's BSD Authentication, not PAM)
ok, _ := bsdauth.Authenticate(user, pass, "auth-myapp")
// `auth_userokay()` returns nonzero on success. :contentReference[oaicite:2]{index=2}
if !ok {
http.Error(w, "invalid credentials", http.StatusUnauthorized)
return
}
// Rotate session token to prevent fixation, then set user
if err := session.Manager.RenewToken(r.Context()); err != nil {
http.Error(w, "server error", http.StatusInternalServerError)
return
}
session.Manager.Put(r.Context(), "user", user)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
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)
}