add auth middleware

Signed-off-by: Tobias Erbshäußer <tobias@tesoft.dev>
This commit is contained in:
2026-05-24 09:22:21 +02:00
parent af43e23fe6
commit 13cdbe249b
+27 -6
View File
@@ -1,15 +1,36 @@
package main package main
import "net/http" import (
"context"
"net/http"
)
type ApiHandler struct { type ApiHandler struct {
db *Database
authToken *string
} }
func NewApiHandler() *ApiHandler { const authTokenCookieName = "auth-token"
// TODO const isAuthorizedContextKey = "is-authorized"
return &ApiHandler{}
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) { func IsAuthorized(request *http.Request) bool {
// TODO value := request.Context().Value(isAuthorizedContextKey)
return value != nil && value.(bool)
} }