github.com/antevens/oras@v0.8.1/pkg/auth/docker/login.go (about)

     1  package docker
     2  
     3  import (
     4  	"context"
     5  
     6  	ctypes "github.com/docker/cli/cli/config/types"
     7  	"github.com/docker/docker/api/types"
     8  	"github.com/docker/docker/registry"
     9  )
    10  
    11  // Login logs in to a docker registry identified by the hostname.
    12  func (c *Client) Login(ctx context.Context, hostname, username, secret string, renegotiate string, insecure bool) error {
    13  	hostname = resolveHostname(hostname)
    14  	cred := types.AuthConfig{
    15  		Username:      username,
    16  		ServerAddress: hostname,
    17  	}
    18  	if username == "" {
    19  		cred.IdentityToken = secret
    20  	} else {
    21  		cred.Password = secret
    22  	}
    23  
    24  	opts := registry.ServiceOptions{}
    25  
    26  	if insecure {
    27  		opts.InsecureRegistries = []string{hostname}
    28  	}
    29  
    30  	// Login to ensure valid credential
    31  	remote, err := registry.NewService(opts)
    32  	if err != nil {
    33  		return err
    34  	}
    35  	if _, token, err := remote.Auth(ctx, &cred, "oras"); err != nil {
    36  		return err
    37  	} else if token != "" {
    38  		cred.Username = ""
    39  		cred.Password = ""
    40  		cred.IdentityToken = token
    41  	}
    42  
    43  	// Store credential
    44  	return c.primaryCredentialsStore(hostname).Store(ctypes.AuthConfig(cred))
    45  }