Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autogenerate the Name of Credential in Login Flow #148

Merged
merged 6 commits into from
Sep 24, 2024

Conversation

nox1134
Copy link
Contributor

@nox1134 nox1134 commented Aug 2, 2024

Fixes #145

Added a function generateCredentialName in login.go to automatically create a credential name using the server URL and username. The credential name is generated by combining the server address (stripped of protocol and port) and the username.

@nox1134
Copy link
Contributor Author

nox1134 commented Aug 2, 2024

Hi! Should I also update the login_test to verify that the credential name is generated correctly?

Copy link
Collaborator

@bupd bupd left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should first make the 'Credential Name' optional in the login command before utilizing this.

@Althaf66
Copy link
Collaborator

@nox1134 Make changes in pkg/views/login/create.go

package login

import (
	"errors"

	"github.com/charmbracelet/huh"
	log "github.com/sirupsen/logrus"
)

type LoginView struct {
	Server   string
	Username string
	Password string
	Name     string
}

func CreateView(loginView *LoginView) {
	theme := huh.ThemeCharm()
	err := huh.NewForm(
		huh.NewGroup(
			huh.NewInput().
				Title("Server").
				Value(&loginView.Server).
				Validate(func(str string) error {
					if str == "" {
						return errors.New("server cannot be empty")
					}
					return nil
				}),
			huh.NewInput().
				Title("User Name").
				Value(&loginView.Username).
				Validate(func(str string) error {
					if str == "" {
						return errors.New("username cannot be empty")
					}
					return nil
				}),
			huh.NewInput().
				Title("Password").
        		EchoMode(huh.EchoModePassword).
				Value(&loginView.Password).
				Validate(func(str string) error {
					if str == "" {
						return errors.New("password cannot be empty")
					}
					return nil
				}),
			huh.NewInput().
				Title("Name of Credential").
				Value(&loginView.Name),
		),
	).WithTheme(theme).Run()

	if err != nil {
		log.Fatal(err)
	}

}

@Althaf66
Copy link
Collaborator

Changes in cmd/harbor/root/login.go

package root

import (
	"context"
	"fmt"
	"strings"

	"github.com/goharbor/go-client/pkg/harbor"
	"github.com/goharbor/go-client/pkg/sdk/v2.0/client/user"
	"github.com/goharbor/harbor-cli/pkg/utils"
	"github.com/goharbor/harbor-cli/pkg/views/login"
	"github.com/spf13/cobra"
)

var (
	serverAddress string
	Username      string
	Password      string
	Name          string
)

// LoginCommand creates a new `harbor login` command
func LoginCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "login [server]",
		Short: "Log in to Harbor registry",
		Long:  "Authenticate with Harbor Registry.",
		Args:  cobra.MaximumNArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			if len(args) > 0 {
				serverAddress = args[0]
			}

			if Name == "" {
				// Auto-generate the credential name if not provided
				Name = generateCredentialName(serverAddress, Username)
			}

			loginView := login.LoginView{
				Server:   serverAddress,
				Username: Username,
				Password: Password,
				Name:     Name,
			}

			var err error

			if loginView.Server != "" && loginView.Username != "" && loginView.Password != "" &&
				loginView.Name != "" {
				err = runLogin(loginView)
			} else {
				err = createLoginView(&loginView)
			}

			if err != nil {
				return err
			}
			return nil
		},
	}

	flags := cmd.Flags()
	flags.StringVarP(&Name, "name", "", "", "name for the set of credentials")
	flags.StringVarP(&Username, "username", "u", "", "Username")
	flags.StringVarP(&Password, "password", "p", "", "Password")

	return cmd
}

// generateCredentialName creates a default credential name based on server and username
func generateCredentialName(server, username string) string {
	if strings.HasPrefix(server, "http://") {
		server = strings.ReplaceAll(server, "http://", "")
	}
	if strings.HasPrefix(server, "https://") {
		server = strings.ReplaceAll(server, "https://", "")
	}
	if username != "" {
		return fmt.Sprintf("%s@%s", username, server)
	}
	return server
}

func createLoginView(loginView *login.LoginView) error {
	if loginView == nil {
		loginView = &login.LoginView{
			Server:   "",
			Username: "",
			Password: "",
			Name:     "",
		}
	}
	login.CreateView(loginView)
	return runLogin(*loginView)
}

func runLogin(opts login.LoginView) error {
	opts.Server = utils.FormatUrl(opts.Server)

	clientConfig := &harbor.ClientSetConfig{
		URL:      opts.Server,
		Username: opts.Username,
		Password: opts.Password,
	}
	client := utils.GetClientByConfig(clientConfig)

	ctx := context.Background()
	_, err := client.User.GetCurrentUserInfo(ctx, &user.GetCurrentUserInfoParams{})
	if err != nil {
		return fmt.Errorf("login failed, please check your credentials: %s", err)
	}
	if opts.Name == "" {
		opts.Name = generateCredentialName(opts.Server,opts.Username)
	}

	cred := utils.Credential{
		Name:          opts.Name,
		Username:      opts.Username,
		Password:      opts.Password,
		ServerAddress: opts.Server,
	}

	if err = utils.AddCredentialsToConfigFile(cred, utils.DefaultConfigPath); err != nil {
		return fmt.Errorf("failed to store the credential: %s", err)
	}
	return nil
}

@nox1134
Copy link
Contributor Author

nox1134 commented Sep 18, 2024

Hi @Althaf66! Thank you! I have made the requested changes.

@Althaf66
Copy link
Collaborator

ready for review

Copy link
Collaborator

@bupd bupd left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Run go fmt ./... to fix formatting issues in your code.

cmd/harbor/root/login.go Outdated Show resolved Hide resolved
Comment on lines 112 to 114
if opts.Name == "" {
opts.Name = generateCredentialName(opts.Server,opts.Username)
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

checking here is enough.

@bupd bupd added the enhancement New feature or request label Sep 21, 2024
nox1134 and others added 2 commits September 24, 2024 00:21
Co-authored-by: Prasanth B <[email protected]>
Signed-off-by: Priyanshi Gaur <[email protected]>
Signed-off-by: Priyanshi Gaur <[email protected]>
@Vad1mo Vad1mo merged commit bdf0233 into goharbor:main Sep 24, 2024
1 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Autogenerate the Name of Credential in Login Flow
4 participants