github.com/hanks177/podman/v4@v4.1.3-0.20220613032544-16d90015bc83/pkg/api/handlers/compat/auth.go (about)

     1  package compat
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net/http"
     8  	"strings"
     9  
    10  	DockerClient "github.com/containers/image/v5/docker"
    11  	"github.com/containers/image/v5/types"
    12  	"github.com/hanks177/podman/v4/libpod"
    13  	"github.com/hanks177/podman/v4/pkg/api/handlers/utils"
    14  	api "github.com/hanks177/podman/v4/pkg/api/types"
    15  	"github.com/hanks177/podman/v4/pkg/domain/entities"
    16  	docker "github.com/docker/docker/api/types"
    17  	"github.com/pkg/errors"
    18  )
    19  
    20  func stripAddressOfScheme(address string) string {
    21  	for _, s := range []string{"https", "http"} {
    22  		address = strings.TrimPrefix(address, s+"://")
    23  	}
    24  	return address
    25  }
    26  
    27  func Auth(w http.ResponseWriter, r *http.Request) {
    28  	var authConfig docker.AuthConfig
    29  	err := json.NewDecoder(r.Body).Decode(&authConfig)
    30  	if err != nil {
    31  		utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to parse request"))
    32  		return
    33  	}
    34  
    35  	skipTLS := types.NewOptionalBool(false)
    36  	if strings.HasPrefix(authConfig.ServerAddress, "https://localhost/") || strings.HasPrefix(authConfig.ServerAddress, "https://localhost:") || strings.HasPrefix(authConfig.ServerAddress, "localhost:") {
    37  		// support for local testing
    38  		skipTLS = types.NewOptionalBool(true)
    39  	}
    40  
    41  	runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
    42  	sysCtx := runtime.SystemContext()
    43  	sysCtx.DockerInsecureSkipTLSVerify = skipTLS
    44  
    45  	fmt.Println("Authenticating with existing credentials...")
    46  	registry := stripAddressOfScheme(authConfig.ServerAddress)
    47  	if err := DockerClient.CheckAuth(context.Background(), sysCtx, authConfig.Username, authConfig.Password, registry); err == nil {
    48  		utils.WriteResponse(w, http.StatusOK, entities.AuthReport{
    49  			IdentityToken: "",
    50  			Status:        "Login Succeeded",
    51  		})
    52  	} else {
    53  		var msg string
    54  
    55  		var unauthErr DockerClient.ErrUnauthorizedForCredentials
    56  		if errors.As(err, &unauthErr) {
    57  			msg = "401 Unauthorized"
    58  		} else {
    59  			msg = err.Error()
    60  		}
    61  
    62  		utils.WriteResponse(w, http.StatusInternalServerError, struct {
    63  			Message string `json:"message"`
    64  		}{
    65  			Message: "login attempt to " + authConfig.ServerAddress + " failed with status: " + msg,
    66  		})
    67  	}
    68  }