github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/auth/basic_provider.go (about)

     1  /*
     2   * Copyright 2020 The Compass 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 auth
    18  
    19  import (
    20  	"context"
    21  	"encoding/base64"
    22  
    23  	"github.com/pkg/errors"
    24  )
    25  
    26  // BasicAuthorizationProvider presents an AuthorizationProvider implementation which crafts Basic Authentication header values for the Authorization header
    27  type basicAuthorizationProvider struct{}
    28  
    29  // NewBasicAuthorizationProvider constructs a BasicAuthorizationProvider
    30  func NewBasicAuthorizationProvider() *basicAuthorizationProvider {
    31  	return &basicAuthorizationProvider{}
    32  }
    33  
    34  // Name specifies the name of the AuthorizationProvider
    35  func (u basicAuthorizationProvider) Name() string {
    36  	return "BasicAuthorizationProvider"
    37  }
    38  
    39  // Matches contains the logic for matching the AuthorizationProvider
    40  func (u basicAuthorizationProvider) Matches(ctx context.Context) bool {
    41  	credentials, err := LoadFromContext(ctx)
    42  	if err != nil {
    43  		return false
    44  	}
    45  
    46  	return credentials.Type() == BasicCredentialType
    47  }
    48  
    49  // GetAuthorization prepares the Authorization header Basic Authentication value for the executing request
    50  func (u basicAuthorizationProvider) GetAuthorization(ctx context.Context) (string, error) {
    51  	credentials, err := LoadFromContext(ctx)
    52  	if err != nil {
    53  		return "", err
    54  	}
    55  
    56  	basicCredentials, ok := credentials.Get().(*BasicCredentials)
    57  	if !ok {
    58  		return "", errors.New("failed to cast credentials to basic credentials type")
    59  	}
    60  
    61  	auth := basicCredentials.Username + ":" + basicCredentials.Password
    62  	encodedAuth := base64.StdEncoding.EncodeToString([]byte(auth))
    63  
    64  	return "Basic " + encodedAuth, nil
    65  }