1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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)
}
|