format code

This commit is contained in:
Peter Hormanns 2019-07-16 20:32:31 +02:00
parent 904f4c330f
commit 22dd341de7
31 changed files with 1649 additions and 1652 deletions

View File

@ -6,40 +6,40 @@ import java.util.List;
public class Group implements Serializable, LDAPBean {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private String dn;
private String name;
private List<String> members;
private String dn;
private String name;
private List<String> members;
public Group() {
members = new ArrayList<String>();
}
public Group() {
members = new ArrayList<>();
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getMembers() {
return members;
}
public List<String> getMembers() {
return members;
}
public void setMembers(List<String> members) {
this.members = members;
}
public void setMembers(List<String> members) {
this.members = members;
}
@Override
public String getDn() {
return dn;
}
@Override
public String getDn() {
return dn;
}
@Override
public void setDn(String dn) {
this.dn = dn;
}
@Override
public void setDn(String dn) {
this.dn = dn;
}
}

View File

@ -2,8 +2,8 @@ package de.jalin.ldapadmin.beans;
public interface LDAPBean {
public String getDn();
public String getDn();
public void setDn(String dn);
public void setDn(String dn);
}

View File

@ -2,26 +2,26 @@ package de.jalin.ldapadmin.beans;
public class MembershipCheck {
private User user;
private Group group;
private User user;
private Group group;
public User getUser() {
return user;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void setUser(User user) {
this.user = user;
}
public Group getGroup() {
return group;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public void setGroup(Group group) {
this.group = group;
}
public String getChecked() {
return user != null && group != null && user.getGroups().contains(group.getDn()) ? "checked" : ""; //$NON-NLS-1$ //$NON-NLS-2$
}
public String getChecked() {
return user != null && group != null && user.getGroups().contains(group.getDn()) ? "checked" : ""; //$NON-NLS-1$ //$NON-NLS-2$
}
}

View File

@ -9,118 +9,118 @@ import de.jalin.ldapadmin.ldap.SimplePasswordException;
public class User implements Serializable, LDAPBean {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private String dn;
private String login;
private String password;
private String firstname;
private String lastname;
private String displayname;
private String email;
private String phone;
private String mobile;
private List<String> groups;
private String dn;
private String login;
private String password;
private String firstname;
private String lastname;
private String displayname;
private String email;
private String phone;
private String mobile;
private List<String> groups;
public User() {
groups = new ArrayList<String>();
}
public User() {
groups = new ArrayList<String>();
}
public User(final String login) {
this.login = login;
groups = new ArrayList<String>();
}
public User(final String login) {
this.login = login;
groups = new ArrayList<String>();
}
public String getLogin() {
return login;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setPassword(String password) {
this.password = password;
}
public void setAndValidatePassword(String password) throws SimplePasswordException {
final PasswordValidator validator = new PasswordValidator();
validator.validate(password);
this.password = password;
}
public void setAndValidatePassword(String password) throws SimplePasswordException {
final PasswordValidator validator = new PasswordValidator();
validator.validate(password);
this.password = password;
}
public String getFirstname() {
return firstname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getDisplayname() {
return displayname;
}
public String getDisplayname() {
return displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public String getEmail() {
return email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public List<String> getGroups() {
return groups;
}
public List<String> getGroups() {
return groups;
}
public void setGroups(List<String> groups) {
this.groups = groups;
}
public void setGroups(List<String> groups) {
this.groups = groups;
}
@Override
public String toString() {
return getFirstname() + " " + getLastname() + " (" + getLogin() + ", " + getEmail() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
@Override
public String toString() {
return getFirstname() + " " + getLastname() + " (" + getLogin() + ", " + getEmail() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
@Override
public String getDn() {
return dn;
}
@Override
public String getDn() {
return dn;
}
@Override
public void setDn(String dn) {
this.dn = dn;
}
@Override
public void setDn(String dn) {
this.dn = dn;
}
}

View File

@ -2,22 +2,22 @@ package de.jalin.ldapadmin.beans;
public class ValidationException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private final String fieldname;
private final String condition;
private final String fieldname;
private final String condition;
public ValidationException(final String fieldname, final String condition) {
this.fieldname = fieldname;
this.condition = condition;
}
public ValidationException(final String fieldname, final String condition) {
this.fieldname = fieldname;
this.condition = condition;
}
public String getFieldname() {
return fieldname;
}
public String getFieldname() {
return fieldname;
}
public String getCondition() {
return condition;
}
public String getCondition() {
return condition;
}
}

View File

@ -2,16 +2,16 @@ package de.jalin.ldapadmin.ldap;
public class AlreadyBoundException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private final String name;
private final String name;
public AlreadyBoundException(final String name) {
this.name = name;
}
public AlreadyBoundException(final String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
}

View File

@ -16,110 +16,106 @@ import de.jalin.ldapadmin.beans.User;
public class GroupsDAO {
private final LDAPSession session;
private final LDAPSession session;
public GroupsDAO(final LDAPSession session) {
this.session = session;
}
public GroupsDAO(final LDAPSession session) {
this.session = session;
}
public SortedMap<String, Group> loadGroups(final SortedMap<String, User> users) throws LDAPSessionException
{
final SortedMap<String, Group> list = new TreeMap<String, Group>();
final List<SearchResult> searchResult = session.search("ou=groups"); //$NON-NLS-1$
for (final SearchResult result : searchResult) {
final Attributes attribs = result.getAttributes();
final Group grp = new Group();
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
grp.setDn(result.getNameInNamespace());
final List<String> listOfMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
final String dn = grp.getDn();
for (String userDN : listOfMembers) {
final User user = users.get(userDN);
final List<String> groups = user.getGroups();
groups.add(dn);
}
grp.setMembers(listOfMembers);
list.put(dn, grp);
}
return list;
}
public SortedMap<String, Group> loadGroups(final SortedMap<String, User> users) throws LDAPSessionException {
final SortedMap<String, Group> list;
list = new TreeMap<>();
final List<SearchResult> searchResult = session.search("ou=groups"); //$NON-NLS-1$
for (final SearchResult result : searchResult) {
final Attributes attribs = result.getAttributes();
final Group grp = new Group();
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
grp.setDn(result.getNameInNamespace());
final List<String> listOfMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
final String dn = grp.getDn();
listOfMembers.stream().map((userDN) -> users.get(userDN)).map((user) -> user.getGroups()).forEachOrdered((groups) -> {
groups.add(dn);
});
grp.setMembers(listOfMembers);
list.put(dn, grp);
}
return list;
}
public void create(final Group grp) throws LDAPSessionException, AlreadyBoundException {
assert grp != null;
final String name = grp.getName();
assert name != null;
final BasicAttributes attributes = new BasicAttributes();
final BasicAttribute objClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
objClass.add("top"); //$NON-NLS-1$
objClass.add("groupOfUniqueNames"); //$NON-NLS-1$
attributes.put(objClass);
attributes.put("cn", name); //$NON-NLS-1$
final List<String> uniqueMembers = grp.getMembers();
final BasicAttribute uniqMembers = new BasicAttribute("uniqueMember"); //$NON-NLS-1$
if (uniqueMembers != null && uniqueMembers.size() > 0) {
for (String dn : uniqueMembers) {
uniqMembers.add(dn);
}
}
attributes.put(uniqMembers);
final String dn = session.createSubcontext("cn=${cn},ou=groups".replace("${cn}", name), attributes); //$NON-NLS-1$ //$NON-NLS-2$
grp.setDn(dn);
}
public void create(final Group grp) throws LDAPSessionException, AlreadyBoundException {
assert grp != null;
final String name = grp.getName();
assert name != null;
final BasicAttributes attributes = new BasicAttributes();
final BasicAttribute objClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
objClass.add("top"); //$NON-NLS-1$
objClass.add("groupOfUniqueNames"); //$NON-NLS-1$
attributes.put(objClass);
attributes.put("cn", name); //$NON-NLS-1$
final List<String> uniqueMembers = grp.getMembers();
final BasicAttribute uniqMembers = new BasicAttribute("uniqueMember"); //$NON-NLS-1$
if (uniqueMembers != null && uniqueMembers.size() > 0) {
uniqueMembers.forEach((dn) -> {
uniqMembers.add(dn);
});
}
attributes.put(uniqMembers);
final String dn = session.createSubcontext("cn=${cn},ou=groups".replace("${cn}", name), attributes); //$NON-NLS-1$ //$NON-NLS-2$
grp.setDn(dn);
}
public Group readGroup(final String dn, final SortedMap<String, User> users) throws LDAPSessionException {
final Attributes attribs = session.getAttributes(dn.substring(0, dn.indexOf("ou=groups") + 9)); //$NON-NLS-1$
final Group grp = new Group();
grp.setDn(dn);
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
final List<String> listOfMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
for (String userDN : listOfMembers) {
final User user = users.get(userDN);
final List<String> groups = user.getGroups();
groups.add(dn);
}
grp.setMembers(listOfMembers);
return grp;
}
public Group readGroup(final String dn, final SortedMap<String, User> users) throws LDAPSessionException {
final Attributes attribs = session.getAttributes(dn.substring(0, dn.indexOf("ou=groups") + 9)); //$NON-NLS-1$
final Group grp = new Group();
grp.setDn(dn);
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
final List<String> listOfMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
listOfMembers.stream().map((userDN) -> users.get(userDN)).map((user) -> user.getGroups()).forEachOrdered((groups) -> {
groups.add(dn);
});
grp.setMembers(listOfMembers);
return grp;
}
public void update(final Group grp) throws LDAPSessionException, NoGroupMembersException {
assert grp != null;
final String name = grp.getName();
assert name != null;
if (grp.getMembers().size() == 0) {
throw new NoGroupMembersException(name);
}
final BasicAttribute membersOfAttrib = new BasicAttribute("uniqueMember"); //$NON-NLS-1$
for (final String memberDN : grp.getMembers()) {
membersOfAttrib.add(memberDN);
}
final ModificationItem modificationItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, membersOfAttrib);
session.modifyAttributes("cn=${cn},ou=groups".replace("${cn}", name), new ModificationItem[] { modificationItem }); //$NON-NLS-1$ //$NON-NLS-2$
}
public void update(final Group grp) throws LDAPSessionException, NoGroupMembersException {
assert grp != null;
final String name = grp.getName();
assert name != null;
if (grp.getMembers().isEmpty()) {
throw new NoGroupMembersException(name);
}
final BasicAttribute membersOfAttrib = new BasicAttribute("uniqueMember"); //$NON-NLS-1$
grp.getMembers().forEach((memberDN) -> {
membersOfAttrib.add(memberDN);
});
final ModificationItem modificationItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, membersOfAttrib);
session.modifyAttributes("cn=${cn},ou=groups".replace("${cn}", name), new ModificationItem[]{modificationItem}); //$NON-NLS-1$ //$NON-NLS-2$
}
public void updateMemberships(final User usr) throws LDAPSessionException, NoGroupMembersException {
final List<SearchResult> searchResult = session.search("ou=groups"); //$NON-NLS-1$
for (final SearchResult result : searchResult) {
final Attributes attribs = result.getAttributes();
final Group grp = new Group();
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
grp.setDn(result.getNameInNamespace());
final List<String> listOfGroupMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
grp.setMembers(listOfGroupMembers);
final List<String> listOfUserMemberships = usr.getGroups();
if (listOfGroupMembers.contains(usr.getDn()) && !listOfUserMemberships.contains(grp.getDn())) {
grp.getMembers().remove(usr.getDn());
update(grp);
}
if (!listOfGroupMembers.contains(usr.getDn()) && listOfUserMemberships.contains(grp.getDn())) {
grp.getMembers().add(usr.getDn());
update(grp);
}
}
}
public void updateMemberships(final User usr) throws LDAPSessionException, NoGroupMembersException {
final List<SearchResult> searchResult = session.search("ou=groups"); //$NON-NLS-1$
for (final SearchResult result : searchResult) {
final Attributes attribs = result.getAttributes();
final Group grp = new Group();
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
grp.setDn(result.getNameInNamespace());
final List<String> listOfGroupMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
grp.setMembers(listOfGroupMembers);
final List<String> listOfUserMemberships = usr.getGroups();
if (listOfGroupMembers.contains(usr.getDn()) && !listOfUserMemberships.contains(grp.getDn())) {
grp.getMembers().remove(usr.getDn());
update(grp);
}
if (!listOfGroupMembers.contains(usr.getDn()) && listOfUserMemberships.contains(grp.getDn())) {
grp.getMembers().add(usr.getDn());
update(grp);
}
}
}
public void delete(final Group grp) throws LDAPSessionException {
assert grp != null;
session.unbind("cn=${id},ou=groups", grp.getName()); //$NON-NLS-1$
}
public void delete(final Group grp) throws LDAPSessionException {
assert grp != null;
session.unbind("cn=${id},ou=groups", grp.getName()); //$NON-NLS-1$
}
}

View File

@ -20,163 +20,166 @@ import javax.naming.directory.SearchResult;
public class LDAPSession {
private InitialDirContext ctx;
private InitialDirContext ctx;
public LDAPSession(final String providerURL, final String principal, final String password) throws LDAPSessionException {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
env.put("com.sun.jndi.ldap.connect.pool", "true"); //$NON-NLS-1$ //$NON-NLS-2$
env.put(Context.PROVIDER_URL, providerURL);
env.put(Context.SECURITY_AUTHENTICATION, "simple"); //$NON-NLS-1$
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
ctx = new InitialDirContext(env);
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
createOrgUnitNodesIfNotExist();
}
public LDAPSession(final String providerURL, final String principal, final String password) throws LDAPSessionException {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
env.put("com.sun.jndi.ldap.connect.pool", "true"); //$NON-NLS-1$ //$NON-NLS-2$
env.put(Context.PROVIDER_URL, providerURL);
env.put(Context.SECURITY_AUTHENTICATION, "simple"); //$NON-NLS-1$
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
ctx = new InitialDirContext(env);
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
createOrgUnitNodesIfNotExist();
}
public String getStringValue(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName);
if (attribute == null) {
return null;
}
try {
return (String) attribute.get();
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public String getStringValue(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName);
if (attribute == null) {
return null;
}
try {
return (String) attribute.get();
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public byte[] getBytesValue(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName);
if (attribute == null) {
return null;
}
try {
return (byte[]) attribute.get();
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public byte[] getBytesValue(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName);
if (attribute == null) {
return null;
}
try {
return (byte[]) attribute.get();
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public List<String> getListOfValues(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName);
if (attribute == null) {
return null;
}
try {
final int size = attribute.size();
List<String> listOfValues = new ArrayList<String>();
for (int idx = 0; idx < size; idx++) {
listOfValues.add((String) attribute.get(idx));
}
return listOfValues;
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public List<String> getListOfValues(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName);
if (attribute == null) {
return null;
}
try {
final int size = attribute.size();
List<String> listOfValues;
listOfValues = new ArrayList<>();
for (int idx = 0; idx < size; idx++) {
listOfValues.add((String) attribute.get(idx));
}
return listOfValues;
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public String createSubcontext(final String subcontext, final BasicAttributes attributes) throws LDAPSessionException, AlreadyBoundException {
try {
final DirContext dirContext = ctx.createSubcontext(subcontext, attributes);
return dirContext.getNameInNamespace();
} catch (NameAlreadyBoundException e) {
throw new AlreadyBoundException(subcontext);
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public String createSubcontext(final String subcontext, final BasicAttributes attributes) throws LDAPSessionException, AlreadyBoundException {
try {
final DirContext dirContext = ctx.createSubcontext(subcontext, attributes);
return dirContext.getNameInNamespace();
} catch (NameAlreadyBoundException e) {
throw new AlreadyBoundException(subcontext);
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public List<SearchResult> search(final String name, final String attribName, final String attribValue) throws LDAPSessionException {
final List<SearchResult> searchResult = new ArrayList<SearchResult>();
try {
Attributes matchingAttributes = new BasicAttributes();
matchingAttributes.put(attribName, attribValue);
final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, matchingAttributes);
while (searchEnum.hasMore()) {
searchResult.add(searchEnum.next());
}
return searchResult;
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public List<SearchResult> search(final String name, final String attribName, final String attribValue) throws LDAPSessionException {
final List<SearchResult> searchResult;
searchResult = new ArrayList<>();
try {
Attributes matchingAttributes = new BasicAttributes();
matchingAttributes.put(attribName, attribValue);
final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, matchingAttributes);
while (searchEnum.hasMore()) {
searchResult.add(searchEnum.next());
}
return searchResult;
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public List<SearchResult> search(final String name) throws LDAPSessionException {
final List<SearchResult> searchResult = new ArrayList<SearchResult>();
try {
final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, null);
while (searchEnum.hasMore()) {
searchResult.add(searchEnum.next());
}
return searchResult;
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public List<SearchResult> search(final String name) throws LDAPSessionException {
final List<SearchResult> searchResult;
searchResult = new ArrayList<>();
try {
final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, null);
while (searchEnum.hasMore()) {
searchResult.add(searchEnum.next());
}
return searchResult;
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public Attributes getAttributes(final String dn) throws LDAPSessionException {
try {
return ctx.getAttributes(dn);
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public Attributes getAttributes(final String dn) throws LDAPSessionException {
try {
return ctx.getAttributes(dn);
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public void modifyAttributes(final String name, final ModificationItem[] mods) throws LDAPSessionException {
try {
ctx.modifyAttributes(name, mods);
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
public void modifyAttributes(final String name, final ModificationItem[] mods) throws LDAPSessionException {
try {
ctx.modifyAttributes(name, mods);
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
}
public void unbind(final String searchPattern, final String id) throws LDAPSessionException {
try {
ctx.unbind(searchPattern.replace("${id}", id)); //$NON-NLS-1$
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public void unbind(final String searchPattern, final String id) throws LDAPSessionException {
try {
ctx.unbind(searchPattern.replace("${id}", id)); //$NON-NLS-1$
} catch (NamingException e) {
throw new LDAPSessionException(e);
}
}
public void close() throws NamingException {
if (ctx != null) {
ctx.close();
ctx = null;
}
}
public void close() throws NamingException {
if (ctx != null) {
ctx.close();
ctx = null;
}
}
private void createOrgUnitNodesIfNotExist() throws LDAPSessionException {
try {
final BasicAttributes usersAttributes = new BasicAttributes();
final BasicAttribute usersObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
usersObjClass.add("top"); //$NON-NLS-1$
usersObjClass.add("organizationalUnit"); //$NON-NLS-1$
usersAttributes.put(usersObjClass);
usersAttributes.put("ou", "users"); //$NON-NLS-1$ //$NON-NLS-2$
ctx.createSubcontext("ou=users", usersAttributes); //$NON-NLS-1$
} catch (NamingException e) {
if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) {
throw new LDAPSessionException(e);
}
}
try {
final BasicAttributes groupsAttributes = new BasicAttributes();
final BasicAttribute groupsObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
groupsObjClass.add("top"); //$NON-NLS-1$
groupsObjClass.add("organizationalUnit"); //$NON-NLS-1$
groupsAttributes.put(groupsObjClass);
groupsAttributes.put("ou", "groups"); //$NON-NLS-1$ //$NON-NLS-2$
ctx.createSubcontext("ou=groups", groupsAttributes); //$NON-NLS-1$
} catch (NamingException e) {
if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) {
throw new LDAPSessionException(e);
}
}
}
private void createOrgUnitNodesIfNotExist() throws LDAPSessionException {
try {
final BasicAttributes usersAttributes = new BasicAttributes();
final BasicAttribute usersObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
usersObjClass.add("top"); //$NON-NLS-1$
usersObjClass.add("organizationalUnit"); //$NON-NLS-1$
usersAttributes.put(usersObjClass);
usersAttributes.put("ou", "users"); //$NON-NLS-1$ //$NON-NLS-2$
ctx.createSubcontext("ou=users", usersAttributes); //$NON-NLS-1$
} catch (NamingException e) {
if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) {
throw new LDAPSessionException(e);
}
}
try {
final BasicAttributes groupsAttributes = new BasicAttributes();
final BasicAttribute groupsObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
groupsObjClass.add("top"); //$NON-NLS-1$
groupsObjClass.add("organizationalUnit"); //$NON-NLS-1$
groupsAttributes.put(groupsObjClass);
groupsAttributes.put("ou", "groups"); //$NON-NLS-1$ //$NON-NLS-2$
ctx.createSubcontext("ou=groups", groupsAttributes); //$NON-NLS-1$
} catch (NamingException e) {
if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) {
throw new LDAPSessionException(e);
}
}
}
}

View File

@ -4,10 +4,10 @@ import javax.naming.NamingException;
public class LDAPSessionException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public LDAPSessionException(NamingException e) {
super(e);
}
public LDAPSessionException(NamingException e) {
super(e);
}
}

View File

@ -2,16 +2,16 @@ package de.jalin.ldapadmin.ldap;
public class NoGroupMembersException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private final String groupName;
private final String groupName;
public NoGroupMembersException(final String name) {
groupName = name;
}
public NoGroupMembersException(final String name) {
groupName = name;
}
public String getGroupName() {
return groupName;
}
public String getGroupName() {
return groupName;
}
}

View File

@ -1,40 +1,41 @@
package de.jalin.ldapadmin.ldap;
public class PasswordValidator {
private static final int MIN_PASSWORD_LEN = 6;
private static final int MIN_PASSWORD_LEN = 6;
public void validate(final String password) throws SimplePasswordException {
if (password == null || password.isEmpty()) {
throw new SimplePasswordException("password required");
}
if (password.length() < MIN_PASSWORD_LEN) {
throw new SimplePasswordException("minimal password length is " + MIN_PASSWORD_LEN + " characters");
}
int hasLowerCaseChar = 0;
int hasUpperCaseChar = 0;
int hasDigits = 0;
int hasSpecialChar = 0;
for (int idx = 0; idx < password.length(); idx++) {
final char test = password.charAt(idx);
final int type = Character.getType(test);
if (type == Character.DECIMAL_DIGIT_NUMBER) {
hasDigits = 1;
} else {
if (type == Character.LOWERCASE_LETTER) {
hasLowerCaseChar = 1;
} else
if (type == Character.UPPERCASE_LETTER) {
hasUpperCaseChar = 1;
} else
hasSpecialChar = 1;
}
}
if (hasDigits + hasLowerCaseChar + hasUpperCaseChar + hasSpecialChar < 3) {
throw new SimplePasswordException("a password requires 3 out of 4 "
+ "different character types: lowercase, uppercase, digits and special characters");
}
}
public void validate(final String password) throws SimplePasswordException {
if (password == null || password.isEmpty()) {
throw new SimplePasswordException("password required");
}
if (password.length() < MIN_PASSWORD_LEN) {
throw new SimplePasswordException("minimal password length is " + MIN_PASSWORD_LEN + " characters");
}
int hasLowerCaseChar = 0;
int hasUpperCaseChar = 0;
int hasDigits = 0;
int hasSpecialChar = 0;
for (int idx = 0; idx < password.length(); idx++) {
final char test = password.charAt(idx);
final int type = Character.getType(test);
if (type == Character.DECIMAL_DIGIT_NUMBER) {
hasDigits = 1;
} else {
if (type == Character.LOWERCASE_LETTER) {
hasLowerCaseChar = 1;
} else {
if (type == Character.UPPERCASE_LETTER) {
hasUpperCaseChar = 1;
} else {
hasSpecialChar = 1;
}
}
}
}
if (hasDigits + hasLowerCaseChar + hasUpperCaseChar + hasSpecialChar < 3) {
throw new SimplePasswordException("a password requires 3 out of 4 "
+ "different character types: lowercase, uppercase, digits and special characters");
}
}
}

View File

@ -2,15 +2,15 @@ package de.jalin.ldapadmin.ldap;
public class RequiredAttributeException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private final String fieldname;
private final String fieldname;
public RequiredAttributeException(final String fieldname) {
this.fieldname = fieldname;
}
public RequiredAttributeException(final String fieldname) {
this.fieldname = fieldname;
}
public String getFieldname() {
return fieldname;
}
public String getFieldname() {
return fieldname;
}
}

View File

@ -2,10 +2,10 @@ package de.jalin.ldapadmin.ldap;
public class SimplePasswordException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public SimplePasswordException(final String message) {
super(message);
}
public SimplePasswordException(final String message) {
super(message);
}
}

View File

@ -16,153 +16,152 @@ import de.jalin.ldapadmin.beans.User;
public class UsersDAO {
private final LDAPSession session;
private final LDAPSession session;
public UsersDAO(final LDAPSession session) {
this.session = session;
}
public UsersDAO(final LDAPSession session) {
this.session = session;
}
public SortedMap<String, User> loadUsers() throws LDAPSessionException
{
final SortedMap<String, User> usersHash = new TreeMap<String, User>();
final List<SearchResult> enumeration = session.search("ou=users"); //$NON-NLS-1$
for (SearchResult result : enumeration) {
final Attributes attribs = result.getAttributes();
final User usr = new User();
usr.setFirstname(session.getStringValue(attribs, "givenName")); //$NON-NLS-1$
usr.setLastname(session.getStringValue(attribs, "sn")); //$NON-NLS-1$
usr.setEmail(session.getStringValue(attribs, "mail")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setPhone(session.getStringValue(attribs, "telephoneNumber")); //$NON-NLS-1$
usr.setMobile(session.getStringValue(attribs, "mobile")); //$NON-NLS-1$
usr.setDisplayname(session.getStringValue(attribs, "displayName")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setDn(result.getNameInNamespace());
usersHash.put(usr.getDn(), usr);
}
return usersHash;
}
public SortedMap<String, User> loadUsers() throws LDAPSessionException {
final SortedMap<String, User> usersHash = new TreeMap<String, User>();
final List<SearchResult> enumeration = session.search("ou=users"); //$NON-NLS-1$
for (SearchResult result : enumeration) {
final Attributes attribs = result.getAttributes();
final User usr = new User();
usr.setFirstname(session.getStringValue(attribs, "givenName")); //$NON-NLS-1$
usr.setLastname(session.getStringValue(attribs, "sn")); //$NON-NLS-1$
usr.setEmail(session.getStringValue(attribs, "mail")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setPhone(session.getStringValue(attribs, "telephoneNumber")); //$NON-NLS-1$
usr.setMobile(session.getStringValue(attribs, "mobile")); //$NON-NLS-1$
usr.setDisplayname(session.getStringValue(attribs, "displayName")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setDn(result.getNameInNamespace());
usersHash.put(usr.getDn(), usr);
}
return usersHash;
}
public void create(final User usr) throws LDAPSessionException, RequiredAttributeException, AlreadyBoundException {
assert usr != null;
final String uid = usr.getLogin();
if (!hasValue(uid)) {
throw new RequiredAttributeException("uid"); //$NON-NLS-1$
}
assert uid != null;
final BasicAttributes attributes = new BasicAttributes();
final BasicAttribute objClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
objClass.add("top"); //$NON-NLS-1$
objClass.add("person"); //$NON-NLS-1$
objClass.add("organizationalPerson"); //$NON-NLS-1$
objClass.add("inetOrgPerson"); //$NON-NLS-1$
attributes.put(objClass);
final String firstName = usr.getFirstname();
if (hasValue(firstName)) {
attributes.put("givenName", firstName); //$NON-NLS-1$
}
final String lastname = usr.getLastname();
if (!hasValue(lastname)) {
throw new RequiredAttributeException("lastname"); //$NON-NLS-1$
}
attributes.put("sn", lastname); //$NON-NLS-1$
final String email = usr.getEmail();
if (hasValue(email)) {
attributes.put("mail", email); //$NON-NLS-1$
}
attributes.put("uid", uid); //$NON-NLS-1$
attributes.put("cn", uid); //$NON-NLS-1$
final String telephone = usr.getPhone();
if (hasValue(telephone)) {
attributes.put("telephoneNumber", telephone); //$NON-NLS-1$
}
final String mobile = usr.getMobile();
if (hasValue(mobile)) {
attributes.put("mobile", mobile); //$NON-NLS-1$
}
final String comment = usr.getDisplayname();
if (hasValue(comment)) {
attributes.put("displayName", comment); //$NON-NLS-1$
} else {
attributes.put("displayName", firstName == null ? lastname : lastname + ", " + firstName); //$NON-NLS-1$ //$NON-NLS-2$
}
final String password = usr.getPassword();
if (!hasValue(password)) {
throw new RequiredAttributeException("password"); //$NON-NLS-1$
}
attributes.put("userPassword", password); //$NON-NLS-1$
final String dn = session.createSubcontext("uid=${uid},ou=users".replace("${uid}", uid), attributes); //$NON-NLS-1$ //$NON-NLS-2$
usr.setDn(dn);
}
public void create(final User usr) throws LDAPSessionException, RequiredAttributeException, AlreadyBoundException {
assert usr != null;
final String uid = usr.getLogin();
if (!hasValue(uid)) {
throw new RequiredAttributeException("uid"); //$NON-NLS-1$
}
assert uid != null;
final BasicAttributes attributes = new BasicAttributes();
final BasicAttribute objClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
objClass.add("top"); //$NON-NLS-1$
objClass.add("person"); //$NON-NLS-1$
objClass.add("organizationalPerson"); //$NON-NLS-1$
objClass.add("inetOrgPerson"); //$NON-NLS-1$
attributes.put(objClass);
final String firstName = usr.getFirstname();
if (hasValue(firstName)) {
attributes.put("givenName", firstName); //$NON-NLS-1$
}
final String lastname = usr.getLastname();
if (!hasValue(lastname)) {
throw new RequiredAttributeException("lastname"); //$NON-NLS-1$
}
attributes.put("sn", lastname); //$NON-NLS-1$
final String email = usr.getEmail();
if (hasValue(email)) {
attributes.put("mail", email); //$NON-NLS-1$
}
attributes.put("uid", uid); //$NON-NLS-1$
attributes.put("cn", uid); //$NON-NLS-1$
final String telephone = usr.getPhone();
if (hasValue(telephone)) {
attributes.put("telephoneNumber", telephone); //$NON-NLS-1$
}
final String mobile = usr.getMobile();
if (hasValue(mobile)) {
attributes.put("mobile", mobile); //$NON-NLS-1$
}
final String comment = usr.getDisplayname();
if (hasValue(comment)) {
attributes.put("displayName", comment); //$NON-NLS-1$
} else {
attributes.put("displayName", firstName == null ? lastname : lastname + ", " + firstName); //$NON-NLS-1$ //$NON-NLS-2$
}
final String password = usr.getPassword();
if (!hasValue(password)) {
throw new RequiredAttributeException("password"); //$NON-NLS-1$
}
attributes.put("userPassword", password); //$NON-NLS-1$
final String dn = session.createSubcontext("uid=${uid},ou=users".replace("${uid}", uid), attributes); //$NON-NLS-1$ //$NON-NLS-2$
usr.setDn(dn);
}
public User read(final String dn) throws LDAPSessionException {
final Attributes attribs = session.getAttributes(dn.substring(0, dn.indexOf("ou=users") + 8)); //$NON-NLS-1$
final User usr = new User();
usr.setFirstname(session.getStringValue(attribs, "givenName")); //$NON-NLS-1$
usr.setLastname(session.getStringValue(attribs, "sn")); //$NON-NLS-1$
usr.setEmail(session.getStringValue(attribs, "mail")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setPhone(session.getStringValue(attribs, "telephoneNumber")); //$NON-NLS-1$
usr.setMobile(session.getStringValue(attribs, "mobile")); //$NON-NLS-1$
usr.setDisplayname(session.getStringValue(attribs, "displayName")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setDn(dn);
return usr;
}
public User read(final String dn) throws LDAPSessionException {
final Attributes attribs = session.getAttributes(dn.substring(0, dn.indexOf("ou=users") + 8)); //$NON-NLS-1$
final User usr = new User();
usr.setFirstname(session.getStringValue(attribs, "givenName")); //$NON-NLS-1$
usr.setLastname(session.getStringValue(attribs, "sn")); //$NON-NLS-1$
usr.setEmail(session.getStringValue(attribs, "mail")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setPhone(session.getStringValue(attribs, "telephoneNumber")); //$NON-NLS-1$
usr.setMobile(session.getStringValue(attribs, "mobile")); //$NON-NLS-1$
usr.setDisplayname(session.getStringValue(attribs, "displayName")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setDn(dn);
return usr;
}
public void update(final User usr) throws LDAPSessionException {
assert usr != null;
final String uid = usr.getLogin();
assert uid != null;
final Attributes attribs = session.getAttributes(
"uid=${uid},ou=users".replace("${uid}", uid)); //$NON-NLS-1$ //$NON-NLS-2$
final List<ModificationItem> updates = new ArrayList<ModificationItem>();
addStringAttrUpdate(updates, attribs, "displayName", usr.getDisplayname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "mail", usr.getEmail()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "givenName", usr.getFirstname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "sn", usr.getLastname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "mobile", usr.getMobile()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "telephoneNumber", usr.getPhone()); //$NON-NLS-1$
addPasswordUpdate(updates, "userPassword", usr.getPassword()); //$NON-NLS-1$
session.modifyAttributes("uid=${uid},ou=users".replace("${uid}", uid), updates.toArray(new ModificationItem[] { })); //$NON-NLS-1$ //$NON-NLS-2$
}
public void update(final User usr) throws LDAPSessionException {
assert usr != null;
final String uid = usr.getLogin();
assert uid != null;
final Attributes attribs = session.getAttributes(
"uid=${uid},ou=users".replace("${uid}", uid)); //$NON-NLS-1$ //$NON-NLS-2$
final List<ModificationItem> updates = new ArrayList<ModificationItem>();
addStringAttrUpdate(updates, attribs, "displayName", usr.getDisplayname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "mail", usr.getEmail()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "givenName", usr.getFirstname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "sn", usr.getLastname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "mobile", usr.getMobile()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "telephoneNumber", usr.getPhone()); //$NON-NLS-1$
addPasswordUpdate(updates, "userPassword", usr.getPassword()); //$NON-NLS-1$
session.modifyAttributes("uid=${uid},ou=users".replace("${uid}", uid), updates.toArray(new ModificationItem[]{})); //$NON-NLS-1$ //$NON-NLS-2$
}
public void delete(final User user) throws LDAPSessionException {
assert user != null;
session.unbind("uid=${id},ou=users", user.getLogin()); //$NON-NLS-1$
}
public void delete(final User user) throws LDAPSessionException {
assert user != null;
session.unbind("uid=${id},ou=users", user.getLogin()); //$NON-NLS-1$
}
private boolean hasValue(final String email) {
return email != null && !email.isEmpty();
}
private boolean hasValue(final String email) {
return email != null && !email.isEmpty();
}
private void addStringAttrUpdate(final List<ModificationItem> updates,
final Attributes attribs, final String attributeName, final String newValue) throws LDAPSessionException {
final String oldValue = session.getStringValue(attribs, attributeName);
final BasicAttribute basicAttribute = new BasicAttribute(attributeName);
if (hasValue(newValue)) {
if (!newValue.equals(oldValue)) {
basicAttribute.add(newValue);
int ldapOp = DirContext.REPLACE_ATTRIBUTE;
if (oldValue == null) {
ldapOp = DirContext.ADD_ATTRIBUTE;
}
final ModificationItem modificationItem = new ModificationItem(ldapOp, basicAttribute);
updates.add(modificationItem);
}
} else {
if (hasValue(oldValue)) {
updates.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute));
}
}
}
private void addStringAttrUpdate(final List<ModificationItem> updates,
final Attributes attribs, final String attributeName, final String newValue) throws LDAPSessionException {
final String oldValue = session.getStringValue(attribs, attributeName);
final BasicAttribute basicAttribute = new BasicAttribute(attributeName);
if (hasValue(newValue)) {
if (!newValue.equals(oldValue)) {
basicAttribute.add(newValue);
int ldapOp = DirContext.REPLACE_ATTRIBUTE;
if (oldValue == null) {
ldapOp = DirContext.ADD_ATTRIBUTE;
}
final ModificationItem modificationItem = new ModificationItem(ldapOp, basicAttribute);
updates.add(modificationItem);
}
} else {
if (hasValue(oldValue)) {
updates.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute));
}
}
}
private void addPasswordUpdate(final List<ModificationItem> updates,
final String attributeName, final String newValue) throws LDAPSessionException {
if (hasValue(newValue)) {
updates.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute(attributeName, newValue)));
}
}
private void addPasswordUpdate(final List<ModificationItem> updates,
final String attributeName, final String newValue) throws LDAPSessionException {
if (hasValue(newValue)) {
updates.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute(attributeName, newValue)));
}
}
}

View File

@ -19,64 +19,63 @@ import java.util.logging.Logger;
public class AbstractLDAPServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
protected static final Logger LOG = Logger.getLogger("LDAP");
protected static final Logger LOG = Logger.getLogger("LDAP");
private SortedMap<String, User> users;
private SortedMap<String, Group> groups;
private SortedMap<String, User> users;
private SortedMap<String, Group> groups;
protected LDAPSession ldapSession;
protected Properties config;
protected LDAPSession ldapSession;
protected Properties config;
protected void loadData() {
users = new TreeMap<>();
groups = new TreeMap<>();
}
protected void loadData() {
users = new TreeMap<>();
groups = new TreeMap<>();
}
protected User getUser(final String uid) {
return users.get(uid);
}
protected User getUser(final String uid) {
return users.get(uid);
}
protected Group getGroup(final String gid) {
return groups.get(gid);
}
protected Group getGroup(final String gid) {
return groups.get(gid);
}
@Override
public void init() throws ServletException {
super.init();
final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties"); //$NON-NLS-1$
config = new Properties();
try {
config.load(inputStream);
ldapSession = new LDAPSession(config.getProperty("provider.url"), config.getProperty("security.principal"), config.getProperty("security.password")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} catch (IOException | LDAPSessionException e) {
LOG.severe(e.getMessage());
throw new ServletException(e);
}
}
@Override
public void init() throws ServletException {
super.init();
final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties"); //$NON-NLS-1$
config = new Properties();
try {
config.load(inputStream);
ldapSession = new LDAPSession(config.getProperty("provider.url"), config.getProperty("security.principal"), config.getProperty("security.password")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} catch (IOException | LDAPSessionException e) {
LOG.severe(e.getMessage());
throw new ServletException(e);
}
}
@Override
public void destroy() {
super.destroy();
try {
ldapSession.close();
} catch (NamingException e) {
LOG.severe(e.getMessage());
}
}
@Override
public void destroy() {
super.destroy();
try {
ldapSession.close();
} catch (NamingException e) {
LOG.severe(e.getMessage());
}
}
protected void throwServletException(final HttpSession session, final Exception e) throws ServletException
{
session.setAttribute("servletexception", e); //$NON-NLS-1$
LOG.severe(e.getMessage());
throw new ServletException(e);
}
protected void throwServletException(final HttpSession session, final Exception e) throws ServletException {
session.setAttribute("servletexception", e); //$NON-NLS-1$
LOG.severe(e.getMessage());
throw new ServletException(e);
}
protected void cleanSession(final HttpSession httpSession) {
httpSession.removeAttribute("errormessage"); //$NON-NLS-1$
httpSession.removeAttribute("successmessage"); //$NON-NLS-1$
httpSession.removeAttribute("servletexception"); //$NON-NLS-1$
}
protected void cleanSession(final HttpSession httpSession) {
httpSession.removeAttribute("errormessage"); //$NON-NLS-1$
httpSession.removeAttribute("successmessage"); //$NON-NLS-1$
httpSession.removeAttribute("servletexception"); //$NON-NLS-1$
}
}

View File

@ -20,130 +20,130 @@ import de.jalin.ldapadmin.ldap.LDAPSessionException;
import de.jalin.ldapadmin.ldap.NoGroupMembersException;
import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapGroup",urlPatterns={"/group/*"})
@WebServlet(name = "LdapGroup", urlPatterns = {"/group/*"})
public class GroupServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final String pathInfo = req.getPathInfo();
String groupDN = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
groupDN = pathInfo.substring(1);
}
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "view"; //$NON-NLS-1$
}
httpSession.setAttribute("operation", operation); //$NON-NLS-1$
httpSession.setAttribute("formdisabled", "view".equals(operation) || "delete".equals(operation) ? "disabled" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
httpSession.setAttribute("iddisabled", "create".equals(operation) ? "" : "disabled"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final String pathInfo = req.getPathInfo();
String groupDN = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
groupDN = pathInfo.substring(1);
}
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "view"; //$NON-NLS-1$
}
httpSession.setAttribute("operation", operation); //$NON-NLS-1$
httpSession.setAttribute("formdisabled", "view".equals(operation) || "delete".equals(operation) ? "disabled" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
httpSession.setAttribute("iddisabled", "create".equals(operation) ? "" : "disabled"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
final UsersDAO usersDAO = new UsersDAO(ldapSession);
try {
final SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$
if (groupDN != null && groupDN.length() > 9) {
httpSession.setAttribute("group", groupsDAO.readGroup(groupDN, users)); //$NON-NLS-1$
} else {
httpSession.setAttribute("group", new Group()); //$NON-NLS-1$
}
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
}
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
final UsersDAO usersDAO = new UsersDAO(ldapSession);
try {
final SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$
if (groupDN != null && groupDN.length() > 9) {
httpSession.setAttribute("group", groupsDAO.readGroup(groupDN, users)); //$NON-NLS-1$
} else {
httpSession.setAttribute("group", new Group()); //$NON-NLS-1$
}
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final String pathInfo = req.getPathInfo();
String dn = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
dn = pathInfo.substring(1);
}
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "none"; //$NON-NLS-1$
}
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
final Group grp = new Group();
final List<String> members;
members = new ArrayList<>();
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
@SuppressWarnings("unchecked") final SortedMap<String, User> usersHash = (SortedMap<String, User>) httpSession.getAttribute("users"); //$NON-NLS-1$
final Iterator<String> userDNIterator = usersHash.keySet().iterator();
while (userDNIterator.hasNext()) {
final String userDN = userDNIterator.next();
final User usr = usersHash.get(userDN);
final String isChecked = req.getParameter("check_user_" + usr.getLogin()); //$NON-NLS-1$
if (isChecked != null && !isChecked.isEmpty()) {
members.add(usr.getDn());
}
}
grp.setMembers(members);
try {
if ("edit".equals(operation) && !dn.isEmpty()) { //$NON-NLS-1$
final Group oldValue = groupsDAO.readGroup(dn, usersHash);
grp.setDn(dn);
grp.setName(oldValue.getName());
if (grp.getMembers().isEmpty()) {
httpSession.setAttribute("group", grp); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
try {
groupsDAO.update(grp);
} catch (NoGroupMembersException e) {
httpSession.setAttribute("group", grp); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
}
if ("delete".equals(operation) && !dn.isEmpty()) { //$NON-NLS-1$
final Group oldValue = groupsDAO.readGroup(dn, usersHash);
grp.setDn(dn);
grp.setName(oldValue.getName());
groupsDAO.delete(grp);
}
if ("create".equals(operation)) { //$NON-NLS-1$
final String grpName = req.getParameter("name"); //$NON-NLS-1$
grp.setName(grpName);
if (grp.getMembers().isEmpty()) {
httpSession.setAttribute("group", grp); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
try {
groupsDAO.create(grp);
} catch (AlreadyBoundException e) {
httpSession.setAttribute("group", grp); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.group_exists")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
resp.sendRedirect(req.getContextPath() + req.getServletPath() + "/" + grp.getDn()); //$NON-NLS-1$
} else {
if ("delete".equals(operation)) { //$NON-NLS-1$
resp.sendRedirect(req.getContextPath() + "/groups"); //$NON-NLS-1$
} else {
resp.sendRedirect(req.getContextPath() + req.getServletPath() + pathInfo);
}
}
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final String pathInfo = req.getPathInfo();
String dn = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
dn = pathInfo.substring(1);
}
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "none"; //$NON-NLS-1$
}
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
final Group grp = new Group();
final List<String> members;
members = new ArrayList<>();
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
@SuppressWarnings("unchecked")
final SortedMap<String, User> usersHash = (SortedMap<String, User>) httpSession.getAttribute("users"); //$NON-NLS-1$
final Iterator<String> userDNIterator = usersHash.keySet().iterator();
while (userDNIterator.hasNext()) {
final String userDN = userDNIterator.next();
final User usr = usersHash.get(userDN);
final String isChecked = req.getParameter("check_user_" + usr.getLogin()); //$NON-NLS-1$
if (isChecked != null && !isChecked.isEmpty()) {
members.add(usr.getDn());
}
}
grp.setMembers(members);
try {
if ("edit".equals(operation) && !dn.isEmpty()) { //$NON-NLS-1$
final Group oldValue = groupsDAO.readGroup(dn, usersHash);
grp.setDn(dn);
grp.setName(oldValue.getName());
if (grp.getMembers().isEmpty()) {
httpSession.setAttribute("group", grp); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
try {
groupsDAO.update(grp);
} catch (NoGroupMembersException e) {
httpSession.setAttribute("group", grp); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
}
if ("delete".equals(operation) && !dn.isEmpty()) { //$NON-NLS-1$
final Group oldValue = groupsDAO.readGroup(dn, usersHash);
grp.setDn(dn);
grp.setName(oldValue.getName());
groupsDAO.delete(grp);
}
if ("create".equals(operation)) { //$NON-NLS-1$
final String grpName = req.getParameter("name"); //$NON-NLS-1$
grp.setName(grpName);
if (grp.getMembers().isEmpty()) {
httpSession.setAttribute("group", grp); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
try {
groupsDAO.create(grp);
} catch (AlreadyBoundException e) {
httpSession.setAttribute("group", grp); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.group_exists")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
resp.sendRedirect(req.getContextPath() + req.getServletPath() + "/" + grp.getDn()); //$NON-NLS-1$
} else {
if ("delete".equals(operation)) { //$NON-NLS-1$
resp.sendRedirect(req.getContextPath() + "/groups"); //$NON-NLS-1$
} else {
resp.sendRedirect(req.getContextPath() + req.getServletPath() + pathInfo);
}
}
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
}
}

View File

@ -14,27 +14,26 @@ import de.jalin.ldapadmin.ldap.GroupsDAO;
import de.jalin.ldapadmin.ldap.LDAPSessionException;
import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapGroups",urlPatterns={"/groups"})
@WebServlet(name = "LdapGroups", urlPatterns = {"/groups"})
public class GroupsServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException
{
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try {
final SortedMap<String, User> loadedUsers = usersDAO.loadUsers();
httpSession.setAttribute("users", loadedUsers); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(loadedUsers)); //$NON-NLS-1$
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/groups.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try {
final SortedMap<String, User> loadedUsers = usersDAO.loadUsers();
httpSession.setAttribute("users", loadedUsers); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(loadedUsers)); //$NON-NLS-1$
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/groups.jsp").forward(req, resp); //$NON-NLS-1$
}
}

View File

@ -8,18 +8,18 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name="Logout",urlPatterns={"/logout"})
@WebServlet(name = "Logout", urlPatterns = {"/logout"})
public class LogoutServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
httpSession.invalidate();
resp.sendRedirect(httpSession.getServletContext().getContextPath() + "/"); //$NON-NLS-1$
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
httpSession.invalidate();
resp.sendRedirect(httpSession.getServletContext().getContextPath() + "/"); //$NON-NLS-1$
}
}

View File

@ -6,19 +6,19 @@ import java.util.ResourceBundle;
public class Messages {
private static final String BUNDLE_NAME = "de.jalin.ldapadmin.admin.web.messages"; //$NON-NLS-1$
private static final String BUNDLE_NAME = "de.jalin.ldapadmin.admin.web.messages"; //$NON-NLS-1$
private final ResourceBundle resourceBundle;
private final ResourceBundle resourceBundle;
public Messages(final Locale requestLocale) {
resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, requestLocale);
}
public Messages(final Locale requestLocale) {
resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, requestLocale);
}
public String getString(final String key) {
try {
return resourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
public String getString(final String key) {
try {
return resourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}

View File

@ -14,37 +14,37 @@ import javax.net.ssl.X509TrustManager;
public class NaiveTrustManager implements X509TrustManager {
private static final SSLContext SSL_CONTEXT;
private static final SSLContext SSL_CONTEXT;
static {
try {
SSL_CONTEXT = SSLContext.getInstance("TLSv1.2");
SSL_CONTEXT.init(null, new TrustManager[] { new NaiveTrustManager() }, null);
SSLContext.setDefault(SSL_CONTEXT);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
}
}
static {
try {
SSL_CONTEXT = SSLContext.getInstance("TLSv1.2");
SSL_CONTEXT.init(null, new TrustManager[]{new NaiveTrustManager()}, null);
SSLContext.setDefault(SSL_CONTEXT);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
}
}
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}

View File

@ -18,102 +18,102 @@ import de.jalin.ldapadmin.ldap.LDAPSessionException;
import de.jalin.ldapadmin.ldap.SimplePasswordException;
import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapProfile",urlPatterns={"/profile", "/profile/*"})
@WebServlet(name = "LdapProfile", urlPatterns = {"/profile", "/profile/*"})
public class ProfileServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
String userDN = ""; //$NON-NLS-1$
try {
final String remoteUID = req.getRemoteUser();
final List<SearchResult> list = ldapSession.search("ou=users", "uid", remoteUID); //$NON-NLS-1$ //$NON-NLS-2$
if (list != null && list.size() > 0) {
final SearchResult first = list.get(0);
userDN = first.getNameInNamespace();
}
cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "profile"; //$NON-NLS-1$
}
httpSession.setAttribute("operation", operation); //$NON-NLS-1$
httpSession.setAttribute("formdisabled", "profile".equals(operation) ? "disabled" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
httpSession.setAttribute("iddisabled", "disabled"); //$NON-NLS-1$ //$NON-NLS-2$
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(users)); //$NON-NLS-1$
httpSession.setAttribute("user", users.get(userDN)); //$NON-NLS-1$
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
String userDN = ""; //$NON-NLS-1$
try {
final String remoteUID = req.getRemoteUser();
final List<SearchResult> list = ldapSession.search("ou=users", "uid", remoteUID); //$NON-NLS-1$ //$NON-NLS-2$
if (list != null && list.size() > 0) {
final SearchResult first = list.get(0);
userDN = first.getNameInNamespace();
}
cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "profile"; //$NON-NLS-1$
}
httpSession.setAttribute("operation", operation); //$NON-NLS-1$
httpSession.setAttribute("formdisabled", "profile".equals(operation) ? "disabled" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
httpSession.setAttribute("iddisabled", "disabled"); //$NON-NLS-1$ //$NON-NLS-2$
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(users)); //$NON-NLS-1$
httpSession.setAttribute("user", users.get(userDN)); //$NON-NLS-1$
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final String pathInfo = req.getPathInfo();
String dn = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
dn = pathInfo.substring(1);
}
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "none"; //$NON-NLS-1$
}
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final String password = req.getParameter("password"); //$NON-NLS-1$
final String password2 = req.getParameter("password2"); //$NON-NLS-1$
final User usr = (User) httpSession.getAttribute("user"); //$NON-NLS-1$
try {
if (password != null && !password.isEmpty()) {
if (password2 == null || !password2.equals(password)) {
throw new ValidationException("password2", messages.getString("ProfileServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
} else {
usr.setAndValidatePassword(password);
}
}
} catch (SimplePasswordException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (ValidationException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ProfileServlet.inputfield") + e.getFieldname() + " " + e.getCondition()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
try {
if ("password".equals(operation)) { //$NON-NLS-1$
final User oldValue = usersDAO.read(dn);
usr.setLogin(oldValue.getLogin());
usr.setDn(dn);
usersDAO.update(usr);
httpSession.setAttribute("successmessage", messages.getString("ProfileServlet.password_changed")); //$NON-NLS-1$ //$NON-NLS-2$
httpSession.setAttribute("operation", "profile"); //$NON-NLS-1$ //$NON-NLS-2$
httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp);
}
} catch (LDAPSessionException e) {
final String excMessage = e.getMessage();
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ProfileServlet.invalid_reuse")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
throwServletException(httpSession, e);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final String pathInfo = req.getPathInfo();
String dn = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
dn = pathInfo.substring(1);
}
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "none"; //$NON-NLS-1$
}
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final String password = req.getParameter("password"); //$NON-NLS-1$
final String password2 = req.getParameter("password2"); //$NON-NLS-1$
final User usr = (User) httpSession.getAttribute("user"); //$NON-NLS-1$
try {
if (password != null && !password.isEmpty()) {
if (password2 == null || !password2.equals(password)) {
throw new ValidationException("password2", messages.getString("ProfileServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
} else {
usr.setAndValidatePassword(password);
}
}
} catch (SimplePasswordException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (ValidationException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ProfileServlet.inputfield") + e.getFieldname() + " " + e.getCondition()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
try {
if ("password".equals(operation)) { //$NON-NLS-1$
final User oldValue = usersDAO.read(dn);
usr.setLogin(oldValue.getLogin());
usr.setDn(dn);
usersDAO.update(usr);
httpSession.setAttribute("successmessage", messages.getString("ProfileServlet.password_changed")); //$NON-NLS-1$ //$NON-NLS-2$
httpSession.setAttribute("operation", "profile"); //$NON-NLS-1$ //$NON-NLS-2$
httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp);
}
} catch (LDAPSessionException e) {
final String excMessage = e.getMessage();
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ProfileServlet.invalid_reuse")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
throwServletException(httpSession, e);
}
}
}

View File

@ -26,171 +26,170 @@ import de.jalin.ldapadmin.ldap.LDAPSessionException;
import de.jalin.ldapadmin.ldap.SimplePasswordException;
import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="ResetPassword",urlPatterns={"/passwordreset"})
@WebServlet(name = "ResetPassword", urlPatterns = {"/passwordreset"})
public class ResetPasswordServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private String smtpHost;
private String smtpPort;
private String smtpFrom;
private String smtpHost;
private String smtpPort;
private String smtpFrom;
@Override
public void init() throws ServletException {
super.init();
smtpHost = config.getProperty("smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
smtpPort = config.getProperty("smtp.port", "25"); //$NON-NLS-1$ //$NON-NLS-2$
smtpFrom = config.getProperty("smtp.from", "nobody@localhost"); //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
public void init() throws ServletException {
super.init();
smtpHost = config.getProperty("smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
smtpPort = config.getProperty("smtp.port", "25"); //$NON-NLS-1$ //$NON-NLS-2$
smtpFrom = config.getProperty("smtp.from", "nobody@localhost"); //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final String token = req.getParameter("token"); //$NON-NLS-1$
if (token != null && !token.isEmpty()) {
final File passwdResetFile = new File("/tmp/passwd" + token + ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
if (passwdResetFile.exists() && passwdResetFile.canRead()) {
try (final BufferedReader reader = new BufferedReader(new FileReader(passwdResetFile))) {
final String[] uidAndEMail = reader.readLine().split(":"); //$NON-NLS-1$
final UsersDAO usrDAO = new UsersDAO(ldapSession);
final User usr = usrDAO.read("uid=" + uidAndEMail[0] + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$
httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (LDAPSessionException e) {
LOG.warning("no valid password reset request");
httpSession.setAttribute("errormessage", new Messages(req.getLocale()).getString("ResetPasswordServlet.no_valid_passwordreset_request")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
}
}
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final UsersDAO usrDAO = new UsersDAO(ldapSession);
final String loginParam = req.getParameter("login"); //$NON-NLS-1$
final User sessUsr = (User) httpSession.getAttribute("user"); //$NON-NLS-1$
if (loginParam != null && sessUsr != null && loginParam.equals(sessUsr.getLogin())) {
final String password1 = req.getParameter("password"); //$NON-NLS-1$
final String password2 = req.getParameter("password2"); //$NON-NLS-1$
if (password1 != null && !password1.isEmpty()) {
if (password2 == null || !password2.equals(password1)) {
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} else {
try {
sessUsr.setAndValidatePassword(password1);
usrDAO.update(sessUsr);
httpSession.setAttribute("successmessage", messages.getString("ResetPasswordServlet.password_changed")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (SimplePasswordException e) {
httpSession.setAttribute("user", sessUsr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (LDAPSessionException e) {
final String excMessage = e.getMessage();
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("user", sessUsr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.invalid_password_reuse")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
throwServletException(httpSession, e);
}
}
}
}
final String loginOrEMail = req.getParameter("loginoremail"); //$NON-NLS-1$
final File tempFile = File.createTempFile("passwd", ".tmp", new File("/tmp")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
try (final PrintStream printStream = new PrintStream(tempFile)) {
String email = ""; //$NON-NLS-1$
String login = ""; //$NON-NLS-1$
String salutation = ""; //$NON-NLS-1$
if (loginOrEMail != null) {
if (loginOrEMail.contains("@")) { //$NON-NLS-1$
final SortedMap<String,User> usersMap = usrDAO.loadUsers();
final Collection<User> allUsers = usersMap.values();
for (User usr : allUsers) {
if (usr.getEmail() != null && usr.getEmail().equalsIgnoreCase(loginOrEMail)) {
login = usr.getLogin();
email = usr.getEmail();
salutation = usr.getFirstname() + " " + usr.getLastname(); //$NON-NLS-1$
}
}
} else {
final User usr = usrDAO.read("uid=" + loginOrEMail + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$
if (usr != null) {
login = usr.getLogin();
email = usr.getEmail();
salutation = usr.getFirstname() + " " + usr.getLastname(); //$NON-NLS-1$
}
}
if (login.isEmpty() || email.isEmpty()) {
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.error_sending_password_reset")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
printStream.println(login + ":" + email); //$NON-NLS-1$
}
final StringBuffer messageText = new StringBuffer(messages.getString("ResetPasswordServlet.email_greeting")); //$NON-NLS-1$
messageText.append(salutation);
messageText.append(messages.getString("ResetPasswordServlet.email_content")); //$NON-NLS-1$
messageText.append(req.getRequestURL().toString().replaceAll("^http\\:", "https://"));
messageText.append("?token="); //$NON-NLS-1$
final String filename = tempFile.getName();
messageText.append(filename.substring(6,filename.length()-4));
messageText.append(messages.getString("ResetPasswordServlet.email_signature")); //$NON-NLS-1$
smtpSend(smtpHost, smtpPort, messages, smtpFrom, email, messages.getString("ResetPasswordServlet.email_subject"), messageText.toString()); //$NON-NLS-1$ //$NON-NLS-2$
} catch (LDAPSessionException | IOException e) {
LOG.severe("smtp problem");
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.error_sending_password_reset")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
httpSession.invalidate();
resp.sendRedirect(httpSession.getServletContext().getContextPath() + "/"); //$NON-NLS-1$
}
private static void smtpSend(final String smtpHost, final String smtpPort, final Messages messages, final String fromAddress, final String toAddress, final String subject, final String text) throws IOException {
final SMTPClient client = new SMTPClient();
final String canonicalHostName = InetAddress.getLocalHost().getHostName();
client.connect(smtpHost, Integer.parseInt(smtpPort));
int reply = client.getReplyCode();
if (!SMTPReply.isPositiveCompletion(reply)) {
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email_server")); //$NON-NLS-1$
}
client.login(canonicalHostName);
client.setSender(fromAddress.trim());
client.addRecipient(toAddress.trim());
final Writer sendMessageData = client.sendMessageData();
if (sendMessageData == null) {
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email_relay")); //$NON-NLS-1$
}
try (PrintWriter wr = new PrintWriter(sendMessageData)) {
final SimpleSMTPHeader header = new SimpleSMTPHeader(fromAddress, toAddress, subject);
header.addHeaderField("Content-Type", "text/plain; charset=ISO-8859-15");
header.addHeaderField("Content-Transfer-Encoding", "8bit");
wr.write(header.toString());
wr.write(text);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final String token = req.getParameter("token"); //$NON-NLS-1$
if (token != null && !token.isEmpty()) {
final File passwdResetFile = new File("/tmp/passwd" + token + ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
if (passwdResetFile.exists() && passwdResetFile.canRead()) {
try (final BufferedReader reader = new BufferedReader(new FileReader(passwdResetFile))) {
final String[] uidAndEMail = reader.readLine().split(":"); //$NON-NLS-1$
final UsersDAO usrDAO = new UsersDAO(ldapSession);
final User usr = usrDAO.read("uid=" + uidAndEMail[0] + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$
httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (LDAPSessionException e) {
LOG.warning("no valid password reset request");
httpSession.setAttribute("errormessage", new Messages(req.getLocale()).getString("ResetPasswordServlet.no_valid_passwordreset_request")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
}
if (!client.completePendingCommand()) {
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email")); //$NON-NLS-1$
}
client.logout();
client.disconnect();
}
}
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final UsersDAO usrDAO = new UsersDAO(ldapSession);
final String loginParam = req.getParameter("login"); //$NON-NLS-1$
final User sessUsr = (User) httpSession.getAttribute("user"); //$NON-NLS-1$
if (loginParam != null && sessUsr != null && loginParam.equals(sessUsr.getLogin())) {
final String password1 = req.getParameter("password"); //$NON-NLS-1$
final String password2 = req.getParameter("password2"); //$NON-NLS-1$
if (password1 != null && !password1.isEmpty()) {
if (password2 == null || !password2.equals(password1)) {
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} else {
try {
sessUsr.setAndValidatePassword(password1);
usrDAO.update(sessUsr);
httpSession.setAttribute("successmessage", messages.getString("ResetPasswordServlet.password_changed")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (SimplePasswordException e) {
httpSession.setAttribute("user", sessUsr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (LDAPSessionException e) {
final String excMessage = e.getMessage();
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("user", sessUsr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.invalid_password_reuse")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
throwServletException(httpSession, e);
}
}
}
}
final String loginOrEMail = req.getParameter("loginoremail"); //$NON-NLS-1$
final File tempFile = File.createTempFile("passwd", ".tmp", new File("/tmp")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
try (final PrintStream printStream = new PrintStream(tempFile)) {
String email = ""; //$NON-NLS-1$
String login = ""; //$NON-NLS-1$
String salutation = ""; //$NON-NLS-1$
if (loginOrEMail != null) {
if (loginOrEMail.contains("@")) { //$NON-NLS-1$
final SortedMap<String, User> usersMap = usrDAO.loadUsers();
final Collection<User> allUsers = usersMap.values();
for (User usr : allUsers) {
if (usr.getEmail() != null && usr.getEmail().equalsIgnoreCase(loginOrEMail)) {
login = usr.getLogin();
email = usr.getEmail();
salutation = usr.getFirstname() + " " + usr.getLastname(); //$NON-NLS-1$
}
}
} else {
final User usr = usrDAO.read("uid=" + loginOrEMail + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$
if (usr != null) {
login = usr.getLogin();
email = usr.getEmail();
salutation = usr.getFirstname() + " " + usr.getLastname(); //$NON-NLS-1$
}
}
if (login.isEmpty() || email.isEmpty()) {
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.error_sending_password_reset")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
printStream.println(login + ":" + email); //$NON-NLS-1$
}
final StringBuffer messageText = new StringBuffer(messages.getString("ResetPasswordServlet.email_greeting")); //$NON-NLS-1$
messageText.append(salutation);
messageText.append(messages.getString("ResetPasswordServlet.email_content")); //$NON-NLS-1$
messageText.append(req.getRequestURL().toString().replaceAll("^http\\:", "https://"));
messageText.append("?token="); //$NON-NLS-1$
final String filename = tempFile.getName();
messageText.append(filename.substring(6, filename.length() - 4));
messageText.append(messages.getString("ResetPasswordServlet.email_signature")); //$NON-NLS-1$
smtpSend(smtpHost, smtpPort, messages, smtpFrom, email, messages.getString("ResetPasswordServlet.email_subject"), messageText.toString()); //$NON-NLS-1$ //$NON-NLS-2$
} catch (LDAPSessionException | IOException e) {
LOG.severe("smtp problem");
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.error_sending_password_reset")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
httpSession.invalidate();
resp.sendRedirect(httpSession.getServletContext().getContextPath() + "/"); //$NON-NLS-1$
}
private static void smtpSend(final String smtpHost, final String smtpPort, final Messages messages, final String fromAddress, final String toAddress, final String subject, final String text) throws IOException {
final SMTPClient client = new SMTPClient();
final String canonicalHostName = InetAddress.getLocalHost().getHostName();
client.connect(smtpHost, Integer.parseInt(smtpPort));
int reply = client.getReplyCode();
if (!SMTPReply.isPositiveCompletion(reply)) {
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email_server")); //$NON-NLS-1$
}
client.login(canonicalHostName);
client.setSender(fromAddress.trim());
client.addRecipient(toAddress.trim());
final Writer sendMessageData = client.sendMessageData();
if (sendMessageData == null) {
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email_relay")); //$NON-NLS-1$
}
try (PrintWriter wr = new PrintWriter(sendMessageData)) {
final SimpleSMTPHeader header = new SimpleSMTPHeader(fromAddress, toAddress, subject);
header.addHeaderField("Content-Type", "text/plain; charset=ISO-8859-15");
header.addHeaderField("Content-Transfer-Encoding", "8bit");
wr.write(header.toString());
wr.write(text);
}
if (!client.completePendingCommand()) {
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email")); //$NON-NLS-1$
}
client.logout();
client.disconnect();
}
}

View File

@ -23,193 +23,194 @@ import de.jalin.ldapadmin.ldap.RequiredAttributeException;
import de.jalin.ldapadmin.ldap.SimplePasswordException;
import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapUser",urlPatterns={"/user/*"})
@WebServlet(name = "LdapUser", urlPatterns = {"/user/*"})
public class UserServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final String pathInfo = req.getPathInfo();
String userDN = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
userDN = pathInfo.substring(1);
}
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "view"; //$NON-NLS-1$
}
httpSession.setAttribute("operation", operation); //$NON-NLS-1$
httpSession.setAttribute("formdisabled", "view".equals(operation) || "delete".equals(operation) ? "disabled" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
httpSession.setAttribute("iddisabled", "create".equals(operation) ? "" : "disabled"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try {
SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(users)); //$NON-NLS-1$
if ("create".equals(operation)) { //$NON-NLS-1$
httpSession.setAttribute("user", new User()); //$NON-NLS-1$
} else {
httpSession.setAttribute("user", users.get(userDN)); //$NON-NLS-1$
}
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final String pathInfo = req.getPathInfo();
String userDN = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
userDN = pathInfo.substring(1);
}
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "view"; //$NON-NLS-1$
}
httpSession.setAttribute("operation", operation); //$NON-NLS-1$
httpSession.setAttribute("formdisabled", "view".equals(operation) || "delete".equals(operation) ? "disabled" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
httpSession.setAttribute("iddisabled", "create".equals(operation) ? "" : "disabled"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try {
SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(users)); //$NON-NLS-1$
if ("create".equals(operation)) { //$NON-NLS-1$
httpSession.setAttribute("user", new User()); //$NON-NLS-1$
} else {
httpSession.setAttribute("user", users.get(userDN)); //$NON-NLS-1$
}
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final String pathInfo = req.getPathInfo();
String dn = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
dn = pathInfo.substring(1);
}
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "none"; //$NON-NLS-1$
}
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final String login = req.getParameter("login"); //$NON-NLS-1$
final String firstname = req.getParameter("firstname"); //$NON-NLS-1$
final String lastname = req.getParameter("lastname"); //$NON-NLS-1$
final String email = req.getParameter("email"); //$NON-NLS-1$
final String phone = req.getParameter("phone"); //$NON-NLS-1$
final String mobile = req.getParameter("mobile"); //$NON-NLS-1$
final String password = req.getParameter("password"); //$NON-NLS-1$
final String password2 = req.getParameter("password2"); //$NON-NLS-1$
final User usr = new User();
if (!dn.isEmpty()) {
usr.setDn(dn);
}
usr.setLogin(login);
usr.setFirstname(firstname);
usr.setLastname(lastname);
usr.setDisplayname(lastname + ", " + firstname); //$NON-NLS-1$
usr.setEmail(email);
usr.setPhone(phone);
usr.setMobile(mobile);
final List<String> memberships;
memberships = new ArrayList<>();
@SuppressWarnings("unchecked") final SortedMap<String, Group> groupsHash = (SortedMap<String, Group>) httpSession.getAttribute("groups"); //$NON-NLS-1$
final Iterator<String> groupDNIterator = groupsHash.keySet().iterator();
while (groupDNIterator.hasNext()) {
final String groupDN = groupDNIterator.next();
final Group grp = groupsHash.get(groupDN);
final String isChecked = req.getParameter("check_group_" + grp.getName()); //$NON-NLS-1$
if (isChecked != null && !isChecked.isEmpty()) {
memberships.add(grp.getDn());
}
}
usr.setGroups(memberships);
try {
validatePhone(messages, "phone", phone); //$NON-NLS-1$
validatePhone(messages, "mobile", mobile); //$NON-NLS-1$
validateEMail(messages, email);
validateLastName(messages, lastname);
if (password != null && !password.isEmpty()) {
if (password2 == null || !password2.equals(password)) {
throw new ValidationException("password2", messages.getString("UserServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
} else {
usr.setAndValidatePassword(password);
}
}
} catch (SimplePasswordException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (ValidationException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.input_field") + " \"" + e.getFieldname() + "\" " + e.getCondition()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try {
if ("edit".equals(operation)) { //$NON-NLS-1$
final User oldValue = usersDAO.read(dn);
usr.setLogin(oldValue.getLogin());
usr.setDn(dn);
usersDAO.update(usr);
groupsDAO.updateMemberships(usr);
}
if ("delete".equals(operation)) { //$NON-NLS-1$
final User oldValue = usersDAO.read(dn);
usr.setLogin(oldValue.getLogin());
usr.setDn(dn);
usr.getGroups().clear();
groupsDAO.updateMemberships(usr);
usersDAO.delete(usr);
}
if ("create".equals(operation)) { //$NON-NLS-1$
usr.setLogin(login);
usersDAO.create(usr);
groupsDAO.updateMemberships(usr);
resp.sendRedirect(req.getContextPath() + req.getServletPath() + "/" + usr.getDn()); //$NON-NLS-1$
} else {
if ("delete".equals(operation)) { //$NON-NLS-1$
resp.sendRedirect(req.getContextPath() + "/users"); //$NON-NLS-1$
} else {
resp.sendRedirect(req.getContextPath() + req.getServletPath() + pathInfo);
}
}
} catch (LDAPSessionException e) {
final String excMessage = e.getMessage();
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.invalid_password_reuse")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
throwServletException(httpSession, e);
} catch (NoGroupMembersException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.group_last_member")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
} catch (RequiredAttributeException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.the_input_field") + " " + e.getFieldname() + " " + messages.getString("UserServlet.is_required")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
} catch (AlreadyBoundException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.user_exists")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final String pathInfo = req.getPathInfo();
String dn = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
dn = pathInfo.substring(1);
}
String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) {
operation = "none"; //$NON-NLS-1$
}
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final String login = req.getParameter("login"); //$NON-NLS-1$
final String firstname = req.getParameter("firstname"); //$NON-NLS-1$
final String lastname = req.getParameter("lastname"); //$NON-NLS-1$
final String email = req.getParameter("email"); //$NON-NLS-1$
final String phone = req.getParameter("phone"); //$NON-NLS-1$
final String mobile = req.getParameter("mobile"); //$NON-NLS-1$
final String password = req.getParameter("password"); //$NON-NLS-1$
final String password2 = req.getParameter("password2"); //$NON-NLS-1$
final User usr = new User();
if (!dn.isEmpty()) {
usr.setDn(dn);
}
usr.setLogin(login);
usr.setFirstname(firstname);
usr.setLastname(lastname);
usr.setDisplayname(lastname + ", " + firstname); //$NON-NLS-1$
usr.setEmail(email);
usr.setPhone(phone);
usr.setMobile(mobile);
final List<String> memberships;
memberships = new ArrayList<>();
@SuppressWarnings("unchecked")
final SortedMap<String, Group> groupsHash = (SortedMap<String, Group>) httpSession.getAttribute("groups"); //$NON-NLS-1$
final Iterator<String> groupDNIterator = groupsHash.keySet().iterator();
while (groupDNIterator.hasNext()) {
final String groupDN = groupDNIterator.next();
final Group grp = groupsHash.get(groupDN);
final String isChecked = req.getParameter("check_group_" + grp.getName()); //$NON-NLS-1$
if (isChecked != null && !isChecked.isEmpty()) {
memberships.add(grp.getDn());
}
}
usr.setGroups(memberships);
try {
validatePhone(messages, "phone", phone); //$NON-NLS-1$
validatePhone(messages, "mobile", mobile); //$NON-NLS-1$
validateEMail(messages, email);
validateLastName(messages, lastname);
if (password != null && !password.isEmpty()) {
if (password2 == null || !password2.equals(password)) {
throw new ValidationException("password2", messages.getString("UserServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
} else {
usr.setAndValidatePassword(password);
}
}
} catch (SimplePasswordException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (ValidationException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.input_field") + " \"" + e.getFieldname() + "\" " + e.getCondition()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try {
if ("edit".equals(operation)) { //$NON-NLS-1$
final User oldValue = usersDAO.read(dn);
usr.setLogin(oldValue.getLogin());
usr.setDn(dn);
usersDAO.update(usr);
groupsDAO.updateMemberships(usr);
}
if ("delete".equals(operation)) { //$NON-NLS-1$
final User oldValue = usersDAO.read(dn);
usr.setLogin(oldValue.getLogin());
usr.setDn(dn);
usr.getGroups().clear();
groupsDAO.updateMemberships(usr);
usersDAO.delete(usr);
}
if ("create".equals(operation)) { //$NON-NLS-1$
usr.setLogin(login);
usersDAO.create(usr);
groupsDAO.updateMemberships(usr);
resp.sendRedirect(req.getContextPath() + req.getServletPath() + "/" + usr.getDn()); //$NON-NLS-1$
} else {
if ("delete".equals(operation)) { //$NON-NLS-1$
resp.sendRedirect(req.getContextPath() + "/users"); //$NON-NLS-1$
} else {
resp.sendRedirect(req.getContextPath() + req.getServletPath() + pathInfo);
}
}
} catch (LDAPSessionException e) {
final String excMessage = e.getMessage();
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.invalid_password_reuse")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
throwServletException(httpSession, e);
} catch (NoGroupMembersException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.group_last_member")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
} catch (RequiredAttributeException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.the_input_field") + " " + e.getFieldname() + " " + messages.getString("UserServlet.is_required")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
} catch (AlreadyBoundException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.user_exists")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
}
}
private void validatePhone(final Messages messages, final String field, final String phone) throws ValidationException {
if (phone == null || phone.isEmpty()) {
return;
}
final String valid = phone.trim();
if (!valid.matches("[0-9\\-\\ \\(\\)]*")) { //$NON-NLS-1$
throw new ValidationException(field, messages.getString("UserServlet.phone_not_valid")); //$NON-NLS-1$
}
}
private void validatePhone(final Messages messages, final String field, final String phone) throws ValidationException {
if (phone == null || phone.isEmpty()) {
return;
}
final String valid = phone.trim();
if (!valid.matches("[0-9\\-\\ \\(\\)]*")) { //$NON-NLS-1$
throw new ValidationException(field, messages.getString("UserServlet.phone_not_valid")); //$NON-NLS-1$
}
}
private void validateEMail(final Messages messages, final String email) throws ValidationException {
if (email == null || email.isEmpty()) {
return;
}
final String valid = email.trim();
if (!valid.matches("[A-Za-z0-9_+\\.\\-]*@[a-z0-9\\.\\-üöäß]*")) { //$NON-NLS-1$
throw new ValidationException("email", messages.getString("UserServlet.email_not_valid")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void validateEMail(final Messages messages, final String email) throws ValidationException {
if (email == null || email.isEmpty()) {
return;
}
final String valid = email.trim();
if (!valid.matches("[A-Za-z0-9_+\\.\\-]*@[a-z0-9\\.\\-üöäß]*")) { //$NON-NLS-1$
throw new ValidationException("email", messages.getString("UserServlet.email_not_valid")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void validateLastName(final Messages messages, final String lastname) throws ValidationException {
if (lastname == null || lastname.isEmpty()) {
throw new ValidationException("lastname", messages.getString("UserServlet.is_required")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void validateLastName(final Messages messages, final String lastname) throws ValidationException {
if (lastname == null || lastname.isEmpty()) {
throw new ValidationException("lastname", messages.getString("UserServlet.is_required")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}

View File

@ -15,27 +15,27 @@ import de.jalin.ldapadmin.ldap.GroupsDAO;
import de.jalin.ldapadmin.ldap.LDAPSessionException;
import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapUsers",urlPatterns={"/users"})
@WebServlet(name = "LdapUsers", urlPatterns = {"/users"})
public class UsersServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try {
final SortedMap<String, User> users = usersDAO.loadUsers();
final SortedMap<String,Group> groups = groupsDAO.loadGroups(users);
httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groups); //$NON-NLS-1$
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/users.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try {
final SortedMap<String, User> users = usersDAO.loadUsers();
final SortedMap<String, Group> groups = groupsDAO.loadGroups(users);
httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groups); //$NON-NLS-1$
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/users.jsp").forward(req, resp); //$NON-NLS-1$
}
}

View File

@ -14,61 +14,61 @@ import de.jalin.ldapadmin.beans.User;
public class TestCreateGroup {
private static final String USERS_DN = "uid=${uid},ou=users,dc=saastest,dc=example,dc=com";
private static final String USERS_DN = "uid=${uid},ou=users,dc=saastest,dc=example,dc=com";
private LDAPSession session;
private LDAPSession session;
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@Test
public void test() {
final UsersDAO udao = new UsersDAO(session);
final GroupsDAO gdao = new GroupsDAO(session);
try {
final User newUser1 = newUsersInstance("Jan", "Janssen");
udao.create(newUser1);
final User newUser2 = newUsersInstance("Jens", "Jenssen");
udao.create(newUser2);
Group login = new Group();
login.setName("login");
login.setMembers(Arrays.asList(new String[] { newUser1.getDn(), newUser2.getDn() }));
gdao.create(login);
Group admins = new Group();
admins.setName("admins");
admins.setMembers(Arrays.asList(new String[] { newUser1.getDn(), newUser2.getDn() }));
gdao.create(admins);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
@Test
public void test() {
final UsersDAO udao = new UsersDAO(session);
final GroupsDAO gdao = new GroupsDAO(session);
try {
final User newUser1 = newUsersInstance("Jan", "Janssen");
udao.create(newUser1);
final User newUser2 = newUsersInstance("Jens", "Jenssen");
udao.create(newUser2);
Group login = new Group();
login.setName("login");
login.setMembers(Arrays.asList(new String[]{newUser1.getDn(), newUser2.getDn()}));
gdao.create(login);
Group admins = new Group();
admins.setName("admins");
admins.setMembers(Arrays.asList(new String[]{newUser1.getDn(), newUser2.getDn()}));
gdao.create(admins);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
private User newUsersInstance(final String fn, final String ln) {
final String uid = fn.substring(0, 3).toLowerCase();
final User newUser = new User();
newUser.setDn(USERS_DN.replace("${uid}", uid));
newUser.setDisplayname(fn + " " + ln);
newUser.setEmail(fn.toLowerCase() + "." + ln.toLowerCase() + "@example.com");
newUser.setFirstname(fn);
newUser.setLastname(ln);
newUser.setLogin(uid);
newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678");
newUser.setPassword("geheim");
return newUser;
}
private User newUsersInstance(final String fn, final String ln) {
final String uid = fn.substring(0, 3).toLowerCase();
final User newUser = new User();
newUser.setDn(USERS_DN.replace("${uid}", uid));
newUser.setDisplayname(fn + " " + ln);
newUser.setEmail(fn.toLowerCase() + "." + ln.toLowerCase() + "@example.com");
newUser.setFirstname(fn);
newUser.setLastname(ln);
newUser.setLogin(uid);
newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678");
newUser.setPassword("geheim");
return newUser;
}
}

View File

@ -11,48 +11,48 @@ import de.jalin.ldapadmin.beans.User;
public class TestCreateUser {
private static final String USERS_DN = "uid=pet,ou=users,dc=saastest,dc=example,dc=com";
private static final String USERS_DN = "uid=pet,ou=users,dc=saastest,dc=example,dc=com";
private LDAPSession session;
private LDAPSession session;
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Peter Petersen");
newUser.setEmail("peter.petersen@example.com");
newUser.setFirstname("Peter");
newUser.setLastname("Petersen");
newUser.setLogin("pet");
newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Peter Petersen");
newUser.setEmail("peter.petersen@example.com");
newUser.setFirstname("Peter");
newUser.setLastname("Petersen");
newUser.setLogin("pet");
newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
}

View File

@ -11,51 +11,51 @@ import de.jalin.ldapadmin.beans.User;
public class TestDeleteUser {
private static final String USERS_DN = "uid=hei,ou=users,dc=saastest,dc=example,dc=com";
private static final String USERS_DN = "uid=hei,ou=users,dc=saastest,dc=example,dc=com";
private LDAPSession session;
private LDAPSession session;
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Hein Hanssen");
newUser.setEmail("hein.hanssen@example.com");
newUser.setFirstname("Hein");
newUser.setLastname("Hanssen");
newUser.setLogin("hei");
newUser.setMobile("0163 4434567");
newUser.setPhone("030 44345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
dao.delete(createdUser);
final User deletedUser = dao.loadUsers().get(USERS_DN);
assertNull("should be removed", deletedUser);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Hein Hanssen");
newUser.setEmail("hein.hanssen@example.com");
newUser.setFirstname("Hein");
newUser.setLastname("Hanssen");
newUser.setLogin("hei");
newUser.setMobile("0163 4434567");
newUser.setPhone("030 44345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
dao.delete(createdUser);
final User deletedUser = dao.loadUsers().get(USERS_DN);
assertNull("should be removed", deletedUser);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
}

View File

@ -11,51 +11,51 @@ import de.jalin.ldapadmin.beans.User;
public class TestReadUser {
private static final String USERS_DN = "uid=chr,ou=users,dc=saastest,dc=example,dc=com";
private static final String USERS_DN = "uid=chr,ou=users,dc=saastest,dc=example,dc=com";
private LDAPSession session;
private LDAPSession session;
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Chris Christansen");
newUser.setEmail("chris.christansen@example.com");
newUser.setFirstname("Chris");
newUser.setLastname("Christansen");
newUser.setLogin("chr");
newUser.setMobile("0163 8834567");
newUser.setPhone("030 88345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
final User readUser = dao.read(USERS_DN);
assertNotNull(readUser);
assertTrue("chris.christansen@example.com".equals(readUser.getEmail()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Chris Christansen");
newUser.setEmail("chris.christansen@example.com");
newUser.setFirstname("Chris");
newUser.setLastname("Christansen");
newUser.setLogin("chr");
newUser.setMobile("0163 8834567");
newUser.setPhone("030 88345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
final User readUser = dao.read(USERS_DN);
assertNotNull(readUser);
assertTrue("chris.christansen@example.com".equals(readUser.getEmail()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
}

View File

@ -15,57 +15,57 @@ import de.jalin.ldapadmin.beans.User;
public class TestUpdateAsBindUser {
private static final String USERS_DN = "uid=pau,ou=users,dc=saastest,dc=example,dc=com";
private static final String USERS_DN = "uid=pau,ou=users,dc=saastest,dc=example,dc=com";
private LDAPSession session;
private LDAPSession session;
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=application,ou=bind,dc=saastest,dc=example,dc=com", "app-secret");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=application,ou=bind,dc=saastest,dc=example,dc=com", "app-secret");
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Paul Paulsen");
newUser.setEmail("paul.paulsen@example.com");
newUser.setFirstname("Paul");
newUser.setLastname("Pausen");
newUser.setLogin("pau");
newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
createdUser.setLastname("Paulsen");
createdUser.setPassword("strenggeheim");
dao.update(createdUser);
final User updatedUser = dao.loadUsers().get(USERS_DN);
assertTrue("should be updated", "Paulsen".equals(updatedUser.getLastname()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Paul Paulsen");
newUser.setEmail("paul.paulsen@example.com");
newUser.setFirstname("Paul");
newUser.setLastname("Pausen");
newUser.setLogin("pau");
newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
createdUser.setLastname("Paulsen");
createdUser.setPassword("strenggeheim");
dao.update(createdUser);
final User updatedUser = dao.loadUsers().get(USERS_DN);
assertTrue("should be updated", "Paulsen".equals(updatedUser.getLastname()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
}

View File

@ -17,68 +17,68 @@ import de.jalin.ldapadmin.beans.User;
public class TestUpdateAsSimpleUser {
private static final String USERS_DN = "uid=mic,ou=users,dc=saastest,dc=example,dc=com";
private static final String USERS_DN = "uid=mic,ou=users,dc=saastest,dc=example,dc=com";
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@Before
public void setUp() throws Exception {
final LDAPSession bindUserSession = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=application,ou=bind,dc=saastest,dc=example,dc=com", "app-secret");
final UsersDAO dao = new UsersDAO(bindUserSession);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Paul Petersen");
newUser.setEmail("paul.petersen@example.com");
newUser.setFirstname("Paul");
newUser.setLastname("Petersen");
newUser.setLogin("plp");
newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678");
newUser.setPassword("geheim");
dao.create(newUser);
bindUserSession.close();
}
@Before
public void setUp() throws Exception {
final LDAPSession bindUserSession = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=application,ou=bind,dc=saastest,dc=example,dc=com", "app-secret");
final UsersDAO dao = new UsersDAO(bindUserSession);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Paul Petersen");
newUser.setEmail("paul.petersen@example.com");
newUser.setFirstname("Paul");
newUser.setLastname("Petersen");
newUser.setLogin("plp");
newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678");
newUser.setPassword("geheim");
dao.create(newUser);
bindUserSession.close();
}
@After
public void tearDown() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
@AfterClass
public static void tearDownClass() throws Exception {
// Thread.sleep(10 * 60000L);
}
}
@Test
public void test() {
try {
final LDAPSession simpleUserSession = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=plp,ou=users,dc=saastest,dc=example,dc=com", "geheim");
final UsersDAO dao = new UsersDAO(simpleUserSession);
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Micha Michaelsen");
newUser.setEmail("micha.michaelsen@example.com");
newUser.setFirstname("Michael");
newUser.setLastname("Michaelsen");
newUser.setLogin("mic");
newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678");
newUser.setPassword("geheim");
try {
dao.create(newUser);
dao.loadUsers().get(USERS_DN);
fail("should not exist");
} catch (LDAPSessionException e) {
assertTrue(e.getCause() instanceof NoPermissionException);
}
simpleUserSession.close();
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException | NamingException e) {
fail(e.getMessage());
}
}
@Test
public void test() {
try {
final LDAPSession simpleUserSession = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=plp,ou=users,dc=saastest,dc=example,dc=com", "geheim");
final UsersDAO dao = new UsersDAO(simpleUserSession);
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Micha Michaelsen");
newUser.setEmail("micha.michaelsen@example.com");
newUser.setFirstname("Michael");
newUser.setLastname("Michaelsen");
newUser.setLogin("mic");
newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678");
newUser.setPassword("geheim");
try {
dao.create(newUser);
dao.loadUsers().get(USERS_DN);
fail("should not exist");
} catch (LDAPSessionException e) {
assertTrue(e.getCause() instanceof NoPermissionException);
}
simpleUserSession.close();
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException | NamingException e) {
fail(e.getMessage());
}
}
}

View File

@ -14,53 +14,53 @@ import de.jalin.ldapadmin.beans.User;
public class TestUpdateUser {
private static final String USERS_DN = "uid=kla,ou=users,dc=saastest,dc=example,dc=com";
private static final String USERS_DN = "uid=kla,ou=users,dc=saastest,dc=example,dc=com";
private LDAPSession session;
private LDAPSession session;
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@BeforeClass
public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@Before
public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@After
public void tearDown() throws Exception {
session.close();
session = null;
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Klaas Clahsen");
newUser.setEmail("klaas.clahsen@example.com");
newUser.setFirstname("Klaas");
newUser.setLastname("Klahsen");
newUser.setLogin("kla");
newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
createdUser.setLastname("Clahsen");
createdUser.setPassword("strenggeheim");
dao.update(createdUser);
final User updatedUser = dao.loadUsers().get(USERS_DN);
assertTrue("should be updated", "Clahsen".equals(updatedUser.getLastname()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
@Test
public void test() {
final UsersDAO dao = new UsersDAO(session);
try {
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser);
final User newUser = new User();
newUser.setDn(USERS_DN);
newUser.setDisplayname("Klaas Clahsen");
newUser.setEmail("klaas.clahsen@example.com");
newUser.setFirstname("Klaas");
newUser.setLastname("Klahsen");
newUser.setLogin("kla");
newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678");
newUser.setPassword("geheim");
dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser);
createdUser.setLastname("Clahsen");
createdUser.setPassword("strenggeheim");
dao.update(createdUser);
final User updatedUser = dao.loadUsers().get(USERS_DN);
assertTrue("should be updated", "Clahsen".equals(updatedUser.getLastname()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage());
}
}
}