summaryrefslogtreecommitdiff
path: root/handlers/login.go
blob: 6da835aaddd2279d5f9675122966d9d916b21fd1 (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
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(`
<!doctype html><title>Login</title>
<form method="post" action="/login/submit">
  <input type="hidden" name="next" value="{{.Next}}">
  <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, 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)
}