muldap/cmd/search.go
Gregory Ballantine 092c9f3791
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Updated dependency versions (viper, cobra, and ldap)
2022-06-11 01:15:44 -04:00

67 lines
1.8 KiB
Go

package cmd
import (
"fmt"
"log"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
ldap "github.com/go-ldap/ldap/v3"
)
var (
flagAttrs string
flagFilter string
)
func init() {
// define search command flags
searchCmd.Flags().StringP("base", "b", "dc=example,dc=com", "LDAP search base DN")
searchCmd.Flags().IntP("indent", "i", 2, "Number of spaces to use while indenting search output")
searchCmd.Flags().StringVarP(&flagAttrs, "attributes", "a", "", "Comma-separated list of LDAP attributes to retrieve in the search")
searchCmd.Flags().StringVarP(&flagFilter, "filter", "f", "objectClass=*", "LDAP search filter")
// bind config file values to flags
viper.BindPFlag("search_base", searchCmd.Flags().Lookup("base"))
viper.BindPFlag("print_indent", searchCmd.Flags().Lookup("indent"))
}
// define search command
var searchCmd = &cobra.Command{
Use: "search",
Short: "Search an LDAP directory",
Long: `Perform an LDAP search operation on an LDAP directory`,
Run: func(cmd *cobra.Command, args []string) {
// create slice of attributes
var attrs []string = nil
if flagAttrs != "" {
attrs = strings.Split(flagAttrs, ",")
}
// 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()
// create a new LDAP search request
searchRequest := ldap.NewSearchRequest(
viper.GetString("search_base"), // The base dn to search
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(%s)", flagFilter), // The filter to apply
attrs, // A list attributes to retrieve
nil,
)
// perform the LDAP search
sr, err := l.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
// print the results
sr.PrettyPrint(viper.GetInt("print_indent"))
},
}