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) }