vitess.io/vitess@v0.16.2/go/vt/vtadmin/http/handlers/authentication.go (about)

     1  /*
     2  Copyright 2021 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package handlers
    18  
    19  import (
    20  	"net/http"
    21  
    22  	"vitess.io/vitess/go/vt/vtadmin/rbac"
    23  )
    24  
    25  // NewAuthenticationHandler returns an http middleware that invokes the given
    26  // authenticator and calls the next handler in the middleware chain, with the
    27  // authenticated actor added to the request context.
    28  //
    29  // If the authenticator returns an error, then the overall http request is
    30  // failed with an Unauthorized code.
    31  func NewAuthenticationHandler(authenticator rbac.Authenticator) func(http.Handler) http.Handler {
    32  	return func(next http.Handler) http.Handler {
    33  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    34  			actor, err := authenticator.AuthenticateHTTP(r)
    35  			if err != nil {
    36  				http.Error(w, err.Error(), http.StatusUnauthorized)
    37  				return
    38  			}
    39  
    40  			next.ServeHTTP(w, r.WithContext(rbac.NewContext(r.Context(), actor)))
    41  		})
    42  	}
    43  }