/** * Lock an user : * <ul> * <li>Clear the password to prevent new authentication</li> * <li>Set the disabled flag.</li> * </ul> * * @param principal * User requesting the lock. * @param user * The LDAP user to disable. * @param isolate * When <code>true</code>, the user will be isolated in addition. */ private void lock(final String principal, final UserOrg user, final boolean isolate) { if (user.getLockedBy() == null) { // Not yet locked final ModificationItem[] mods = new ModificationItem[2]; final long timeInMillis = DateUtils.newCalendar().getTimeInMillis(); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(lockedAttribute, String.format("%s|%s|%s|%s|", lockedValue, timeInMillis, principal, isolate ? user.getCompany() : ""))); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(PASSWORD_ATTRIBUTE, null)); template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(user.getDn()), mods); // Also update the disabled date user.setLocked(new Date(timeInMillis)); user.setLockedBy(principal); } }
/** * Remove an "uniqueMember" from given group. Cache is not updated there. * * @param uniqueMember * DN of the member to remove. * @param group * CN of the group to update. Must be normalized. * @return the {@link GroupOrg} where the member has just been removed from. */ private GroupOrg removeMember(final ResourceOrg uniqueMember, final String group) { final GroupOrg groupLdap = findById(group); if (groupLdap.getMembers().contains(uniqueMember.getId()) || groupLdap.getSubGroups().contains(uniqueMember.getId())) { // Not useless LDAP operation, avoid LDAP duplicate deletion final ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(UNIQUE_MEMBER, uniqueMember.getDn())); try { template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(groupLdap.getDn()), mods); } catch (final org.springframework.ldap.AttributeInUseException aiue) { // Even if the membership update failed, the user does not exist anymore. A broken reference can remains // in LDAP, but this case is well managed. log.info("Unable to remove user {} from the group {} : {}", uniqueMember.getDn(), group, aiue); } catch (final org.springframework.ldap.SchemaViolationException sve) { // NOSONAR - Exception is logged // Occurs when there is a LDAP schema violation such as as last member removed log.warn("Unable to remove user {} from the group {}", uniqueMember.getDn(), group, sve); throw new ValidationJsonException("groups", "last-member-of-group", "user", uniqueMember.getId(), "group", group); } } return groupLdap; }
@Override public void addAttributes(final String dn, final String attribute, final Collection<String> values) { if (values.isEmpty()) { // Ignore this call return; } // Build the modification operation final ModificationItem[] mods = values.stream().map(v -> new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(attribute, v))) .toArray(ModificationItem[]::new); try { // Perform the addition template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(dn), mods); } catch (final org.springframework.ldap.AttributeInUseException aiue) { if (!aiue.getMessage().matches(".*(value #0 already exists|error code 20|ATTRIBUTE_OR_VALUE_EXISTS).*")) { throw aiue; } log.info("{} is already member of {}", values, dn); } }
/** * Converts an {@link Attribute} to a JNDI Attribute. * * @param attribute the {@link Attribute} to convert * @return the equivalent JNDI Attribute */ public static javax.naming.directory.Attribute toJndiAttribute( Attribute attribute ) { if ( attribute != null ) { javax.naming.directory.Attribute jndiAttribute = new BasicAttribute( attribute.getUpId() ); // Looping on values for ( Iterator<Value> valueIterator = attribute.iterator(); valueIterator.hasNext(); ) { Value value = valueIterator.next(); jndiAttribute.add( value.getValue() ); } return jndiAttribute; } return null; }
/** * Test a conversion of an attributes from a LDIF file * @throws org.apache.directory.api.ldap.model.ldif.LdapLdifException */ @Test public void testConvertAttributesfromLdif() throws LdapException, LdapLdifException { Attributes attributes = new BasicAttributes( true ); Attribute oc = new BasicAttribute( "objectclass" ); oc.add( "top" ); oc.add( "person" ); oc.add( "inetorgPerson" ); attributes.put( oc ); attributes.put( "cn", "Saarbrucken" ); attributes.put( "sn", "test" ); String ldif = LdifUtils.convertToLdif( attributes, ( Dn ) null, 15 ); Attributes result = LdifUtils.getJndiAttributesFromLdif( ldif ); assertEquals( attributes, result ); }
/** * Create the Trigger execution subentry * * @param apCtx The administration point context * @param subentryCN The CN used by the suentry * @param subtreeSpec The subtree specification * @param prescriptiveTriggerSpec The prescriptive trigger specification * @throws NamingException If the operation failed */ public static void createTriggerExecutionSubentry( LdapContext apCtx, String subentryCN, String subtreeSpec, String prescriptiveTriggerSpec ) throws NamingException { Attributes subentry = new BasicAttributes( SchemaConstants.CN_AT, subentryCN, true ); Attribute objectClass = new BasicAttribute( SchemaConstants.OBJECT_CLASS_AT ); subentry.put( objectClass ); objectClass.add( SchemaConstants.TOP_OC ); objectClass.add( SchemaConstants.SUBENTRY_OC ); objectClass.add( SchemaConstants.TRIGGER_EXECUTION_SUBENTRY_OC ); subentry.put( SchemaConstants.SUBTREE_SPECIFICATION_AT, subtreeSpec ); subentry.put( SchemaConstants.PRESCRIPTIVE_TRIGGER_SPECIFICATION_AT, prescriptiveTriggerSpec ); apCtx.createSubcontext( "cn=" + subentryCN, subentry ); }
public static Context getURLContext( String scheme, Hashtable<?,?> environment) throws NamingException { return new DnsContext("", null, new Hashtable<String,String>()) { public Attributes getAttributes(String name, String[] attrIds) throws NamingException { return new BasicAttributes() { public Attribute get(String attrID) { BasicAttribute ba = new BasicAttribute(attrID); ba.add("1 1 99 b.com."); ba.add("0 0 88 a.com."); // 2nd has higher priority return ba; } }; } }; }
public static Context getURLContext( String scheme, Hashtable<?,?> environment) throws NamingException { return new InitialDirContext() { public Attributes getAttributes(String name, String[] attrIds) throws NamingException { return new BasicAttributes() { public Attribute get(String attrID) { BasicAttribute ba = new BasicAttribute(attrID); ba.add("1 1 99 b.com."); ba.add("0 0 88 a.com."); // 2nd has higher priority return ba; } }; } }; }
/** * This seems to be required for objectClass posixGroup. */ private ApacheDS activateNis() throws Exception { Preconditions.checkState(ldapServer.isStarted()); Attribute disabled = new BasicAttribute("m-disabled", "TRUE"); Attribute disabled2 = new BasicAttribute("m-disabled", "FALSE"); ModificationItem[] mods = new ModificationItem[] { new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled), new ModificationItem(DirContext.ADD_ATTRIBUTE, disabled2) }; Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, getUrl()); DirContext ctx = new InitialDirContext(env); ctx.modifyAttributes("cn=nis,ou=schema", mods); return this; }
/** * Collect all the value from the table (Arguments), using this create the * basicAttributes. This will create the Basic Attributes for the User * defined TestCase for Add Test. * * @return the BasicAttributes */ private BasicAttributes getUserAttributes() { BasicAttribute basicattribute = new BasicAttribute("objectclass"); //$NON-NLS-1$ basicattribute.add("top"); //$NON-NLS-1$ basicattribute.add("person"); //$NON-NLS-1$ basicattribute.add("organizationalPerson"); //$NON-NLS-1$ basicattribute.add("inetOrgPerson"); //$NON-NLS-1$ BasicAttributes attrs = new BasicAttributes(true); attrs.put(basicattribute); BasicAttribute attr; for (JMeterProperty jMeterProperty : getArguments()) { Argument item = (Argument) jMeterProperty.getObjectValue(); attr = getBasicAttribute(item.getName(), item.getValue()); attrs.put(attr); } return attrs; }
/** * This will create the Basic Attributes for the In build TestCase for Add * Test. * * @return the BasicAttributes */ private BasicAttributes getBasicAttributes() { BasicAttributes basicattributes = new BasicAttributes(); BasicAttribute basicattribute = new BasicAttribute("objectclass"); //$NON-NLS-1$ basicattribute.add("top"); //$NON-NLS-1$ basicattribute.add("person"); //$NON-NLS-1$ basicattribute.add("organizationalPerson"); //$NON-NLS-1$ basicattribute.add("inetOrgPerson"); //$NON-NLS-1$ basicattributes.put(basicattribute); String s1 = "User"; //$NON-NLS-1$ String s3 = "Test"; //$NON-NLS-1$ String s5 = "user"; //$NON-NLS-1$ String s6 = "test"; //$NON-NLS-1$ counter += 1; basicattributes.put(new BasicAttribute("givenname", s1)); //$NON-NLS-1$ basicattributes.put(new BasicAttribute("sn", s3)); //$NON-NLS-1$ basicattributes.put(new BasicAttribute("cn", "TestUser" + counter)); //$NON-NLS-1$ //$NON-NLS-2$ basicattributes.put(new BasicAttribute("uid", s5)); //$NON-NLS-1$ basicattributes.put(new BasicAttribute("userpassword", s6)); //$NON-NLS-1$ setProperty(new StringProperty(ADD, "cn=TestUser" + counter)); //$NON-NLS-1$ return basicattributes; }
/** * Function for instance_admin to reset user password */ public boolean resetUserPassword(String usrDn, String pw) { DirContext context = null; try { context = getContext(); Attribute userPassword = new BasicAttribute(LdapManager.PERSON_PASSWORD, hash256(pw)); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword); context.modifyAttributes(usrDn, mods); logger.info("LdapManager info: User '"+usrDn+"' password reseted by instance_admin."); context.close(); } catch (NamingException e) { logger.error("LdapManager error: Error reseting user password, "+e); return false; } return true; }
private static Attributes toAttributes(String strAttributes,String delimiter, String separator) throws PageException { String[] arrAttr = toStringAttributes(strAttributes,delimiter); BasicAttributes attributes = new BasicAttributes(); for(int i=0; i<arrAttr.length; i++) { String strAttr = arrAttr[i]; // Type int eqIndex=strAttr.indexOf('='); Attribute attr = new BasicAttribute((eqIndex != -1)?strAttr.substring(0, eqIndex).trim():null); // Value String strValue = (eqIndex!=-1)?strAttr.substring( eqIndex+ 1):strAttr; String[] arrValue=ListUtil.toStringArray(ListUtil.listToArrayRemoveEmpty(strValue,separator)); // Fill for(int y=0; y<arrValue.length; y++) { attr.add(arrValue[y]); } attributes.put(attr); } return attributes; }
private void enableKerberoseSchema() throws DirectoryServerException { // check if krb5kdc is disabled Attributes krb5kdcAttrs; try { krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc"); boolean isKrb5KdcDisabled = false; if (krb5kdcAttrs.get("m-disabled") != null) { isKrb5KdcDisabled = "TRUE".equalsIgnoreCase((String) krb5kdcAttrs.get("m-disabled").get()); } // if krb5kdc is disabled then enable it if (isKrb5KdcDisabled) { Attribute disabled = new BasicAttribute("m-disabled"); ModificationItem[] mods = new ModificationItem[]{new ModificationItem( DirContext.REMOVE_ATTRIBUTE, disabled)}; schemaRoot.modifyAttributes("cn=Krb5kdc", mods); } } catch (NamingException e) { String msg = "An error occurred while enabling Kerberos schema."; logger.error(msg, e); throw new DirectoryServerException(msg, e); } }
/** * Convenience method for creating principals. * * @param cn the commonName of the person * @param principal the kerberos principal name for the person * @param sn the surName of the person * @param uid the unique identifier for the person * @param userPassword the credentials of the person * @return the attributes of the person principal */ protected Attributes getPrincipalAttributes(String sn, String cn, String uid, String userPassword, String principal) { Attributes attributes = new BasicAttributes(true); Attribute basicAttribute = new BasicAttribute("objectClass"); basicAttribute.add("top"); basicAttribute.add("person"); // sn $ cn basicAttribute.add("inetOrgPerson"); // uid basicAttribute.add("krb5principal"); basicAttribute.add("krb5kdcentry"); attributes.put(basicAttribute); attributes.put("cn", cn); attributes.put("sn", sn); attributes.put("uid", uid); attributes.put(SchemaConstants.USER_PASSWORD_AT, userPassword); attributes.put(KerberosAttribute.KRB5_PRINCIPAL_NAME_AT, principal); attributes.put(KerberosAttribute.KRB5_KEY_VERSION_NUMBER_AT, "0"); return attributes; }
private Attributes buildAttributes(String dn, String[] attributes, String[] values, String multValuedSeparator) { Attributes attrs = new javax.naming.directory.BasicAttributes(true); int nrAttributes = attributes.length; for (int i = 0; i < nrAttributes; i++) { if (!Const.isEmpty(values[i])) { // We have a value String value = values[i].trim(); if (multValuedSeparator != null && value.indexOf(multValuedSeparator) > 0) { Attribute attr = new javax.naming.directory.BasicAttribute(attributes[i]); for (String attribute : value.split(multValuedSeparator)) { attr.add(attribute); } attrs.put(attr); } else { attrs.put(attributes[i], value); } } } return attrs; }
/** * Adds user attribute. * @param objectDn the subject dn * @param attributeName the user attribute will be added. * @param attributeValue the user attribute value will be added. * @throws CredentialPolicyException if the credentials are invalid * @throws IdentityException if a system error occurs preventing the action * @throws NamingException if an LDAP naming exception occurs * @throws SQLException if a database communication exception occurs */ @Override public void addAttribute(String objectDn, String attributeName, String attributeValue) throws CredentialPolicyException, IdentityException, NamingException, SQLException { LdapClient client = null; try { // register the user client = newServiceConnection(); BasicAttributes ldapAttributes = new BasicAttributes(); BasicAttribute ldapAttribute = new BasicAttribute(attributeName,attributeValue); ldapAttributes.put(ldapAttribute); client.getEditFunctions().addAttribute(client.getConnectedContext(), objectDn, ldapAttributes); } finally { if (client != null) client.close(); } }
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { System.out.println("Searching Dummy LDAP Server Results:"); if (!"ou=proxyroles,dc=mycompany,dc=com".equalsIgnoreCase(name)) { System.out.println("baseName mismatch"); return new ResultEnum<SearchResult>(); } if (!"cn=127.0.0.1".equals((String) matchingAttributes.get("uniqueMember") .get())) { System.out.println("Ip address mismatch"); return new ResultEnum<SearchResult>(); } BasicAttributes attrs = new BasicAttributes(); BasicAttribute uidAttr = new BasicAttribute("uid", "testuser"); attrs.put(uidAttr); BasicAttribute groupAttr = new BasicAttribute("userClass", "testgroup"); attrs.put(groupAttr); BasicAttribute locAttr = new BasicAttribute("documentLocation", "/testdir"); attrs.put(locAttr); SearchResult sr = new SearchResult(null, null, attrs); ArrayList<SearchResult> al = new ArrayList<SearchResult>(); al.add(sr); NamingEnumeration<SearchResult> ne = new ResultEnum<SearchResult>(al); return ne; }
/** * A list of attributes, each attribute can contain more than one value * * @return a list of Attribute */ public List toAttributeList() { List list = new ArrayList(); for (Iterator iter = keySet().iterator(); iter.hasNext();) { ValueWrapper element = (ValueWrapper) iter.next(); BasicAttribute ba = new BasicAttribute(element.getStringValue(), true); List list2 = (List) attributes.get(element); for (Iterator iterator = list2.iterator(); iterator.hasNext();) { ValueWrapper elementList = (ValueWrapper) iterator.next(); ba.add(elementList.getValue()); } list.add(ba); } return list; }
public void testClone_IgnoreCase() { int count = 5; Attribute[] attributes = new Attribute[count]; for (int i = 0; i < count; i++) { Person person = Person.getInstance(); attributes[i] = new BasicAttribute(person.getName(), person); ignoreCaseAttributes.put(attributes[i]); } BasicAttributes cloneAttributes = (BasicAttributes) ignoreCaseAttributes .clone(); assertEquals(cloneAttributes, ignoreCaseAttributes); for (Attribute element : attributes) { element.getID(); } cloneAttributes.put("newID", "new Obj"); assertEquals(ignoreCaseAttributes.size() + 1, cloneAttributes.size()); }
public void testGet_IgnoreCase_Simple() { int count = 5; Attribute[] attributes = new Attribute[count]; for (int i = 0; i < count; i++) { Person person = Person.getInstance(); attributes[i] = new BasicAttribute(person.getName(), person); ignoreCaseAttributes.put(attributes[i]); } for (int i = 0; i < count; i++) { Attribute attribute = ignoreCaseAttributes.get(attributes[i] .getID().toUpperCase()); assertEquals(attributes[i], attribute); } assertNull(ignoreCaseAttributes.get("Not existing value")); }
public void testGet_CaseSensitive_Simple() { int count = 5; Attribute[] attributes = new Attribute[count]; for (int i = 0; i < count; i++) { Person person = Person.getInstance(); attributes[i] = new BasicAttribute(person.getName(), person); caseSensitiveAttributes.put(attributes[i]); } for (int i = 0; i < count; i++) { Attribute attribute = caseSensitiveAttributes.get(attributes[i] .getID()); assertEquals(attributes[i], attribute); } assertNull(caseSensitiveAttributes.get("Not existing value")); }
public void testSerializable_Simple() throws ClassNotFoundException, IOException { int count = 5; Person[] persons = new Person[count]; for (int i = 0; i < count; i++) { persons[i] = Person.getInstance(); unorderedAttribute.add(persons[i]); } // write to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(unorderedAttribute); byte[] buffer = baos.toByteArray(); // read from byte array ByteArrayInputStream bais = new ByteArrayInputStream(buffer); ObjectInputStream ois = new ObjectInputStream(bais); BasicAttribute attribute2 = (BasicAttribute) ois.readObject(); assertEquals(unorderedAttribute, attribute2); }
public Attributes toAttributes() { BasicAttributes bas = new BasicAttributes(true); for (Iterator<Attribute> iter = list.iterator(); iter.hasNext();) { Attribute attr = iter.next(); BasicAttribute ba = new BasicAttribute(attr.getID(), false); try { NamingEnumeration nameEnum = attr.getAll(); while (nameEnum.hasMore()) { ba.add(nameEnum.next()); } } catch (NamingException ne) { } bas.put(ba); } return bas; }
/** * 1. ignoreCase=true 2. Normal values */ public void testEquals_ignoreCase() { BasicAttributes basicAttributes0 = new BasicAttributes(true); BasicAttributes basicAttributes1 = new BasicAttributes(true); int count = 10; BasicAttribute attribute[] = new BasicAttribute[count]; for (int i = 0; i < count; i++) { attribute[i] = new BasicAttribute("ID:" + i, "Value: " + i); basicAttributes0.put(attribute[i]); basicAttributes1.put(attribute[i]); } assertTrue(basicAttributes0.equals(basicAttributes1)); assertTrue(basicAttributes1.equals(basicAttributes0)); assertFalse(basicAttributes0.equals(null)); basicAttributes0.remove("ID:0"); assertFalse(basicAttributes0.equals(basicAttributes1)); assertFalse(basicAttributes1.equals(basicAttributes0)); }
public void testSerializable_Simple() throws ClassNotFoundException, IOException { int count = 10; BasicAttribute attribute[] = new BasicAttribute[count]; for (int i = 0; i < count; i++) { attribute[i] = new BasicAttribute("ID:" + i, "Value: " + i); caseSensitiveAttributes.put(attribute[i]); } // write to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(caseSensitiveAttributes); byte[] buffer = baos.toByteArray(); // read from byte array ByteArrayInputStream bais = new ByteArrayInputStream(buffer); ObjectInputStream ois = new ObjectInputStream(bais); BasicAttributes attributes2 = (BasicAttributes) ois.readObject(); assertEquals(caseSensitiveAttributes, attributes2); }
public void testSerializable_compatibility() throws ClassNotFoundException, IOException { ObjectInputStream ois = new ObjectInputStream( getClass() .getClassLoader() .getResourceAsStream( "/serialization/javax/naming/directory/BasicAttributes.ser")); BasicAttributes attributes2 = (BasicAttributes) ois.readObject(); int count = 10; BasicAttribute attribute[] = new BasicAttribute[count]; for (int i = 0; i < count; i++) { attribute[i] = new BasicAttribute("ID:" + i, "Value: " + i); caseSensitiveAttributes.put(attribute[i]); } assertEquals(caseSensitiveAttributes, attributes2); }
@Override public boolean updatePassword(UserAccount login, String newPasswd) { if (login == null) return false; String username = login.getLogin(); log.trace("changePassword called for account: {}", username); ModificationItem[] mod = new ModificationItem[1]; Attribute attr = new BasicAttribute("userpassword", newPasswd); mod[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr); final String dn = configurationService.getStringConfiguration(CONF_DN, "{login}") .replaceAll(Pattern.quote("{login}"), username); try { // ctx.modifyAttributes(dn, mod); // log.info("LDAP-Passwd update for {} successful ({})", username, dn); // return true; } catch (Exception e) { log.info("LDAP-Passwd update for {} failed ({})", username, dn); } log.warn("LDAP-Passwd update not implemented"); return false; }
public void testClone_unordered() throws NamingException { int count = 5; Person[] persons = new Person[count]; for (int i = 0; i < count; i++) { persons[i] = Person.getInstance(); unorderedAttribute.add(persons[i]); } BasicAttribute cloneAttribute = (BasicAttribute) unorderedAttribute .clone(); for (int i = 0; i < count; i++) { assertSame(unorderedAttribute.get(i), cloneAttribute.get(i)); } assertFalse(cloneAttribute.isOrdered()); assertEquals(unorderedAttribute.getID(), cloneAttribute.getID()); // assertNotSame(unorderedAttribute.values, cloneAttribute.values); cloneAttribute.add("new object"); assertEquals(unorderedAttribute.size() + 1, cloneAttribute.size()); }
public void testEquals_Array() throws CloneNotSupportedException { int count = 5; Person[] persons = new Person[count]; for (int i = 0; i < count; i++) { persons[i] = Person.getInstance(); } Person[] newPersons = new Person[count]; System.arraycopy(persons, 0, newPersons, 0, count); String id = "Array Attribute"; BasicAttribute attribute0 = new BasicAttribute(id, persons, true); BasicAttribute attribute1 = new BasicAttribute(id, newPersons, true); assertTrue(attribute0.equals(attribute1)); assertTrue(attribute1.equals(attribute0)); assertFalse(attribute0.equals(null)); }