summaryrefslogtreecommitdiff
path: root/handlers/login.go
diff options
context:
space:
mode:
authorroerick <roerick@wyo.town>2025-10-19 14:24:40 -0600
committerroerick <roerick@wyo.town>2025-10-19 14:24:40 -0600
commit132e0fe607396123a9fc5390c8657ef145bba3c6 (patch)
tree9a420d6f89a2de70d17bfb08789a26ccc501a9b9 /handlers/login.go
parenta1c3883334a9c54358173ebd822a5a85036dcda6 (diff)
initial commit with auth working
Diffstat (limited to 'handlers/login.go')
-rw-r--r--handlers/login.go70
1 files changed, 70 insertions, 0 deletions
diff --git a/handlers/login.go b/handlers/login.go
new file mode 100644
index 0000000..831cd36
--- /dev/null
+++ b/handlers/login.go
@@ -0,0 +1,70 @@
+package handlers
+
+import (
+ "net/http"
+ "text/template"
+ "context"
+
+ "wyo.town/netzah/bsdauth"
+ "wyo.town/netzah/session"
+ )
+
+
+var loginTmpl = template.Must(template.New("login").Parse(`
+<!doctype html><title>Login</title>
+<form method="post" action="/login/submit">
+ <label>User <input name="username" autocomplete="username"></label><br>
+ <label>Pass <input name="password" type="password" autocomplete="current-password"></label><br>
+ <button>Login</button>
+</form>
+`))
+
+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)
+}