Translate

Friday, March 11, 2022

Golang - Add a user to an active directory group

A simple Golang function that I wrote to add a user to a group in AD.


//func ModifyGroup
//	strUDN: User DN
//	strGCN: Group CN
//	strType: flag to Remove or Add the user from the group
func ModifyGroup(strUDN, strGCN, strType string) bool {
	var bR bool = false
	ldapConn = ldap_Bind()     //Get a connection
	strGDN, _ := GetDN(strGCN) //Get the group DN using the group CN
	modify := ldap.NewModifyRequest(strGDN, []ldap.Control{})
	log.Println("ModifyGroup on User: ", strUDN, ", Group: ", strGCN, ", Type: ", strType)
	if strType == "Remove" {
		modify.Delete("member", []string{strUDN})
	}
	if strType == "Add" {
		modify.Add("member", []string{strUDN})
	}
	err := ldapConn.Modify(modify)
	if err != nil {
		log.Println(err)
	} else {
		bR = true
	}
	return bR
}