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

Fix: Fixes & refactors user-sshkey commands #303

Merged
merged 6 commits into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 126 additions & 33 deletions cmd/users.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package cmd

import (
"context"
"encoding/json"
"errors"
"fmt"
l "github.com/uselagoon/machinery/api/lagoon"
lclient "github.com/uselagoon/machinery/api/lagoon/client"
s "github.com/uselagoon/machinery/api/schema"
"io/ioutil"
"os"
"strconv"
"strings"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -147,22 +152,36 @@ var deleteSSHKeyCmd = &cobra.Command{
Use: "user-sshkey",
Aliases: []string{"u"},
Short: "Delete an SSH key from Lagoon",
Run: func(cmd *cobra.Command, args []string) {
if sshKeyName == "" {
fmt.Println("Missing arguments: SSH key name is not defined")
cmd.Help()
os.Exit(1)
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateTokenE(cmdLagoon)
},
RunE: func(cmd *cobra.Command, args []string) error {
debug, err := cmd.Flags().GetBool("debug")
sshKeyID, err := cmd.Flags().GetUint("id")
if err != nil {
return err
}
var customReqResult []byte
var err error
if yesNo(fmt.Sprintf("You are attempting to delete SSH key named '%s', are you sure?", sshKeyName)) {
customReqResult, err = uClient.DeleteSSHKey(sshKeyName)
if sshKeyID == 0 {
fmt.Println("Missing arguments: SSH key ID is not defined")
return nil
}
current := lagoonCLIConfig.Current
token := lagoonCLIConfig.Lagoons[current].Token
lc := lclient.New(
lagoonCLIConfig.Lagoons[current].GraphQL,
lagoonCLIVersion,
&token,
debug)

if yesNo(fmt.Sprintf("You are attempting to delete SSH key ID:'%d', are you sure?", sshKeyID)) {
_, err := l.RemoveSSHKey(context.TODO(), sshKeyID, lc)
handleError(err)
resultData := output.Result{
Result: string(customReqResult),
Result: "success",
}
output.RenderResult(resultData, outputOptions)
}
return nil
},
}

Expand Down Expand Up @@ -226,23 +245,55 @@ var getUserKeysCmd = &cobra.Command{
Aliases: []string{"us"},
Short: "Get a user's SSH keys",
Long: `Get a user's SSH keys. This will only work for users that are part of a group`,
Run: func(cmd *cobra.Command, args []string) {
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateTokenE(cmdLagoon)
},
RunE: func(cmd *cobra.Command, args []string) error {
debug, err := cmd.Flags().GetBool("debug")
if err != nil {
return err
}
userEmail, err := cmd.Flags().GetString("email")
if err != nil {
return err
}
if userEmail == "" {
fmt.Println("Missing arguments: Email address is not defined")
cmd.Help()
os.Exit(1)
return nil
}
returnedJSON, err := uClient.ListUserSSHKeys(groupName, strings.ToLower(userEmail), false)
handleError(err)
var dataMain output.Table
err = json.Unmarshal([]byte(returnedJSON), &dataMain)

current := lagoonCLIConfig.Current
token := lagoonCLIConfig.Lagoons[current].Token
lc := lclient.New(
lagoonCLIConfig.Lagoons[current].GraphQL,
lagoonCLIVersion,
&token,
debug)
userKeys, err := l.GetUserSSHKeysByEmail(context.TODO(), userEmail, lc)
handleError(err)
if len(dataMain.Data) == 0 {
if len(userKeys.SSHKeys) == 0 {
output.RenderInfo(fmt.Sprintf("No SSH keys for user '%s'", strings.ToLower(userEmail)), outputOptions)
os.Exit(0)
return nil
}
output.RenderOutput(dataMain, outputOptions)

data := []output.Data{}
for _, userkey := range userKeys.SSHKeys {
data = append(data, []string{
strconv.Itoa(int(userkey.ID)),
userKeys.Email,
userkey.Name,
string(userkey.KeyType),
userkey.KeyValue,
})
}

dataMain := output.Table{
Header: []string{"ID", "Email", "Name", "Type", "Value"},
Data: data,
}

output.RenderOutput(dataMain, outputOptions)
return nil
},
}

Expand All @@ -252,18 +303,61 @@ var getAllUserKeysCmd = &cobra.Command{
Aliases: []string{"aus"},
Short: "Get all user SSH keys",
Long: `Get all user SSH keys. This will only work for users that are part of a group`,
Run: func(cmd *cobra.Command, args []string) {
returnedJSON, err := uClient.ListUserSSHKeys(groupName, strings.ToLower(userEmail), true)
handleError(err)
var dataMain output.Table
err = json.Unmarshal([]byte(returnedJSON), &dataMain)
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateTokenE(cmdLagoon)
},
RunE: func(cmd *cobra.Command, args []string) error {
debug, err := cmd.Flags().GetBool("debug")
if err != nil {
return err
}
groupName, err := cmd.Flags().GetString("name")
if err != nil {
return err
}

current := lagoonCLIConfig.Current
token := lagoonCLIConfig.Lagoons[current].Token
lc := lclient.New(
lagoonCLIConfig.Lagoons[current].GraphQL,
lagoonCLIVersion,
&token,
debug)
groupMembers, err := l.ListAllGroupMembersWithKeys(context.TODO(), groupName, lc)
handleError(err)
if len(dataMain.Data) == 0 {
output.RenderInfo("No SSH keys for any users", outputOptions)
os.Exit(0)

var userGroups []s.AddSSHKeyInput
for _, group := range *groupMembers {
for _, member := range group.Members {
for _, key := range member.User.SSHKeys {
userGroups = append(userGroups, s.AddSSHKeyInput{SSHKey: key, UserEmail: member.User.Email})
}
}
}
output.RenderOutput(dataMain, outputOptions)

var data []output.Data
for _, userData := range userGroups {
keyID := strconv.Itoa(int(userData.SSHKey.ID))
userEmail := returnNonEmptyString(strings.Replace(userData.UserEmail, " ", "_", -1))
keyName := returnNonEmptyString(strings.Replace(userData.SSHKey.Name, " ", "_", -1))
keyValue := returnNonEmptyString(strings.Replace(userData.SSHKey.KeyValue, " ", "_", -1))
keyType := returnNonEmptyString(strings.Replace(string(userData.SSHKey.KeyType), " ", "_", -1))
data = append(data, []string{
keyID,
userEmail,
keyName,
keyType,
keyValue,
})
}

dataMain := output.Table{
Header: []string{"ID", "Email", "Name", "Type", "Value"},
Data: data,
}

output.RenderOutput(dataMain, outputOptions)
return nil
},
}

Expand All @@ -281,12 +375,11 @@ func init() {
addUserSSHKeyCmd.Flags().StringVarP(&pubKeyFile, "pubkey", "K", "", "Specify path to the public key to add")
addUserSSHKeyCmd.Flags().StringVarP(&pubKeyValue, "keyvalue", "V", "", "Value of the public key to add (ssh-ed25519 AAA..)")
deleteUserCmd.Flags().StringVarP(&userEmail, "email", "E", "", "Email address of the user")
deleteSSHKeyCmd.Flags().StringVarP(&sshKeyName, "keyname", "N", "", "Name of the SSH key")
deleteSSHKeyCmd.Flags().Uint("id", 0, "ID of the SSH key")
updateUserCmd.Flags().StringVarP(&userFirstName, "firstName", "F", "", "New first name of the user")
updateUserCmd.Flags().StringVarP(&userLastName, "lastName", "L", "", "New last name of the user")
updateUserCmd.Flags().StringVarP(&userEmail, "email", "E", "", "New email address of the user")
updateUserCmd.Flags().StringVarP(&currentUserEmail, "current-email", "C", "", "Current email address of the user")
getUserKeysCmd.Flags().StringVarP(&userEmail, "email", "E", "", "New email address of the user")
getUserKeysCmd.Flags().StringVarP(&groupName, "name", "N", "", "Name of the group to check users in (if not specified, will default to all groups)")
getAllUserKeysCmd.Flags().StringVarP(&groupName, "name", "N", "", "Name of the group to list users in (if not specified, will default to all groups)")
getUserKeysCmd.Flags().StringP("email", "E", "", "New email address of the user")
getAllUserKeysCmd.Flags().StringP("name", "N", "", "Name of the group to list users in (if not specified, will default to all groups)")
}
4 changes: 2 additions & 2 deletions docs/commands/lagoon_delete_user-sshkey.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ lagoon delete user-sshkey [flags]
### Options

```
-h, --help help for user-sshkey
-N, --keyname string Name of the SSH key
-h, --help help for user-sshkey
--id uint ID of the SSH key
```

### Options inherited from parent commands
Expand Down
1 change: 0 additions & 1 deletion docs/commands/lagoon_get_user-sshkeys.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ lagoon get user-sshkeys [flags]
```
-E, --email string New email address of the user
-h, --help help for user-sshkeys
-N, --name string Name of the group to check users in (if not specified, will default to all groups)
```

### Options inherited from parent commands
Expand Down
2 changes: 0 additions & 2 deletions pkg/lagoon/users/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@ type Client interface {
ListUsers(string) ([]byte, error)
AddUser(api.User) ([]byte, error)
AddSSHKeyToUser(api.User, api.SSHKey) ([]byte, error)
DeleteSSHKey(string) ([]byte, error)
DeleteUser(api.User) ([]byte, error)
ModifyUser(api.User, api.User) ([]byte, error)
ListUserSSHKeys(string, string, bool) ([]byte, error)
ListGroups(string) ([]byte, error)
ListGroupProjects(string, bool) ([]byte, error)
}
Expand Down
70 changes: 0 additions & 70 deletions pkg/lagoon/users/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,24 +61,6 @@ func (u *Users) AddSSHKeyToUser(user api.User, sshKey api.SSHKey) ([]byte, error
return returnResult, nil
}

// DeleteSSHKey function
func (u *Users) DeleteSSHKey(keyName string) ([]byte, error) {
customReq := api.CustomRequest{
Query: `mutation deleteSshKey ($keyname: String!) {
deleteSshKey(input:{name: $keyname})
}`,
Variables: map[string]interface{}{
"keyname": keyName,
},
MappedResult: "deleteSshKey",
}
returnResult, err := u.api.Request(customReq)
if err != nil {
return []byte(""), err
}
return returnResult, nil
}

// DeleteUser function
func (u *Users) DeleteUser(user api.User) ([]byte, error) {
customReq := api.CustomRequest{
Expand Down Expand Up @@ -212,58 +194,6 @@ func processUserList(listUsers []byte) ([]byte, error) {
return json.Marshal(dataMain)
}

// ListUserSSHKeys function
func (u *Users) ListUserSSHKeys(groupName string, email string, allUsers bool) ([]byte, error) {
//@TODO: once individual user interaction comes in, this will need to be adjusted
customReq := api.CustomRequest{
Query: `query allGroups ($name: String) {
allGroups (name: $name) {
name
id
members{
user{
id
email
firstName
lastName
sshKeys{
name
keyType
keyValue
}
}
role
}
}
}`,
Variables: map[string]interface{}{
"name": groupName,
},
MappedResult: "allGroups",
}
listUsers, err := u.api.Request(customReq)
if err != nil {
return []byte(""), err
}
returnedKeys, err := processReturnedUserKeysList(listUsers)
if err != nil {
return []byte(""), err
}
var returnResult []byte
if allUsers {
returnResult, err = processAllUserKeysList(returnedKeys)
if err != nil {
return []byte(""), err
}
} else {
returnResult, err = processUserKeysList(returnedKeys, email)
if err != nil {
return []byte(""), err
}
}
return returnResult, nil
}

func processReturnedUserKeysList(listUsers []byte) ([]ExtendedSSHKey, error) {
var groupMembers GroupMembers
userDataStep1 := []ExtendedSSHKey{}
Expand Down
Loading