Skip to content

Commit

Permalink
Add a dedicated command to store/remove the authorisation configurati…
Browse files Browse the repository at this point in the history
…on on to disk.

Remove support for flag --save-config
  • Loading branch information
nikhilsbhat committed Jun 13, 2023
1 parent 208bc04 commit 1e01018
Show file tree
Hide file tree
Showing 5 changed files with 149 additions and 65 deletions.
147 changes: 147 additions & 0 deletions cmd/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package cmd

import (
"os"
"path/filepath"

"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)

const (
goCdCacheDirName = ".gocd"
goCdAuthConfigFileName = "auth_config.yaml"
)

func registerAuthConfigCommand() *cobra.Command {
registerAuthConfigCmd := &cobra.Command{
Use: "auth-config",
Short: "Command to set/remove the authorization configuration to be used by the cli",
Long: `Using the auth config commands, one can cache the authorization configuration onto a file so it can be used by further calls made using this utility.
Also, the cached authentication configurations can be erased using the same`,
RunE: func(cmd *cobra.Command, args []string) error {
if err := cmd.Usage(); err != nil {
return err
}

return nil
},
}

registerAuthConfigCmd.SetUsageTemplate(getUsageTemplate())

registerAuthConfigCmd.AddCommand(getAuthStoreCommand())
registerAuthConfigCmd.AddCommand(getAuthEraseCommand())

for _, command := range registerAuthConfigCmd.Commands() {
command.SilenceUsage = true
}

return registerAuthConfigCmd
}

func getAuthStoreCommand() *cobra.Command {
authStoreCmd := &cobra.Command{
Use: "store",
Short: "Command to cache the GoCD authorization configuration to be used by the cli",
Args: cobra.NoArgs,
PreRunE: setCLIClient,
RunE: func(cmd *cobra.Command, args []string) error {
cliLogger.Debug("saving authorisation config to cache, so that it can be reused next")
home, err := os.UserHomeDir()
if err != nil {
cliLogger.Errorf("fetching user's home directory errored with '%v'", err)

return err
}

authConfigDir := filepath.Join(home, goCdCacheDirName)
const filePermission = 0o644
if err = os.Mkdir(authConfigDir, filePermission); os.IsNotExist(err) {
cliLogger.Errorf("creating directory '%s' errored with '%v'", authConfigDir, err)

return err
}

authFile := filepath.Join(authConfigDir, goCdAuthConfigFileName)
authConfigFile, err := os.Create(authFile)
if err != nil {
cliLogger.Errorf("creating authfile '%s' errored with '%v'", authFile, err)

return err
}

cliLogger.Infof("authorisation config would be saved under %s", authConfigFile.Name())

cfgYAML, err := yaml.Marshal(cliCfg)
if err != nil {
cliLogger.Errorf("serializing auth config data to yaml errored with '%s'", err)

return err
}

if _, err = authConfigFile.WriteString(string(cfgYAML)); err != nil {
cliLogger.Errorf("writing auth config data to file '%s' errored with '%s'", authConfigFile.Name(), err)

return err
}

cliLogger.Infof("authorisation config was successfully saved under %s", authConfigFile.Name())

return nil
},
}

return authStoreCmd
}

func getAuthEraseCommand() *cobra.Command {
authEraseCmd := &cobra.Command{
Use: "remove",
Short: "Command to remove the cached GoCD authorization configuration that is used by the cli.",
Args: cobra.NoArgs,
PreRunE: setCLIClient,
RunE: func(cmd *cobra.Command, args []string) error {
home, err := os.UserHomeDir()
if err != nil {
cliLogger.Errorf("fetching user's home directory errored with '%v'", err)

return err
}

authConfigFile := filepath.Join(home, goCdCacheDirName, goCdAuthConfigFileName)

cliLogger.Infof("authorisation config saved in '%s' would be cleaned", authConfigFile)

if err = os.RemoveAll(authConfigFile); err != nil {
cliLogger.Errorf("cleaning authorisation config saved in '%s' errored with '%v'", authConfigFile, err)

return err
}

cliLogger.Infof("authorisation config saved in '%s' was cleaned successfully", authConfigFile)

return nil
},
}

return authEraseCmd
}

func checkForConfig() (bool, string, error) {
cliLogger.Debug("searching for authorisation configuration in cache")
home, err := os.UserHomeDir()
if err != nil {
return false, "", err
}

configPath := filepath.Join(home, goCdCacheDirName, goCdAuthConfigFileName)

if _, err = os.Stat(configPath); os.IsNotExist(err) {
cliLogger.Debug("no authorisation configuration found in cache")

return false, "", nil
}

return true, configPath, nil
}
58 changes: 0 additions & 58 deletions cmd/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,6 @@ func setCLIClient(cmd *cobra.Command, args []string) error {
}
}

if cliCfg.saveConfig {
cliLogger.Debug("--save-config is enabled, hence saving authorisation configuration")
if err = cliCfg.saveAuthConfig(); err != nil {
return err
}
}

goCDClient := gocd.NewClient(
cliCfg.URL,
cliCfg.Auth,
Expand All @@ -81,54 +74,3 @@ func setCLIClient(cmd *cobra.Command, args []string) error {

return nil
}

func (cfg *Config) saveAuthConfig() error {
cliLogger.Debug("saving authorisation config to cache, so that it can be reused next")
home, err := os.UserHomeDir()
if err != nil {
return err
}

authConfigDir := filepath.Join(home, ".gocd")
const filePermission = 0o644
if err = os.Mkdir(authConfigDir, filePermission); os.IsNotExist(err) {
return err
}

authConfigFile, err := os.Create(filepath.Join(authConfigDir, "auth_config.yaml"))
if err != nil {
return err
}

cliLogger.Debugf("authorisation config would be saved under %s", authConfigFile.Name())

cfgYAML, err := yaml.Marshal(cliCfg)
if err != nil {
return err
}

if _, err = authConfigFile.WriteString(string(cfgYAML)); err != nil {
return err
}

return nil
}

func checkForConfig() (bool, string, error) {
cliLogger.Debug("searching for authorisation configuration in cache")
home, err := os.UserHomeDir()
if err != nil {
return false, "", err
}

authConfigDir := filepath.Join(home, ".gocd")
configPath := filepath.Join(authConfigDir, "auth_config.yaml")

if _, err = os.Stat(configPath); os.IsNotExist(err) {
cliLogger.Debug("no authorisation configuration found in cache")

return false, "", nil
}

return true, configPath, nil
}
2 changes: 1 addition & 1 deletion cmd/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ type Config struct {
LogLevel string `yaml:"-"`
FromFile string `yaml:"-"`
ToFile string `yaml:"-"`
saveConfig bool
skipCacheConfig bool
}

Expand All @@ -47,6 +46,7 @@ func getGoCDCliCommands() *cobra.Command {
command.commands = append(command.commands, registerMaintenanceCommand())
command.commands = append(command.commands, registerJobsCommand())
command.commands = append(command.commands, registerArtifactCommand())
command.commands = append(command.commands, registerAuthConfigCommand())

return command.prepareCommands()
}
Expand Down
5 changes: 0 additions & 5 deletions cmd/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,12 @@ func registerGlobalFlags(cmd *cobra.Command) {
"enable this to Render output in YAML format")
cmd.PersistentFlags().BoolVarP(&cliCfg.YAML, "no-color", "", false,
"enable this to Render output in YAML format")
cmd.PersistentFlags().BoolVarP(&cliCfg.saveConfig, "save-config", "", false,
"enable this to locally save auth configs used to connect GoCD server (path: $HOME/.gocd/auth_config.yaml)")
cmd.PersistentFlags().BoolVarP(&cliCfg.skipCacheConfig, "skip-cache-config", "", false,
"if enabled locally save auth configs would not be used to authenticate GoCD server (path: $HOME/.gocd/auth_config.yaml)")
cmd.PersistentFlags().StringVarP(&cliCfg.FromFile, "from-file", "", "",
"file containing configurations of objects that needs to be created in GoCD, config-repo/pipeline-group/environment and etc.")
cmd.PersistentFlags().StringVarP(&cliCfg.ToFile, "to-file", "", "",
"file to which the output needs to be written to (this works only if --yaml or --json is enabled)")
// cmd.PersistentFlags().StringSliceVarP(&queries, "query", "q", nil,
// `query to filter the results, ex: '.material.attributes.url'. this uses library gojsonq beneath
// more queries can be found here https://github.com/thedevsaddam/gojsonq/wiki/Queries`)
cmd.PersistentFlags().StringVarP(&jsonQuery, "query", "q", "",
`query to filter the results, ex: '.material.attributes.type | id eq git'. this uses library gojsonq beneath
more queries can be found here https://github.com/thedevsaddam/gojsonq/wiki/Queries`)
Expand Down
2 changes: 1 addition & 1 deletion cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func AppVersion(cmd *cobra.Command, args []string) error {
}
}

cliVersionInfo := strings.Join([]string{"cli version", string(buildInfo), "\n"}, ": ")
cliVersionInfo := strings.Join([]string{"client version", string(buildInfo), "\n"}, ": ")
_, err = writer.Write([]byte(cliVersionInfo))
if err != nil {
log.Fatalln(err)
Expand Down

0 comments on commit 1e01018

Please sign in to comment.