github.com/go-kivik/kivik/v4@v4.3.2/x/kivikd/context.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 //go:build !js 14 15 package kivikd 16 17 import ( 18 "context" 19 "net/http" 20 21 "github.com/go-kivik/kivik/v4/x/kivikd/auth" 22 ) 23 24 type contextKey struct { 25 name string 26 } 27 28 var ( 29 // SessionKey is a context key used to access the authenticated session. 30 SessionKey = &contextKey{"session"} 31 // ClientContextKey is a context key used to access the kivik client. 32 ClientContextKey = &contextKey{"client"} 33 // ServiceContextKey is a context key used to access the serve.Service struct. 34 ServiceContextKey = &contextKey{"service"} 35 ) 36 37 func setContext(s *Service) func(http.Handler) http.Handler { 38 return func(next http.Handler) http.Handler { 39 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 40 ctx := r.Context() 41 ctx = context.WithValue(ctx, ClientContextKey, s.Client) 42 ctx = context.WithValue(ctx, ServiceContextKey, s) 43 r = r.WithContext(ctx) 44 next.ServeHTTP(w, r) 45 }) 46 } 47 } 48 49 // MustGetSession returns the user context for the currently authenticated user. 50 // If no session is set, the function panics. 51 func MustGetSession(ctx context.Context) *auth.Session { 52 s, ok := ctx.Value(SessionKey).(**auth.Session) 53 if !ok { 54 panic("No session!") 55 } 56 return *s 57 } 58 59 func mustGetSessionPtr(ctx context.Context) **auth.Session { 60 s, ok := ctx.Value(SessionKey).(**auth.Session) 61 if !ok { 62 panic("No session!") 63 } 64 return s 65 } 66 67 // GetService extracts the Kivik service from the request. 68 func GetService(r *http.Request) *Service { 69 service := r.Context().Value(ServiceContextKey).(*Service) 70 return service 71 }