|
| 1 | +import java.util.Hashtable |
| 2 | +import javax.naming.Context |
| 3 | +import javax.naming.NamingEnumeration |
| 4 | +import javax.naming.NamingException |
| 5 | +import javax.naming.directory.* |
| 6 | +import javax.naming.ldap.* |
| 7 | +import jenkins.model.Jenkins; |
| 8 | +import nectar.plugins.rbac.strategy.*; |
| 9 | +import hudson.security.*; |
| 10 | +import nectar.plugins.rbac.groups.*; |
| 11 | +import nectar.plugins.rbac.roles.*; |
| 12 | + |
| 13 | + |
| 14 | +try { |
| 15 | + String ldapAdServer = "ldap://192.0.2.36:389" |
| 16 | + String ldapSearchBase = "dc=example,dc=com" |
| 17 | + |
| 18 | + String ldapUsername = "CN=tesla,CN=Users,DC=example,DC=com" |
| 19 | + String ldapPassword = "Password12" |
| 20 | + |
| 21 | + String searchFilter = "(& (cn=*) (objectclass=group))" |
| 22 | + |
| 23 | + |
| 24 | + Hashtable<String, Object> env = new Hashtable<String, Object>() |
| 25 | + env.put(Context.SECURITY_AUTHENTICATION, "simple") |
| 26 | + if(ldapUsername != null) { |
| 27 | + env.put(Context.SECURITY_PRINCIPAL, ldapUsername) |
| 28 | + } |
| 29 | + if(ldapPassword != null) { |
| 30 | + env.put(Context.SECURITY_CREDENTIALS, ldapPassword) |
| 31 | + } |
| 32 | + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory") |
| 33 | + env.put(Context.PROVIDER_URL, ldapAdServer) |
| 34 | + |
| 35 | + DirContext ctx = new InitialDirContext(env); |
| 36 | + |
| 37 | + SearchControls searchControls = new SearchControls() |
| 38 | + searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE) |
| 39 | + |
| 40 | + NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls) |
| 41 | + |
| 42 | +//RBAC integration |
| 43 | + RoleMatrixAuthorizationStrategyImpl strategy = RoleMatrixAuthorizationStrategyImpl.getInstance() |
| 44 | + RoleMatrixAuthorizationConfig config = RoleMatrixAuthorizationPlugin.getConfig() |
| 45 | + GroupContainer container = GroupContainerLocator.locate(Jenkins.getInstance()) |
| 46 | + |
| 47 | + List<Group> groups = config.getGroups(); |
| 48 | + Set<String> groupNames = new HashSet<String>() |
| 49 | + groups.each{ g -> groupNames.add(g.name) } |
| 50 | + |
| 51 | + SearchResult searchResult = null |
| 52 | + List<String> ldapGroups = new ArrayList<String>() |
| 53 | + results.each{ result -> |
| 54 | + String name = result.getAttributes().get('name') |
| 55 | + if(!groupNames.contains(name)){ |
| 56 | + println 'Group to Add ' + name |
| 57 | + Group group = new Group(container, name) |
| 58 | + container.addGroup(group) |
| 59 | + } else { |
| 60 | + println 'Group exists ' + name |
| 61 | + groupNames.remove(name) |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + println 'Groups not in LDAP ' |
| 66 | + groupNames.each{ |
| 67 | + println '\t' + it |
| 68 | + } |
| 69 | +} catch (NamingException e) { |
| 70 | + println("Problem getting attribute:" + e.getMessage()) |
| 71 | +} |
0 commit comments