diff --git a/handler/middleware.go b/handler/middleware.go index 54e5d05..bf6b378 100644 --- a/handler/middleware.go +++ b/handler/middleware.go @@ -16,6 +16,7 @@ import ( var ( cacheInfoCtxKey = &ctxKeyType{"cacheInfo"} + userCtxKey = &ctxKeyType{"user"} ) func normalizeMiddleware(next http.Handler) http.Handler { @@ -74,6 +75,11 @@ func normalizeMiddleware(next http.Handler) http.Handler { func wrapMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if token := r.Header.Get(headerToken); token != "" { + if user := plexClient.GetUser(token); user != nil { + r = r.WithContext(context.WithValue(r.Context(), userCtxKey, user)) + } + } next.ServeHTTP(wrapResponseWriter(w, r.ProtoMajor), r) }) } @@ -185,16 +191,12 @@ func cacheMiddleware(next http.Handler) http.Handler { case cachePrefixStatic: break case cachePrefixDynamic, cachePrefixMetadata: - token := r.Header.Get(headerToken) - if token == "" { - return - } - user := plexClient.GetUser(token) + user := r.Context().Value(userCtxKey) if user != nil { - params.Set(headerUserId, strconv.Itoa(user.Id)) + params.Set(headerUserId, strconv.Itoa(user.(*plexUser).Id)) params.Set(headerAccept, getAcceptContentType(r)) } else { - params.Set(headerToken, token) + return } default: // invalid prefix diff --git a/handler/plex.go b/handler/plex.go index b8a4a19..0062dd6 100644 --- a/handler/plex.go +++ b/handler/plex.go @@ -137,21 +137,19 @@ func (c *PlexClient) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - if token := r.Header.Get(headerToken); token != "" { - // If it is an authorized request - if user := c.GetUser(token); user != nil { - switch path { - case "/:/scrobble", "/:/unscrobble": - ratingKey := r.URL.Query().Get("key") - if ratingKey != "" { - go clearCachedMetadata(ratingKey, user.Id) - } - case "/:/timeline": - go c.syncTimelineWithPlaxt(r, user) - case "/video/:/transcode/universal/decision": - if c.disableTranscode { - r = c.disableTranscoding(r) - } + // If it is an authorized request + if user := r.Context().Value(userCtxKey); user != nil { + switch path { + case "/:/scrobble", "/:/unscrobble": + ratingKey := r.URL.Query().Get("key") + if ratingKey != "" { + go clearCachedMetadata(ratingKey, user.(*plexUser).Id) + } + case "/:/timeline": + go c.syncTimelineWithPlaxt(r, user.(*plexUser)) + case "/video/:/transcode/universal/decision": + if c.disableTranscode { + r = c.disableTranscoding(r) } } }