Added a basic user edit command

This commit is contained in:
Gregory Ballantine 2018-07-21 11:01:20 -04:00
parent 4960f91665
commit 9b7763156d
2 changed files with 72 additions and 2 deletions

70
cmd/user/edit.go Normal file
View File

@ -0,0 +1,70 @@
package user
import (
"errors"
"fmt"
"log"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
ldap "gopkg.in/ldap.v2"
)
var (
flagUserAttributes []string
)
func init() {
// define user delete subcommand flags
userEditCmd.Flags().StringP("base_ou", "o", "", "LDAP OU where your user entries are stored")
userEditCmd.Flags().StringP("uid_attribute", "a", "uid", "LDAP DN attribute for users")
userEditCmd.Flags().StringVarP(&flagUserUsername, "username", "u", "", "Username of user to delete")
userEditCmd.Flags().StringSliceVarP(&flagUserAttributes, "attributes", "m", []string{}, "Comma-separated or multi-flagged list of attributes to change (format: attr=value)")
// bind config file values to user delete flags
viper.BindPFlag("user.base_ou", userEditCmd.Flags().Lookup("base_ou"))
viper.BindPFlag("user.uid_attr", userEditCmd.Flags().Lookup("uid_attribute"))
}
// define user edit subcommand
var userEditCmd = &cobra.Command{
Use: "edit",
Short: "Edit an LDAP user in the directory",
Long: `Edit an LDAP user resource in the directory.`,
Run: func(cmd *cobra.Command, args []string) {
// check if any attributes were given
if len(flagUserAttributes) < 1 {
log.Fatal(errors.New("You didn't supply any user attributes"))
}
// create new LDAP connection
l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", viper.GetString("host"), viper.GetInt("port")))
if err != nil {
log.Fatal(err)
}
defer l.Close()
// bind as the admin user
err = l.Bind(viper.GetString("bind_dn"), viper.GetString("bind_pw"))
if err != nil {
log.Fatal(err)
}
// set up user DN
userDn := fmt.Sprintf("%s=%s,%s", viper.GetString("user.uid_attr"), flagUserUsername, viper.GetString("user.base_ou"))
// create a new edit request object
modifyRequest := ldap.NewModifyRequest(userDn)
// loop through list of attribute changes
for _, attrModify := range flagUserAttributes {
attr := strings.Split(attrModify, "=")
modifyRequest.Replace(attr[0], []string{attr[1]})
}
// perform the modify operation
err = l.Modify(modifyRequest)
if err != nil {
log.Fatal(err)
}
},
}

View File

@ -17,7 +17,7 @@ var (
func init() {
// register add command and subcommands
UserCmd.AddCommand(userAddCmd, userDeleteCmd, userPwCmd)
UserCmd.AddCommand(userAddCmd, userDeleteCmd, userEditCmd, userPwCmd)
}
// define user command
@ -26,6 +26,6 @@ var UserCmd = &cobra.Command{
Short: "Manage LDAP user resources",
Long: `Perform various LDAP operations on user resources.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Metaunix.net LDAP tool, user command. Available subcommands are: add, delete, pw")
fmt.Println("Metaunix.net LDAP tool, user command. Available subcommands are: add, delete, edit, pw")
},
}