From 13cdbe249bab66c2e17e1b9ee9eecbb1c7481f2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Erbsh=C3=A4u=C3=9Fer?= Date: Sun, 24 May 2026 09:22:21 +0200 Subject: [PATCH] add auth middleware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tobias Erbshäußer --- backend/api.go | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/backend/api.go b/backend/api.go index 80b4438..d331750 100644 --- a/backend/api.go +++ b/backend/api.go @@ -1,15 +1,36 @@ package main -import "net/http" +import ( + "context" + "net/http" +) type ApiHandler struct { + db *Database + authToken *string } -func NewApiHandler() *ApiHandler { - // TODO - return &ApiHandler{} +const authTokenCookieName = "auth-token" +const isAuthorizedContextKey = "is-authorized" + +func (h *ApiHandler) ProcessAuth(next http.Handler, required bool) http.Handler { + return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + isAuthorized := false + cookie, _ := request.Cookie(authTokenCookieName) + if cookie != nil { + isAuthorized = h.authToken != nil && *h.authToken == cookie.Value + } + + if !isAuthorized && required { + http.Error(writer, "authentication required", http.StatusUnauthorized) + return + } + + next.ServeHTTP(writer, request.WithContext(context.WithValue(request.Context(), isAuthorizedContextKey, isAuthorized))) + }) } -func (api *ApiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // TODO +func IsAuthorized(request *http.Request) bool { + value := request.Context().Value(isAuthorizedContextKey) + return value != nil && value.(bool) }