add logout button

This commit is contained in:
2024-02-02 17:30:35 -06:00
parent 8a07105316
commit 2314b61671
3 changed files with 49 additions and 5 deletions

View File

@@ -34,9 +34,22 @@ func SetSession(w http.ResponseWriter, s player.Session) {
})
}
// WithSession 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 401 error.
// RemoveSession clears the session token cookie on a response.
func RemoveSession(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookie,
Value: "",
Path: "/",
Expires: time.Unix(0, 0),
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
// WithSession is a middleware that adds a player ID and session 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 401 error.
func WithSession(sessions player.RowQuerier) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -55,7 +68,7 @@ func WithSession(sessions player.RowQuerier) func(http.Handler) http.Handler {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
ctx := with(r.Context(), p)
ctx := with(with(r.Context(), id), p)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
@@ -65,3 +78,8 @@ func WithSession(sessions player.RowQuerier) func(http.Handler) http.Handler {
func ReqPlayer(ctx context.Context) player.ID {
return value[player.ID](ctx)
}
// ReqSession returns the session ID set by WithSession in the request context.
func ReqSession(ctx context.Context) player.Session {
return value[player.Session](ctx)
}