autobrr/internal/http/middleware.go
martylukyy 1a23b69bcf
feat(web): move from react-router to @tanstack/router (#1338)
* fix(auth): invalid cookie handling and wrongful basic auth invalidation

* fix(auth): fix test to reflect new HTTP status code

* fix(auth/web): do not throw on error

* fix(http): replace http codes in middleware to prevent basic auth invalidation
fix typo in comment

* fix test

* fix(web): api client handle 403

* refactor(http): auth_test use testify.assert

* refactor(http): set session opts after valid login

* refactor(http): send more client headers

* fix(http): test

* refactor(web): move router to tanstack/router

* refactor(web): use route loaders and suspense

* refactor(web): useSuspense for settings

* refactor(web): invalidate cookie in middleware

* fix: loclfile

* fix: load filter/id

* fix(web): login, onboard, types, imports

* fix(web): filter load

* fix(web): build errors

* fix(web): ts-expect-error

* fix(tests): filter_test.go

* fix(filters): tests

* refactor: remove duplicate spinner components
refactor: ReleaseTable.tsx loading animation
refactor: remove dedicated `pendingComponent` for `settingsRoute`

* fix: refactor missed SectionLoader to RingResizeSpinner

* fix: substitute divides with borders to account for unloaded elements

* fix(api): action status URL param

* revert: action status URL param
add comment

* fix(routing): notfound handling and split files

* fix(filters): notfound get params

* fix(queries): colon

* fix(queries): comments ts-ignore

* fix(queries): extract queryKeys

* fix(queries): remove err

* fix(routes): move zob schema inline

* fix(auth): middleware and redirect to login

* fix(auth): failing test

* fix(logs): invalidate correct key

* fix(logs): invalidate correct key

* fix(logs): invalidate correct key

* fix: JSX element stealing focus from searchbar

* reimplement empty release table state text

* fix(context): use deep-copy

* fix(releases): empty state and filter input warnings

* fix(releases): empty states

* fix(auth): onboarding

* fix(cache): invalidate queries

---------

Co-authored-by: ze0s <43699394+zze0s@users.noreply.github.com>
2024-02-12 13:07:00 +01:00

114 lines
3.3 KiB
Go

// Copyright (c) 2021 - 2024, Ludvig Lundgren and the autobrr contributors.
// SPDX-License-Identifier: GPL-2.0-or-later
package http
import (
"context"
"net/http"
"runtime/debug"
"strings"
"time"
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog"
)
func (s Server) IsAuthenticated(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token := r.Header.Get("X-API-Token"); token != "" {
// check header
if !s.apiService.ValidateAPIKey(r.Context(), token) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
} else if key := r.URL.Query().Get("apikey"); key != "" {
// check query param like ?apikey=TOKEN
if !s.apiService.ValidateAPIKey(r.Context(), key) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
} else {
// check session
session, err := s.cookieStore.Get(r, "user_session")
if err != nil {
s.log.Error().Err(err).Msgf("could not get session from cookieStore")
session.Values["authenticated"] = false
// MaxAge<0 means delete cookie immediately
session.Options.MaxAge = -1
session.Options.Path = s.config.Config.BaseURL
if err := session.Save(r, w); err != nil {
s.log.Error().Err(err).Msgf("could not store session: %s", r.RemoteAddr)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Error(w, err.Error(), http.StatusForbidden)
return
}
// Check if user is authenticated
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
s.log.Warn().Msg("session not authenticated")
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
ctx := context.WithValue(r.Context(), "session", session)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
func LoggerMiddleware(logger *zerolog.Logger) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
log := logger.With().Logger()
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
t1 := time.Now()
defer func() {
t2 := time.Now()
// Recover and record stack traces in case of a panic
if rec := recover(); rec != nil {
log.Error().
Str("type", "error").
Timestamp().
Interface("recover_info", rec).
Bytes("debug_stack", debug.Stack()).
Msg("log system error")
http.Error(ww, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
if !strings.Contains("/api/healthz/liveness|/api/healthz/readiness", r.URL.Path) {
// log end request
log.Trace().
Str("type", "access").
Timestamp().
Fields(map[string]interface{}{
"remote_ip": r.RemoteAddr,
"url": r.URL.Path,
"proto": r.Proto,
"method": r.Method,
"user_agent": r.Header.Get("User-Agent"),
"status": ww.Status(),
"latency_ms": float64(t2.Sub(t1).Nanoseconds()) / 1000000.0,
"bytes_in": r.Header.Get("Content-Length"),
"bytes_out": ww.BytesWritten(),
}).
Msg("incoming_request")
}
}()
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
}