Skip to content

Commit

Permalink
Add update command for user
Browse files Browse the repository at this point in the history
  • Loading branch information
royroyee committed Apr 7, 2024
1 parent a2dec57 commit 65f97e7
Show file tree
Hide file tree
Showing 8 changed files with 139 additions and 30 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,9 @@ $ alpacon user describe [USER NAME]
# Create a new user
$ alpacon user create
# Update the user information.
$ alpacon update [USER NAME]
# Delete user
$ alpacon user delete [USER NAME]
Expand Down
31 changes: 25 additions & 6 deletions api/iam/iam.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,7 @@ func GetUserDetail(ac *client.AlpaconClient, userId string) ([]byte, error) {
return responseBody, nil
}

func GetGroupDetail(ac *client.AlpaconClient, groupName string) ([]byte, error) {
groupId, err := GetGroupIDByName(ac, groupName)
if err != nil {
return nil, err
}

func GetGroupDetail(ac *client.AlpaconClient, groupId string) ([]byte, error) {
responseBody, err := ac.SendGetRequest(utils.BuildURL(groupURL, groupId, nil))
if err != nil {
return nil, err
Expand Down Expand Up @@ -301,3 +296,27 @@ func getLDAPStatus(isLDAP bool) string {

return "local"
}

func UpdateUser(ac *client.AlpaconClient, userName string) ([]byte, error) {
userId, err := GetUserIDByName(ac, userName)
if err != nil {
return nil, err
}

responseBody, err := GetUserDetail(ac, userId)
if err != nil {
return nil, err
}

data, err := utils.ProcessEditedData(responseBody)
if err != nil {
return nil, err
}

responseBody, err = ac.SendPatchRequest(utils.BuildURL(userURL, userId, nil), data)
if err != nil {
return nil, err
}

return responseBody, nil
}
5 changes: 0 additions & 5 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@ func NewAlpaconAPIClient() (*AlpaconClient, error) {
return nil, err
}

// TODO CLI version check
// res, err := utils.VersionCheck()

return client, nil
}

Expand Down Expand Up @@ -175,8 +172,6 @@ func (ac *AlpaconClient) SendPatchRequest(url string, body interface{}) ([]byte,
return nil, err
}

fmt.Println(jsonValue)

req, err := ac.createRequest("PATCH", url, bytes.NewBuffer(jsonValue))
if err != nil {
return nil, err
Expand Down
1 change: 1 addition & 0 deletions cmd/iam/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ func init() {
UserCmd.AddCommand(userDetailCmd)
UserCmd.AddCommand(userDeleteCmd)
UserCmd.AddCommand(userCreateCmd)
UserCmd.AddCommand(userUpdateCmd)
}
40 changes: 40 additions & 0 deletions cmd/iam/user_update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package iam

import (
"github.com/alpacanetworks/alpacon-cli/api/iam"
"github.com/alpacanetworks/alpacon-cli/client"
"github.com/alpacanetworks/alpacon-cli/utils"
"github.com/spf13/cobra"
)

var userUpdateCmd = &cobra.Command{
Use: "update [USER NAME]",
Short: "Update the user information",
Long: `
Update the user information in the Alpacon.
This command allows you to update the user's details, such as email, and other personal information within the Alpacon system.
However, due to permission restrictions or certain fields being read-only, not all submitted changes may be applied.
It's important to understand that modifications to certain information may require higher user privileges.
Due to these factors, after successfully executing the update command, the return of user information allows for verification of the modifications.
`,
Example: `
alpacon user update [USER_NAME]
`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
userName := args[0]

alpaconClient, err := client.NewAlpaconAPIClient()
if err != nil {
utils.CliError("Connection to Alpacon API failed: %s. Consider re-logging.", err)
}

userDetail, err := iam.UpdateUser(alpaconClient, userName)
if err != nil {
utils.CliError("Failed to update the user info: %s.", err)
}

utils.CliInfo("%s user successfully updated to alpacon.", userName)
utils.PrintJson(userDetail)
},
}
36 changes: 18 additions & 18 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
var RootCmd = &cobra.Command{
Use: "alpacon",
Aliases: []string{"ac"},
Short: "Alpacon CLI: Your Gateway to Alpacon Services",
Expand All @@ -31,55 +31,55 @@ var rootCmd = &cobra.Command{
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
if err := RootCmd.Execute(); err != nil {
utils.CliError("While executing the command: %s", err)
}
}

func init() {
// version
rootCmd.AddCommand(versionCmd)
RootCmd.AddCommand(versionCmd)

// login
rootCmd.AddCommand(loginCmd)
RootCmd.AddCommand(loginCmd)

// iam
rootCmd.AddCommand(iam.UserCmd)
rootCmd.AddCommand(iam.GroupCmd)
RootCmd.AddCommand(iam.UserCmd)
RootCmd.AddCommand(iam.GroupCmd)

// server
rootCmd.AddCommand(server.ServerCmd)
RootCmd.AddCommand(server.ServerCmd)

// agent
rootCmd.AddCommand(agent.AgentCmd)
RootCmd.AddCommand(agent.AgentCmd)

// websh
rootCmd.AddCommand(websh.WebshCmd)
RootCmd.AddCommand(websh.WebshCmd)

// ftp
rootCmd.AddCommand(ftp.CpCmd)
RootCmd.AddCommand(ftp.CpCmd)

// packages
rootCmd.AddCommand(packages.PackagesCmd)
RootCmd.AddCommand(packages.PackagesCmd)

// log
rootCmd.AddCommand(log.LogCmd)
RootCmd.AddCommand(log.LogCmd)

// event
rootCmd.AddCommand(event.EventCmd)
RootCmd.AddCommand(event.EventCmd)

// note
rootCmd.AddCommand(note.NoteCmd)
RootCmd.AddCommand(note.NoteCmd)

// authority
rootCmd.AddCommand(authority.AuthorityCmd)
RootCmd.AddCommand(authority.AuthorityCmd)

// csr
rootCmd.AddCommand(csr.CsrCmd)
RootCmd.AddCommand(csr.CsrCmd)

// certificate
rootCmd.AddCommand(cert.CertCmd)
RootCmd.AddCommand(cert.CertCmd)

// token
rootCmd.AddCommand(token.TokenCmd)
RootCmd.AddCommand(token.TokenCmd)
}
7 changes: 7 additions & 0 deletions utils/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,10 @@ func CliWarning(msg string, args ...interface{}) {
warningMessage := fmt.Sprintf(msg, args...)
fmt.Fprintf(os.Stderr, "%s: %s\n", Yellow("Warning"), warningMessage)
}

// CliInfoWithExit prints an informational message to stderr and exits the program with a status code of 0
func CliInfoWithExit(msg string, args ...interface{}) {
infoMessage := fmt.Sprintf(msg, args...)
fmt.Fprintf(os.Stderr, "%s: %s\n", Blue("Info"), infoMessage)
os.Exit(0) // Use exit code 0 to indicate successful completion.
}
46 changes: 45 additions & 1 deletion utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package utils

import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
Expand Down Expand Up @@ -270,6 +272,39 @@ func IsUUID(str string) bool {
return err == nil
}

// ProcessEditedData facilitates user modifications to original data,
// formats it, supports editing via a temp file, compares the edited data against the original,
// and parses it into JSON. If no changes are made, the update is aborted and an error is returned.
func ProcessEditedData(originalData []byte) (interface{}, error) {
prettyJSON, err := PrettyJSON(originalData)
if err != nil {
return nil, err
}

tmpFile, err := CreateAndEditTempFile(prettyJSON.Bytes())
if err != nil {
return nil, err
}
defer os.Remove(tmpFile)

editedContent, err := os.ReadFile(tmpFile)
if err != nil {
return nil, err
}

if bytes.Equal(prettyJSON.Bytes(), editedContent) {
CliInfoWithExit("No changes made. Aborting update.")
}

var jsonData interface{}
err = json.Unmarshal(editedContent, &jsonData)
if err != nil {
return nil, err
}

return jsonData, nil
}

func CreateAndEditTempFile(data []byte) (string, error) {
tmpfile, err := os.CreateTemp("", "example.*.json")
if err != nil {
Expand All @@ -285,7 +320,7 @@ func CreateAndEditTempFile(data []byte) (string, error) {
return "", err
}

cmd := exec.Command("vim", tmpfile.Name())
cmd := exec.Command("vi", tmpfile.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
Expand All @@ -294,3 +329,12 @@ func CreateAndEditTempFile(data []byte) (string, error) {

return tmpfile.Name(), nil
}

func PrettyJSON(data []byte) (*bytes.Buffer, error) {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, data, "", "\t"); err != nil {
return nil, err
}

return &prettyJSON, nil
}

0 comments on commit 65f97e7

Please sign in to comment.