Skip to content

Commit

Permalink
feat: put user info into the context of requests
Browse files Browse the repository at this point in the history
  • Loading branch information
RoyXiang committed Mar 10, 2022
1 parent 2c538a2 commit 2fb175c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 22 deletions.
16 changes: 9 additions & 7 deletions handler/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (

var (
cacheInfoCtxKey = &ctxKeyType{"cacheInfo"}
userCtxKey = &ctxKeyType{"user"}
)

func normalizeMiddleware(next http.Handler) http.Handler {
Expand Down Expand Up @@ -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)
})
}
Expand Down Expand Up @@ -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
Expand Down
28 changes: 13 additions & 15 deletions handler/plex.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
Expand Down

0 comments on commit 2fb175c

Please sign in to comment.