add login handler

This commit is contained in:
2024-02-01 20:40:59 -06:00
parent 570fc6a298
commit 6aa6996f66
4 changed files with 52 additions and 38 deletions

View File

@@ -1,38 +0,0 @@
package serve
import (
"net/http"
"time"
)
const cookieName = "__Host-consent-v1"
// SetConsent registers a consent cookie on the response.
func SetConsent(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: "given",
Expires: time.Now().Add(20 * 365 * 24 * time.Hour),
Path: "/",
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
// NeedsConsent is a middleware that immediately responds with a 403 if the
// request does not bear a consent cookie.
func NeedsConsent(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := r.Cookie(cookieName); err != nil {
http.Error(w, cookieFailed, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
const cookieFailed = `
The requested resource requires consent to processing identifying information and storing necessary cookies.
I'm just a lil guy. The information is used solely for providing the service's functionality.
`

View File

@@ -21,6 +21,19 @@ func with[T any](ctx context.Context, v T) context.Context {
const sessionCookie = "__Host-id-v1"
// SetSession sets a cookie carrying a session token on a response.
func SetSession(w http.ResponseWriter, s player.Session) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookie,
Value: s.String(),
Path: "/",
Expires: time.Now().Add(365 * 24 * time.Hour),
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
// WithPlayerID is a middleware that adds a player ID to the request context
// based on the session cookie content. If there is no such cookie, or its
// value is invalid, the request fails with a 403 error.