From d35c96caa75a4d3c6609f71abd0e565b4e44a055 Mon Sep 17 00:00:00 2001 From: hanhao Date: Wed, 15 Jun 2022 15:17:15 +0800 Subject: [PATCH 1/2] like linux user manage --- cmd/groupadd.go | 16 +++++-------- cmd/groupdel.go | 16 +++++-------- cmd/groupmems.go | 9 +------- cmd/groupmod.go | 11 ++++----- cmd/teamadd.go | 19 ++++++---------- cmd/teamdel.go | 19 +++++----------- cmd/teammod.go | 13 +++++------ cmd/useradd.go | 20 +++++++---------- cmd/userdel.go | 16 +++++-------- cmd/usermod.go | 12 ++++------ eldap/base.go | 56 ++++++++-------------------------------------- eldap/egroup.go | 6 ++++- eldap/eteam.go | 5 ++++- eldap/euser.go | 11 +++++++-- eldap/structs.go | 11 +++++---- go.mod | 2 +- model/ldap.go | 31 ++----------------------- test/eldap_test.go | 5 +++-- 18 files changed, 92 insertions(+), 186 deletions(-) diff --git a/cmd/groupadd.go b/cmd/groupadd.go index f5f4bf9..37429ad 100644 --- a/cmd/groupadd.go +++ b/cmd/groupadd.go @@ -22,16 +22,15 @@ import ( "github.com/spf13/cobra" ) -var groupaddName string var groupaddGidNumber string var groupaddDesc string var groupaddTeamName string -func groupaddRun() { +func groupaddRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() g := eldap.NewGroupEntry() - g.Name = append(g.Name, groupaddName) + g.Name = args g.Description = append(g.Description, groupaddDesc) g.GidNumber = append(g.GidNumber, groupaddGidNumber) if err := o.GroupAdd(groupaddTeamName, g); err != nil { @@ -42,22 +41,19 @@ func groupaddRun() { // groupaddCmd represents the groupadd command var groupaddCmd = &cobra.Command{ - Use: "groupadd", + Use: "groupadd [flags] GROUP", Short: "create a group", - Long: `The groupadd command creates a new group account using the values specified on the command line plus the default values from - the system. The new group will be entered into the ldap server as needed.`, + Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { - groupaddRun() + groupaddRun(cmd, args) }, } func init() { rootCmd.AddCommand(groupaddCmd) groupaddCmd.Flags().StringVarP(&groupaddGidNumber, "gid", "g", "", "use GID for the new group") - groupaddCmd.Flags().StringVarP(&groupaddName, "name", "n", "", "Group Name") - groupaddCmd.Flags().StringVarP(&groupaddDesc, "desc", "d", "no_desc", "Group Description") + groupaddCmd.Flags().StringVarP(&groupaddDesc, "desc", "d", "", "Group Description") groupaddCmd.Flags().StringVarP(&groupaddTeamName, "teamname", "t", "", "You want the group in which team, or default team") - groupaddCmd.MarkFlagRequired("name") groupaddCmd.MarkFlagRequired("gid") } diff --git a/cmd/groupdel.go b/cmd/groupdel.go index f9bd28c..c165f34 100644 --- a/cmd/groupdel.go +++ b/cmd/groupdel.go @@ -17,34 +17,28 @@ package cmd import ( "ela/eldap" - "ela/model" "log" "github.com/spf13/cobra" ) -var groupdelInfo = model.GroupInfo{} - -func groupdelRun() { +func groupdelRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() - if err := o.GroupDel(groupdelInfo.Name); err != nil { + if err := o.GroupDel(args[0]); err != nil { log.Fatalln(err) } } // groupdelCmd represents the groupdel command var groupdelCmd = &cobra.Command{ - Use: "groupdel", + Use: "groupdel [flags] GROUP", Short: "groupdel - delete a group", - Long: `The groupdel command modifies the system account files, deleting all entries that refer to GROUP. The named group must exist.`, + Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { - groupdelRun() + groupdelRun(cmd, args) }, } func init() { rootCmd.AddCommand(groupdelCmd) - groupdelCmd.Flags().StringVarP(&groupdelInfo.Name, "name", "n", "", "Group Name") - groupdelCmd.MarkFlagRequired("name") - } diff --git a/cmd/groupmems.go b/cmd/groupmems.go index f770735..d19805a 100644 --- a/cmd/groupmems.go +++ b/cmd/groupmems.go @@ -25,14 +25,10 @@ import ( var groupmemsName string var addUserName string var delUserName string -var groupmemsList bool func groupmemsRun() { o := eldap.NewOption() - if groupmemsList { - log.Fatalln("not support now") - return - } + if addUserName != "" { if err := o.GroupMems(groupmemsName, []string{addUserName}, eldap.Add); err != nil { log.Fatalln(err) @@ -64,8 +60,5 @@ func init() { groupmemsCmd.Flags().StringVarP(&groupmemsName, "group", "g", "", "change groupname instead of the user's group") groupmemsCmd.Flags().StringVarP(&addUserName, "add", "a", "", "add username to the members of the group") groupmemsCmd.Flags().StringVarP(&delUserName, "delete", "d", "", "add username to the members of the group") - groupmemsCmd.Flags().BoolVarP(&groupmemsList, "list", "l", false, "list the members of the group") - groupmemsCmd.MarkFlagRequired("group") - } diff --git a/cmd/groupmod.go b/cmd/groupmod.go index f4c908f..d73c288 100644 --- a/cmd/groupmod.go +++ b/cmd/groupmod.go @@ -22,14 +22,13 @@ import ( "github.com/spf13/cobra" ) -var groupmodName string var groupmodGidNumber string var groupmodDesc string -func groupmodRun() { +func groupmodRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() if groupaddGidNumber != "" { - if err := o.GroupMod(groupmodName, groupmodGidNumber); err != nil { + if err := o.GroupMod(args[0], groupmodGidNumber); err != nil { log.Fatalln(err) } } @@ -38,19 +37,17 @@ func groupmodRun() { // groupmodCmd represents the groupmod command var groupmodCmd = &cobra.Command{ - Use: "groupmod", + Use: "groupmod [flags] GROUP", Short: "modify a group definition on the system", Long: `The groupmod command modifies the definition of the specified GROUP by modifying the appropriate entry in the group database.`, Run: func(cmd *cobra.Command, args []string) { - groupmodRun() + groupmodRun(cmd, args) }, } func init() { rootCmd.AddCommand(groupmodCmd) - groupmodCmd.Flags().StringVarP(&groupmodName, "name", "n", "", "groupname") groupmodCmd.Flags().StringVarP(&groupmodGidNumber, "gid", "g", "", "change the group ID to GID") groupmodCmd.Flags().StringVarP(&groupmodDesc, "desc", "d", "", "Descroption Not support now") - groupmodCmd.MarkFlagRequired("name") } diff --git a/cmd/teamadd.go b/cmd/teamadd.go index 91ec905..60501bd 100644 --- a/cmd/teamadd.go +++ b/cmd/teamadd.go @@ -22,13 +22,13 @@ import ( "github.com/spf13/cobra" ) -var teamaddName string var teamaddDesc string -func teamaddRun() { +func teamaddRun(cmd *cobra.Command, args []string) { + o := eldap.NewOption() t := eldap.NewTeamEntry() - t.Name = append(t.Name, teamaddName) + t.Name = args t.Description = append(t.Description, teamaddDesc) if err := o.TeamAdd(t); err != nil { log.Fatalln(err) @@ -38,21 +38,16 @@ func teamaddRun() { // teamaddCmd represents the teamadd command var teamaddCmd = &cobra.Command{ - Use: "teamadd", + Use: "teamadd [flags] TEAM", Short: "create a new team", - Long: `team is an organization in ldap. For example: - -ela teamadd -n [-d ]`, + Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { - teamaddRun() + teamaddRun(cmd, args) }, } func init() { rootCmd.AddCommand(teamaddCmd) - - teamaddCmd.Flags().StringVarP(&teamaddName, "name", "n", "", "Team Name you create") - teamaddCmd.Flags().StringVarP(&teamaddDesc, "desc", "d", "no_desc", "Team Description") - teamaddCmd.MarkFlagRequired("name") + teamaddCmd.Flags().StringVarP(&teamaddDesc, "desc", "d", "", "Team Description") } diff --git a/cmd/teamdel.go b/cmd/teamdel.go index 20eda42..60c7155 100644 --- a/cmd/teamdel.go +++ b/cmd/teamdel.go @@ -17,36 +17,29 @@ package cmd import ( "ela/eldap" - "ela/model" "log" "github.com/spf13/cobra" ) -func teamdelRun() { +func teamdelRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() - if teamdelInfo.Name == "" { - log.Fatalln("Team Name Must Exist") - } - if err := o.TeamDelete(teamdelInfo.Name); err != nil { + + if err := o.TeamDelete(args[0]); err != nil { log.Fatalln(err) } } // teamdelCmd represents the teamdel command var teamdelCmd = &cobra.Command{ - Use: "teamdel", + Use: "teamdel [flags] TEAM", Short: "delete a user account", - Long: `delete a user account`, + Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { - teamdelRun() + teamdelRun(cmd, args) }, } -var teamdelInfo = model.TeamInfo{} func init() { rootCmd.AddCommand(teamdelCmd) - teamdelCmd.Flags().StringVarP(&teamdelInfo.Name, "name", "n", "", "The team you want to del") - teamdelCmd.MarkFlagRequired("name") - } diff --git a/cmd/teammod.go b/cmd/teammod.go index 4d6164e..f58a6b1 100644 --- a/cmd/teammod.go +++ b/cmd/teammod.go @@ -22,13 +22,12 @@ import ( "github.com/spf13/cobra" ) -var teammodName string var teammodDesc string -func teammodRun() { +func teammodRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() t := eldap.NewTeamEntry() - t.Name = append(t.Name, teammodName) + t.Name = args t.Description = append(t.Description, teammodDesc) if err := o.TeamDescUpdate(t); err != nil { log.Fatalln(err) @@ -37,19 +36,17 @@ func teammodRun() { // teammodCmd represents the teammod command var teammodCmd = &cobra.Command{ - Use: "teammod", + Use: "teammod [flags] TEAM", Short: "modify a team", - Long: `modify a team,only support modify desc`, + Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { - teammodRun() + teammodRun(cmd, args) }, } func init() { rootCmd.AddCommand(teammodCmd) - teammodCmd.Flags().StringVarP(&teammodName, "name", "n", "", "Team Name") teammodCmd.Flags().StringVarP(&teammodDesc, "desc", "d", "", "Team Description") - teammodCmd.MarkFlagRequired("name") teammodCmd.MarkFlagRequired("desc") } diff --git a/cmd/useradd.go b/cmd/useradd.go index ac4eef2..b501baf 100644 --- a/cmd/useradd.go +++ b/cmd/useradd.go @@ -23,7 +23,6 @@ import ( "github.com/spf13/cobra" ) -var useraddName string var useraddHomeDirectory string var useraddGidNumber string var useraddUidNumber string @@ -31,20 +30,20 @@ var useraddUserPassword string var useraddLoginShell string var useraddTeamName string -func useraddRun() { +func useraddRun(cmd *cobra.Command, args []string) { if useraddHomeDirectory == "" { - useraddHomeDirectory = fmt.Sprintf(`/%s/%s`, "home", useraddName) + useraddHomeDirectory = fmt.Sprintf(`/%s/%s`, "home", args[0]) } if useraddUserPassword == "" { - useraddUserPassword = useraddName + useraddUserPassword = args[0] } if useraddLoginShell == "" { useraddLoginShell = "/bin/bash" } o := eldap.NewOption() u := eldap.NewUserEntry() - u.CN = append(u.CN, useraddName) - u.Name = append(u.Name, useraddName) + u.CN = args + u.Name = args u.GidNumber = append(u.GidNumber, useraddGidNumber) u.UidNumber = append(u.UidNumber, useraddUidNumber) u.HomeDirectory = append(u.HomeDirectory, useraddHomeDirectory) @@ -58,18 +57,16 @@ func useraddRun() { // useraddCmd represents the useradd command var useraddCmd = &cobra.Command{ - Use: "useradd", + Use: "useradd [flags] LOGIN", Short: "create a new user or update default new user information", - Long: `the useradd command creates a new user account using the values specified on the command - line plus the default values from the ldap`, + Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { - useraddRun() + useraddRun(cmd, args) }, } func init() { rootCmd.AddCommand(useraddCmd) - useraddCmd.Flags().StringVarP(&useraddName, "name", "n", "", "username") useraddCmd.Flags().StringVarP(&useraddHomeDirectory, "home-dir", "d", "", "user home dir") useraddCmd.Flags().StringVarP(&useraddGidNumber, "gid", "g", "", "group number") useraddCmd.Flags().StringVarP(&useraddUidNumber, "uid", "u", "", "user uid number") @@ -77,7 +74,6 @@ func init() { useraddCmd.Flags().StringVarP(&useraddLoginShell, "shell", "s", "", "login shell of the new account") useraddCmd.Flags().StringVarP(&useraddTeamName, "team", "t", "", "teamname for this user") - useraddCmd.MarkFlagRequired("name") useraddCmd.MarkFlagRequired("gid") useraddCmd.MarkFlagRequired("uid") diff --git a/cmd/userdel.go b/cmd/userdel.go index 566159f..a11462a 100644 --- a/cmd/userdel.go +++ b/cmd/userdel.go @@ -17,34 +17,30 @@ package cmd import ( "ela/eldap" - "ela/model" "log" "github.com/spf13/cobra" ) -var userdelInfo = model.UserInfo{} +var userdelName string -func userdelRun() { +func userdelRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() - if err := o.UserDel(userdelInfo.Name); err != nil { + if err := o.UserDel(args[0]); err != nil { log.Fatalln(err) } } // userdelCmd represents the userdel command var userdelCmd = &cobra.Command{ - Use: "userdel", + Use: "userdel [flags] LOGIN", Short: "delete a user account and related files", - Long: `The userdel command modifies ldap server data, The named user must exist.`, + Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { - userdelRun() + userdelRun(cmd, args) }, } func init() { rootCmd.AddCommand(userdelCmd) - userdelCmd.Flags().StringVarP(&userdelInfo.Name, "name", "n", "", "username you want to delete") - userdelCmd.MarkFlagRequired("name") - } diff --git a/cmd/usermod.go b/cmd/usermod.go index 1b23521..97aaecd 100644 --- a/cmd/usermod.go +++ b/cmd/usermod.go @@ -23,16 +23,15 @@ import ( ) var usermodHome string -var usermodName string var usermodPassword string var usermodShell string var usermodUidNumber string var usermodGidNumber string -func usermodRun() { +func usermodRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() u := eldap.NewUserEntry() - u.Name = append(u.Name, usermodName) + u.Name = args u.LoginShell = append(u.LoginShell, usermodShell) u.GidNumber = append(u.GidNumber, usermodGidNumber) u.HomeDirectory = append(u.HomeDirectory, usermodHome) @@ -46,21 +45,18 @@ func usermodRun() { // usermodCmd represents the usermod command var usermodCmd = &cobra.Command{ - Use: "usermod", + Use: "usermod [flags] LOGIN", Short: "modify a user account", - Long: `he usermod command modifies the ldap to reflect the changes that are specified on the command line`, Run: func(cmd *cobra.Command, args []string) { - usermodRun() + usermodRun(cmd, args) }, } func init() { rootCmd.AddCommand(usermodCmd) usermodCmd.Flags().StringVarP(&usermodHome, "home", "d", "", "new home directory for the user account") - usermodCmd.Flags().StringVarP(&usermodName, "name", "n", "", "which account you want to change") usermodCmd.Flags().StringVarP(&usermodPassword, "password", "p", "", "use encrypted password for the new password") usermodCmd.Flags().StringVarP(&usermodShell, "shell", "s", "", "new login shell for the user account") usermodCmd.Flags().StringVarP(&usermodUidNumber, "uid", "u", "", "new UID for the user account") usermodCmd.Flags().StringVarP(&usermodGidNumber, "gid", "g", "", "force use GID as new primary group") - usermodCmd.MarkFlagRequired("name") } diff --git a/eldap/base.go b/eldap/base.go index 5fb24f8..0a19b2d 100644 --- a/eldap/base.go +++ b/eldap/base.go @@ -77,7 +77,7 @@ func (o Option) ldapConn() (*ldap.Conn, error) { } -func (o Option) TypeIs(DN string) (*model.EntryBaseInfo, error) { +func (o Option) TypeIs(DN string) (*model.EntryBase, error) { conn, err := o.ldapConn() if err != nil { @@ -90,7 +90,7 @@ func (o Option) TypeIs(DN string) (*model.EntryBaseInfo, error) { if err != nil { return nil, err } - EBI := model.EntryBaseInfo{Kind: Unknown, HasSubordinates: false} + EBI := model.EntryBase{Kind: Unknown, HasSubordinates: false} sr.Print() for _, entry := range sr.Entries { for _, v := range entry.GetAttributeValues("objectClass") { @@ -150,7 +150,7 @@ func (o Option) SearchAllEntryDNByAttr(Kind int, Attr string, Val string) ([]str /** * DN is the Base Search location,and Kind support User,Group,Team range 0-2 */ -func (o Option) SearchAllEntryByKindDN(DN string, Kind int) ([]model.EntryBaseInfo, error) { +func (o Option) SearchAllEntryByKindDN(DN string, Kind int) ([]model.EntryBase, error) { conn, err := o.ldapConn() if err != nil { return nil, err @@ -173,9 +173,9 @@ func (o Option) SearchAllEntryByKindDN(DN string, Kind int) ([]model.EntryBaseIn return nil, err } res.Print() - EBIArr := make([]model.EntryBaseInfo, 0) + EBIArr := make([]model.EntryBase, 0) for _, entry := range res.Entries { - ebi := model.EntryBaseInfo{} + ebi := model.EntryBase{} ebi.HasSubordinates = false if entry.GetAttributeValue("hasSubordinates") == "TRUE" { ebi.HasSubordinates = true @@ -190,7 +190,7 @@ func (o Option) SearchAllEntryByKindDN(DN string, Kind int) ([]model.EntryBaseIn /** Only return one layer entry by the domain you input */ -func (o Option) ShowBaseInfoScopeOne(DN string) ([]model.EntryBaseInfo, error) { +func (o Option) ShowBaseInfoScopeOne(DN string) ([]model.EntryBase, error) { conn, err := o.ldapConn() if err != nil { @@ -203,9 +203,9 @@ func (o Option) ShowBaseInfoScopeOne(DN string) ([]model.EntryBaseInfo, error) { if err != nil { return nil, err } - EBIArr := make([]model.EntryBaseInfo, 0) + EBIArr := make([]model.EntryBase, 0) for _, entry := range res.Entries { - ebi := model.EntryBaseInfo{Kind: Unknown, DN: entry.DN} + ebi := model.EntryBase{Kind: Unknown, DN: entry.DN} for _, v := range entry.GetAttributeValues("objectClass") { if v == defaultKindOC[Group] { @@ -235,7 +235,7 @@ func (o Option) ShowBaseInfoScopeOne(DN string) ([]model.EntryBaseInfo, error) { return EBIArr, nil } -func (o Option) AddEntry(dn string, attrs Attrs) error { +func (o Option) AddEntry(dn string, attrs model.Attrs) error { conn, err := o.ldapConn() if err != nil { return err @@ -248,44 +248,6 @@ func (o Option) AddEntry(dn string, attrs Attrs) error { return conn.Add(nar) } -/* -* Only support User Group Team - */ -func (o Option) AddEntryBYKindDN(SuperDN string, EI model.EntryInfo) error { - conn, err := o.ldapConn() - if err != nil { - return err - } - defer conn.Close() - nar := ldap.NewAddRequest("", nil) - if EI.Kind == Team { - nar.DN = fmt.Sprintf("ou=%s,%s", EI.TI.Name, SuperDN) - nar.Attribute("objectClass", defaultLdapOC[Team]) - nar.Attribute("ou", []string{EI.TI.Name}) - nar.Attribute("associatedDomain", []string{SuperDN}) - nar.Attribute("description", []string{EI.TI.Description}) - } else if EI.Kind == Group { - nar.DN = fmt.Sprintf("cn=%s,%s", EI.GI.Name, SuperDN) - nar.Attribute("objectClass", defaultLdapOC[Group]) - nar.Attribute("cn", []string{EI.GI.Name}) - nar.Attribute("gidNumber", []string{EI.GI.GidNumber}) - nar.Attribute("description", []string{EI.GI.Description}) - } else if EI.Kind == User { - nar.DN = fmt.Sprintf("uid=%s,%s", EI.UI.Name, SuperDN) - nar.Attribute("objectClass", defaultLdapOC[User]) - nar.Attribute("cn", []string{EI.UI.Name}) - nar.Attribute("uid", []string{EI.UI.Name}) // user username - nar.Attribute("uidNumber", []string{EI.UI.UidNumber}) //user uid - nar.Attribute("gidNumber", []string{EI.UI.GidNumber}) // This is primary group - nar.Attribute("homeDirectory", []string{EI.UI.HomeDirectory}) - nar.Attribute("userPassword", []string{EI.UI.UserPassword}) - nar.Attribute("loginShell", []string{EI.UI.LoginShell}) - } else { - return fmt.Errorf("unknow kind: %d", EI.Kind) - } - return conn.Add(nar) -} - func (o Option) ModifyEntryAttr(DN string, Arr []model.AttrVal) error { conn, err := o.ldapConn() if err != nil { diff --git a/eldap/egroup.go b/eldap/egroup.go index 10ed304..6e42d03 100644 --- a/eldap/egroup.go +++ b/eldap/egroup.go @@ -38,7 +38,11 @@ func (o Option) GroupAdd(teamName string, g model.GroupEntry) error { } dn, _ = combineDN(Group, arr[0], g.Name[0]) } - return o.AddEntry(dn, Map(g)) + attrs, err := Map(g) + if err != nil { + return err + } + return o.AddEntry(dn, attrs) } diff --git a/eldap/eteam.go b/eldap/eteam.go index 7264253..c260d64 100644 --- a/eldap/eteam.go +++ b/eldap/eteam.go @@ -32,7 +32,10 @@ func (o Option) TeamAdd(t model.TeamEntry) error { return fmt.Errorf("[FAIL] we find num %d name team,this version only support one from whole tree", len(arr)) } t.AssociatedDomain = append(t.AssociatedDomain, o.LAI.TopDN) - attrs := Map(t) + attrs, err := Map(t) + if err != nil { + return err + } dn, _ := combineDN(Team, o.LAI.TopDN, t.Name[0]) return o.AddEntry(dn, attrs) } diff --git a/eldap/euser.go b/eldap/euser.go index cb1149d..b075262 100644 --- a/eldap/euser.go +++ b/eldap/euser.go @@ -37,7 +37,11 @@ func (o Option) UserAdd(teamName string, u model.UserEntry) error { } dn, _ = combineDN(User, arr[0], u.Name[0]) } - return o.AddEntry(dn, Map(u)) + attrs, err := Map(u) + if err != nil { + return err + } + return o.AddEntry(dn, attrs) } /** @@ -64,7 +68,10 @@ func (o Option) UserMod(u model.UserEntry) error { return fmt.Errorf("bad dn number %d", len(arr)) } dn := arr[0] - um := Map(u) + um, err := Map(u) + if err != nil { + return err + } delete(um, "uid") attrs := []model.AttrVal{} for k, v := range um { diff --git a/eldap/structs.go b/eldap/structs.go index 6f79dd0..e772b86 100644 --- a/eldap/structs.go +++ b/eldap/structs.go @@ -17,15 +17,15 @@ limitations under the License. package eldap import ( + "ela/model" + "fmt" "reflect" ) -type Attrs map[string][]string - /** * Only Used For eldap */ -func Map(s interface{}) Attrs { +func Map(s interface{}) (model.Attrs, error) { rt := reflect.TypeOf(s) rv := reflect.ValueOf(s) mapv := map[string][]string{} @@ -43,5 +43,8 @@ func Map(s interface{}) Attrs { } mapv[key] = val } - return mapv + if len(mapv) == 0 { + return nil, fmt.Errorf("no attr in Attrs") + } + return mapv, nil } diff --git a/go.mod b/go.mod index 0fd330a..fe728ce 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,6 @@ require ( require ( github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef - github.com/magiconair/properties v1.8.6 github.com/stretchr/testify v1.7.1 gopkg.in/ini.v1 v1.66.4 ) @@ -23,6 +22,7 @@ require ( github.com/go-asn1-ber/asn1-ber v1.5.4 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/magiconair/properties v1.8.6 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/pelletier/go-toml v1.9.5 // indirect github.com/pelletier/go-toml/v2 v2.0.1 // indirect diff --git a/model/ldap.go b/model/ldap.go index 63d16bc..e39f126 100644 --- a/model/ldap.go +++ b/model/ldap.go @@ -16,7 +16,7 @@ limitations under the License. package model // Make Sure entry type is leaf or not -type EntryBaseInfo struct { +type EntryBase struct { HasSubordinates bool `json:"hasSub"` Kind int `json:"kind"` Name string `json:"name"` @@ -31,34 +31,7 @@ type LDAPAuthInfo struct { AdminPW string } -type EntryInfo struct { - TI TeamInfo - GI GroupInfo - UI UserInfo - Kind int //User Group Team must exist -} -type TeamInfo struct { - Name string - Description string -} - -type GroupInfo struct { - Name string - GidNumber string - Description string - MemberUid []string - TeamName string -} - -type UserInfo struct { - LoginShell string - GidNumber string - UidNumber string - Name string - HomeDirectory string - UserPassword string - TeamName string -} +type Attrs map[string][]string type AttrVal struct { Attr string diff --git a/test/eldap_test.go b/test/eldap_test.go index bad7665..0a6106d 100644 --- a/test/eldap_test.go +++ b/test/eldap_test.go @@ -2,13 +2,14 @@ package test import ( "ela/eldap" + "ela/model" "testing" "github.com/stretchr/testify/assert" ) func TestMap(t *testing.T) { - tests := []eldap.Attrs{ + tests := []model.Attrs{ { "ou": []string{"47oo"}, "associatedDomain": []string{"dc=nudt,dc=org"}, @@ -18,7 +19,7 @@ func TestMap(t *testing.T) { nt := eldap.NewTeamEntry() nt.Name = append(nt.Name, "47oo") nt.AssociatedDomain = append(nt.AssociatedDomain, "dc=nudt,dc=org") - mapnt := eldap.Map(nt) + mapnt, _ := eldap.Map(nt) t.Logf("%v\n", mapnt) for _, tt := range tests { assert.Equal(t, tt, mapnt) From 0abf780748af60d1ab8bb65ca0af78e0f880e134 Mon Sep 17 00:00:00 2001 From: hanhao Date: Wed, 15 Jun 2022 16:01:15 +0800 Subject: [PATCH 2/2] add an easy ase --- cmd/groupmod.go | 4 ++-- cmd/init.go | 8 ++------ cmd/root.go | 6 ++++-- cmd/userdel.go | 2 -- eldap/base.go | 4 ++-- eldap/egroup.go | 4 ++-- secret/aes.go | 16 ++++++++++++++++ 7 files changed, 28 insertions(+), 16 deletions(-) diff --git a/cmd/groupmod.go b/cmd/groupmod.go index d73c288..aeceb19 100644 --- a/cmd/groupmod.go +++ b/cmd/groupmod.go @@ -27,7 +27,7 @@ var groupmodDesc string func groupmodRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() - if groupaddGidNumber != "" { + if groupmodGidNumber != "" { if err := o.GroupMod(args[0], groupmodGidNumber); err != nil { log.Fatalln(err) } @@ -39,7 +39,7 @@ func groupmodRun(cmd *cobra.Command, args []string) { var groupmodCmd = &cobra.Command{ Use: "groupmod [flags] GROUP", Short: "modify a group definition on the system", - Long: `The groupmod command modifies the definition of the specified GROUP by modifying the appropriate entry in the group database.`, + Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { groupmodRun(cmd, args) }, diff --git a/cmd/init.go b/cmd/init.go index bed93e4..95e9c1d 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -39,11 +39,7 @@ func initRun() { fmt.Printf("Please enter ldap Admin account: ") fmt.Scanln(&lai.Admin) pd, _ := gopass.GetPasswdPrompt(`Please enter ldap admin passwd(enter "NO" to not write password): `, true, os.Stdin, os.Stdout) - asepd, err := secret.EncryptAES([]byte(pd), secret.KEY) - if err != nil { - log.Fatalln(err) - return - } + asepd := secret.EasyEncrypt([]byte(pd), secret.KEY) lai.AdminPW = string(asepd) homedir, _ := os.UserHomeDir() @@ -55,7 +51,7 @@ func initRun() { dS.NewKey("Admin", lai.Admin) dS.NewKey("AdminPW", lai.AdminPW) dS.NewKey("TopDN", lai.TopDN) - if err = cfg.SaveTo(filename); err != nil { + if err := cfg.SaveTo(filename); err != nil { log.Fatalln(err) } diff --git a/cmd/root.go b/cmd/root.go index 0413c20..2db23bd 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + "log" "os" "github.com/spf13/cobra" @@ -87,7 +88,8 @@ func initConfig() { viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) + if err := viper.ReadInConfig(); err != nil { + // fmt.Println("Using config file:", viper.ConfigFileUsed()) + log.Fatalln("Using config file Error:", viper.ConfigFileUsed()) } } diff --git a/cmd/userdel.go b/cmd/userdel.go index a11462a..a8ef9cb 100644 --- a/cmd/userdel.go +++ b/cmd/userdel.go @@ -22,8 +22,6 @@ import ( "github.com/spf13/cobra" ) -var userdelName string - func userdelRun(cmd *cobra.Command, args []string) { o := eldap.NewOption() if err := o.UserDel(args[0]); err != nil { diff --git a/eldap/base.go b/eldap/base.go index 0a19b2d..38e4bce 100644 --- a/eldap/base.go +++ b/eldap/base.go @@ -280,10 +280,10 @@ func (o Option) DeleteEntry(DN string) error { } func NewOption() Option { - pwd, _ := secret.DecryptAES([]byte(viper.GetString("default.adminpw")), secret.KEY) + pwd := secret.EasyDecrypt(viper.GetString("default.adminpw"), secret.KEY) if string(pwd) == "NO" { pass, _ := gopass.GetPasswdPrompt("enter admin password: ", true, os.Stdin, os.Stdout) - pwd = pass + pwd = string(pass) } return Option{ diff --git a/eldap/egroup.go b/eldap/egroup.go index 6e42d03..6ab48e0 100644 --- a/eldap/egroup.go +++ b/eldap/egroup.go @@ -90,8 +90,8 @@ func (o Option) GroupMod(groupName string, gidNumber string) error { if len(arr) != 1 { return fmt.Errorf("bad dn number %d", len(arr)) } - DN := arr[0] - return o.ModifyEntryAttr(DN, []model.AttrVal{ + dn := arr[0] + return o.ModifyEntryAttr(dn, []model.AttrVal{ {AttrOP: Rep, Attr: "gidNumber", Val: []string{gidNumber}}, }) } diff --git a/secret/aes.go b/secret/aes.go index 5c587fe..b8e99f4 100644 --- a/secret/aes.go +++ b/secret/aes.go @@ -19,10 +19,26 @@ import ( "bytes" "crypto/aes" "crypto/cipher" + "encoding/base64" + "fmt" ) var KEY = []byte("easy-ldap-admin!") +func EasyEncrypt(src []byte, key []byte) string { + sk := append(src, key...) + return base64.StdEncoding.EncodeToString(sk) +} + +func EasyDecrypt(src string, key []byte) string { + sk, err := base64.StdEncoding.DecodeString(src) + if err != nil { + fmt.Println(err) + } + passwd := sk[:len(sk)-len(key)] + return string(passwd) +} + // padding data func padding(src []byte, blockSize int) []byte { padNum := blockSize - len(src)%blockSize