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 { public class Group implements Serializable, LDAPBean {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String dn; private String dn;
private String name; private String name;
private List<String> members; private List<String> members;
public Group() { public Group() {
members = new ArrayList<String>(); members = new ArrayList<>();
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public List<String> getMembers() { public List<String> getMembers() {
return members; return members;
} }
public void setMembers(List<String> members) { public void setMembers(List<String> members) {
this.members = members; this.members = members;
} }
@Override @Override
public String getDn() { public String getDn() {
return dn; return dn;
} }
@Override @Override
public void setDn(String dn) { public void setDn(String dn) {
this.dn = dn; this.dn = dn;
} }
} }

View File

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

View File

@ -9,118 +9,118 @@ import de.jalin.ldapadmin.ldap.SimplePasswordException;
public class User implements Serializable, LDAPBean { public class User implements Serializable, LDAPBean {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String dn; private String dn;
private String login; private String login;
private String password; private String password;
private String firstname; private String firstname;
private String lastname; private String lastname;
private String displayname; private String displayname;
private String email; private String email;
private String phone; private String phone;
private String mobile; private String mobile;
private List<String> groups; private List<String> groups;
public User() {
groups = new ArrayList<String>();
}
public User(final String login) { public User() {
this.login = login; groups = new ArrayList<String>();
groups = new ArrayList<String>(); }
}
public String getLogin() { public User(final String login) {
return login; this.login = login;
} groups = new ArrayList<String>();
}
public void setLogin(String login) { public String getLogin() {
this.login = login; return login;
} }
public String getPassword() { public void setLogin(String login) {
return password; this.login = login;
} }
public void setPassword(String password) { public String getPassword() {
this.password = password; return password;
} }
public void setAndValidatePassword(String password) throws SimplePasswordException { public void setPassword(String password) {
final PasswordValidator validator = new PasswordValidator(); this.password = password;
validator.validate(password); }
this.password = password;
}
public String getFirstname() { public void setAndValidatePassword(String password) throws SimplePasswordException {
return firstname; final PasswordValidator validator = new PasswordValidator();
} validator.validate(password);
this.password = password;
}
public void setFirstname(String firstname) { public String getFirstname() {
this.firstname = firstname; return firstname;
} }
public String getLastname() { public void setFirstname(String firstname) {
return lastname; this.firstname = firstname;
} }
public void setLastname(String lastname) { public String getLastname() {
this.lastname = lastname; return lastname;
} }
public String getDisplayname() { public void setLastname(String lastname) {
return displayname; this.lastname = lastname;
} }
public void setDisplayname(String displayname) { public String getDisplayname() {
this.displayname = displayname; return displayname;
} }
public String getEmail() { public void setDisplayname(String displayname) {
return email; this.displayname = displayname;
} }
public void setEmail(String email) { public String getEmail() {
this.email = email; return email;
} }
public String getPhone() { public void setEmail(String email) {
return phone; this.email = email;
} }
public void setPhone(String phone) { public String getPhone() {
this.phone = phone; return phone;
} }
public String getMobile() { public void setPhone(String phone) {
return mobile; this.phone = phone;
} }
public void setMobile(String mobile) { public String getMobile() {
this.mobile = mobile; return mobile;
} }
public List<String> getGroups() { public void setMobile(String mobile) {
return groups; this.mobile = mobile;
} }
public void setGroups(List<String> groups) { public List<String> getGroups() {
this.groups = groups; return groups;
} }
@Override public void setGroups(List<String> groups) {
public String toString() { this.groups = groups;
return getFirstname() + " " + getLastname() + " (" + getLogin() + ", " + getEmail() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ }
}
@Override @Override
public String getDn() { public String toString() {
return dn; return getFirstname() + " " + getLastname() + " (" + getLogin() + ", " + getEmail() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
} }
@Override @Override
public void setDn(String dn) { public String getDn() {
this.dn = dn; return 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 { 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;
public ValidationException(final String fieldname, final String condition) { private final String fieldname;
this.fieldname = fieldname; private final String condition;
this.condition = condition;
} public ValidationException(final String fieldname, final String condition) {
this.fieldname = fieldname;
public String getFieldname() { this.condition = condition;
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 { 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) { public AlreadyBoundException(final String name) {
this.name = 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 { public class GroupsDAO {
private final LDAPSession session; private final LDAPSession session;
public GroupsDAO(final LDAPSession session) { public GroupsDAO(final LDAPSession session) {
this.session = session; this.session = session;
} }
public SortedMap<String, Group> loadGroups(final SortedMap<String, User> users) throws LDAPSessionException public SortedMap<String, Group> loadGroups(final SortedMap<String, User> users) throws LDAPSessionException {
{ final SortedMap<String, Group> list;
final SortedMap<String, Group> list = new TreeMap<String, Group>(); list = new TreeMap<>();
final List<SearchResult> searchResult = session.search("ou=groups"); //$NON-NLS-1$ final List<SearchResult> searchResult = session.search("ou=groups"); //$NON-NLS-1$
for (final SearchResult result : searchResult) { for (final SearchResult result : searchResult) {
final Attributes attribs = result.getAttributes(); final Attributes attribs = result.getAttributes();
final Group grp = new Group(); final Group grp = new Group();
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$ grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
grp.setDn(result.getNameInNamespace()); grp.setDn(result.getNameInNamespace());
final List<String> listOfMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$ final List<String> listOfMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
final String dn = grp.getDn(); final String dn = grp.getDn();
for (String userDN : listOfMembers) { listOfMembers.stream().map((userDN) -> users.get(userDN)).map((user) -> user.getGroups()).forEachOrdered((groups) -> {
final User user = users.get(userDN); groups.add(dn);
final List<String> groups = user.getGroups(); });
groups.add(dn); grp.setMembers(listOfMembers);
} list.put(dn, grp);
grp.setMembers(listOfMembers); }
list.put(dn, grp); return list;
} }
return list;
}
public void create(final Group grp) throws LDAPSessionException, AlreadyBoundException { public void create(final Group grp) throws LDAPSessionException, AlreadyBoundException {
assert grp != null; assert grp != null;
final String name = grp.getName(); final String name = grp.getName();
assert name != null; assert name != null;
final BasicAttributes attributes = new BasicAttributes(); final BasicAttributes attributes = new BasicAttributes();
final BasicAttribute objClass = new BasicAttribute("objectClass"); //$NON-NLS-1$ final BasicAttribute objClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
objClass.add("top"); //$NON-NLS-1$ objClass.add("top"); //$NON-NLS-1$
objClass.add("groupOfUniqueNames"); //$NON-NLS-1$ objClass.add("groupOfUniqueNames"); //$NON-NLS-1$
attributes.put(objClass); attributes.put(objClass);
attributes.put("cn", name); //$NON-NLS-1$ attributes.put("cn", name); //$NON-NLS-1$
final List<String> uniqueMembers = grp.getMembers(); final List<String> uniqueMembers = grp.getMembers();
final BasicAttribute uniqMembers = new BasicAttribute("uniqueMember"); //$NON-NLS-1$ final BasicAttribute uniqMembers = new BasicAttribute("uniqueMember"); //$NON-NLS-1$
if (uniqueMembers != null && uniqueMembers.size() > 0) { if (uniqueMembers != null && uniqueMembers.size() > 0) {
for (String dn : uniqueMembers) { uniqueMembers.forEach((dn) -> {
uniqMembers.add(dn); uniqMembers.add(dn);
} });
} }
attributes.put(uniqMembers); attributes.put(uniqMembers);
final String dn = session.createSubcontext("cn=${cn},ou=groups".replace("${cn}", name), attributes); //$NON-NLS-1$ //$NON-NLS-2$ final String dn = session.createSubcontext("cn=${cn},ou=groups".replace("${cn}", name), attributes); //$NON-NLS-1$ //$NON-NLS-2$
grp.setDn(dn); grp.setDn(dn);
} }
public Group readGroup(final String dn, final SortedMap<String, User> users) throws LDAPSessionException { 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 Attributes attribs = session.getAttributes(dn.substring(0, dn.indexOf("ou=groups") + 9)); //$NON-NLS-1$
final Group grp = new Group(); final Group grp = new Group();
grp.setDn(dn); grp.setDn(dn);
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$ grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
final List<String> listOfMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$ final List<String> listOfMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
for (String userDN : listOfMembers) { listOfMembers.stream().map((userDN) -> users.get(userDN)).map((user) -> user.getGroups()).forEachOrdered((groups) -> {
final User user = users.get(userDN); groups.add(dn);
final List<String> groups = user.getGroups(); });
groups.add(dn); grp.setMembers(listOfMembers);
} return grp;
grp.setMembers(listOfMembers); }
return grp;
}
public void update(final Group grp) throws LDAPSessionException, NoGroupMembersException { public void update(final Group grp) throws LDAPSessionException, NoGroupMembersException {
assert grp != null; assert grp != null;
final String name = grp.getName(); final String name = grp.getName();
assert name != null; assert name != null;
if (grp.getMembers().size() == 0) { if (grp.getMembers().isEmpty()) {
throw new NoGroupMembersException(name); throw new NoGroupMembersException(name);
} }
final BasicAttribute membersOfAttrib = new BasicAttribute("uniqueMember"); //$NON-NLS-1$ final BasicAttribute membersOfAttrib = new BasicAttribute("uniqueMember"); //$NON-NLS-1$
for (final String memberDN : grp.getMembers()) { grp.getMembers().forEach((memberDN) -> {
membersOfAttrib.add(memberDN); membersOfAttrib.add(memberDN);
} });
final ModificationItem modificationItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, membersOfAttrib); 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$ 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 { public void updateMemberships(final User usr) throws LDAPSessionException, NoGroupMembersException {
final List<SearchResult> searchResult = session.search("ou=groups"); //$NON-NLS-1$ final List<SearchResult> searchResult = session.search("ou=groups"); //$NON-NLS-1$
for (final SearchResult result : searchResult) { for (final SearchResult result : searchResult) {
final Attributes attribs = result.getAttributes(); final Attributes attribs = result.getAttributes();
final Group grp = new Group(); final Group grp = new Group();
grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$ grp.setName(session.getStringValue(attribs, "cn")); //$NON-NLS-1$
grp.setDn(result.getNameInNamespace()); grp.setDn(result.getNameInNamespace());
final List<String> listOfGroupMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$ final List<String> listOfGroupMembers = session.getListOfValues(attribs, "uniqueMember"); //$NON-NLS-1$
grp.setMembers(listOfGroupMembers); grp.setMembers(listOfGroupMembers);
final List<String> listOfUserMemberships = usr.getGroups(); final List<String> listOfUserMemberships = usr.getGroups();
if (listOfGroupMembers.contains(usr.getDn()) && !listOfUserMemberships.contains(grp.getDn())) { if (listOfGroupMembers.contains(usr.getDn()) && !listOfUserMemberships.contains(grp.getDn())) {
grp.getMembers().remove(usr.getDn()); grp.getMembers().remove(usr.getDn());
update(grp); update(grp);
} }
if (!listOfGroupMembers.contains(usr.getDn()) && listOfUserMemberships.contains(grp.getDn())) { if (!listOfGroupMembers.contains(usr.getDn()) && listOfUserMemberships.contains(grp.getDn())) {
grp.getMembers().add(usr.getDn()); grp.getMembers().add(usr.getDn());
update(grp); update(grp);
} }
} }
} }
public void delete(final Group grp) throws LDAPSessionException { public void delete(final Group grp) throws LDAPSessionException {
assert grp != null; assert grp != null;
session.unbind("cn=${id},ou=groups", grp.getName()); //$NON-NLS-1$ 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 { 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 String getStringValue(final Attributes attribs, final String attrName) throws LDAPSessionException { public LDAPSession(final String providerURL, final String principal, final String password) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName); final Properties env = new Properties();
if (attribute == null) { env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
return null; env.put("com.sun.jndi.ldap.connect.pool", "true"); //$NON-NLS-1$ //$NON-NLS-2$
} env.put(Context.PROVIDER_URL, providerURL);
try { env.put(Context.SECURITY_AUTHENTICATION, "simple"); //$NON-NLS-1$
return (String) attribute.get(); env.put(Context.SECURITY_PRINCIPAL, principal);
} catch (NamingException e) { env.put(Context.SECURITY_CREDENTIALS, password);
throw new LDAPSessionException(e); try {
} ctx = new InitialDirContext(env);
} } catch (NamingException e) {
throw new LDAPSessionException(e);
public byte[] getBytesValue(final Attributes attribs, final String attrName) throws LDAPSessionException { }
final Attribute attribute = attribs.get(attrName); createOrgUnitNodesIfNotExist();
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 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 { public String getStringValue(final Attributes attribs, final String attrName) throws LDAPSessionException {
final List<SearchResult> searchResult = new ArrayList<SearchResult>(); final Attribute attribute = attribs.get(attrName);
try { if (attribute == null) {
Attributes matchingAttributes = new BasicAttributes(); return null;
matchingAttributes.put(attribName, attribValue); }
final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, matchingAttributes); try {
while (searchEnum.hasMore()) { return (String) attribute.get();
searchResult.add(searchEnum.next()); } catch (NamingException e) {
} throw new LDAPSessionException(e);
return searchResult; }
} catch (NamingException e) { }
throw new LDAPSessionException(e);
}
}
public List<SearchResult> search(final String name) throws LDAPSessionException { public byte[] getBytesValue(final Attributes attribs, final String attrName) throws LDAPSessionException {
final List<SearchResult> searchResult = new ArrayList<SearchResult>(); final Attribute attribute = attribs.get(attrName);
try { if (attribute == null) {
final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, null); return null;
while (searchEnum.hasMore()) { }
searchResult.add(searchEnum.next()); try {
} return (byte[]) attribute.get();
return searchResult; } catch (NamingException e) {
} catch (NamingException e) { throw new LDAPSessionException(e);
throw new LDAPSessionException(e); }
} }
}
public Attributes getAttributes(final String dn) throws LDAPSessionException { public List<String> getListOfValues(final Attributes attribs, final String attrName) throws LDAPSessionException {
try { final Attribute attribute = attribs.get(attrName);
return ctx.getAttributes(dn); if (attribute == null) {
} catch (NamingException e) { return null;
throw new LDAPSessionException(e); }
} 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 void modifyAttributes(final String name, final ModificationItem[] mods) throws LDAPSessionException { public String createSubcontext(final String subcontext, final BasicAttributes attributes) throws LDAPSessionException, AlreadyBoundException {
try { try {
ctx.modifyAttributes(name, mods); final DirContext dirContext = ctx.createSubcontext(subcontext, attributes);
} catch (NamingException e) { return dirContext.getNameInNamespace();
throw new LDAPSessionException(e); } catch (NameAlreadyBoundException e) {
} throw new AlreadyBoundException(subcontext);
} catch (NamingException e) {
} throw new LDAPSessionException(e);
}
}
public void unbind(final String searchPattern, final String id) throws LDAPSessionException { public List<SearchResult> search(final String name, final String attribName, final String attribValue) throws LDAPSessionException {
try { final List<SearchResult> searchResult;
ctx.unbind(searchPattern.replace("${id}", id)); //$NON-NLS-1$ searchResult = new ArrayList<>();
} catch (NamingException e) { try {
throw new LDAPSessionException(e); 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 void close() throws NamingException { public List<SearchResult> search(final String name) throws LDAPSessionException {
if (ctx != null) { final List<SearchResult> searchResult;
ctx.close(); searchResult = new ArrayList<>();
ctx = null; 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);
}
}
private void createOrgUnitNodesIfNotExist() throws LDAPSessionException { public Attributes getAttributes(final String dn) throws LDAPSessionException {
try { try {
final BasicAttributes usersAttributes = new BasicAttributes(); return ctx.getAttributes(dn);
final BasicAttribute usersObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$ } catch (NamingException e) {
usersObjClass.add("top"); //$NON-NLS-1$ throw new LDAPSessionException(e);
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$ public void modifyAttributes(final String name, final ModificationItem[] mods) throws LDAPSessionException {
} catch (NamingException e) { try {
if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) { ctx.modifyAttributes(name, mods);
throw new LDAPSessionException(e); } catch (NamingException e) {
} 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$ public void unbind(final String searchPattern, final String id) throws LDAPSessionException {
groupsObjClass.add("organizationalUnit"); //$NON-NLS-1$ try {
groupsAttributes.put(groupsObjClass); ctx.unbind(searchPattern.replace("${id}", id)); //$NON-NLS-1$
groupsAttributes.put("ou", "groups"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (NamingException e) {
ctx.createSubcontext("ou=groups", groupsAttributes); //$NON-NLS-1$ throw new LDAPSessionException(e);
} catch (NamingException e) { }
if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) { }
throw new LDAPSessionException(e);
} 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);
}
}
}
} }

View File

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

View File

@ -2,16 +2,16 @@ package de.jalin.ldapadmin.ldap;
public class NoGroupMembersException extends Exception { 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) { public NoGroupMembersException(final String name) {
groupName = name; groupName = name;
} }
public String getGroupName() {
return groupName;
}
public String getGroupName() {
return groupName;
}
} }

View File

@ -1,40 +1,41 @@
package de.jalin.ldapadmin.ldap; package de.jalin.ldapadmin.ldap;
public class PasswordValidator { 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 { public void validate(final String password) throws SimplePasswordException {
if (password == null || password.isEmpty()) { if (password == null || password.isEmpty()) {
throw new SimplePasswordException("password required"); throw new SimplePasswordException("password required");
} }
if (password.length() < MIN_PASSWORD_LEN) { if (password.length() < MIN_PASSWORD_LEN) {
throw new SimplePasswordException("minimal password length is " + MIN_PASSWORD_LEN + " characters"); throw new SimplePasswordException("minimal password length is " + MIN_PASSWORD_LEN + " characters");
} }
int hasLowerCaseChar = 0; int hasLowerCaseChar = 0;
int hasUpperCaseChar = 0; int hasUpperCaseChar = 0;
int hasDigits = 0; int hasDigits = 0;
int hasSpecialChar = 0; int hasSpecialChar = 0;
for (int idx = 0; idx < password.length(); idx++) { for (int idx = 0; idx < password.length(); idx++) {
final char test = password.charAt(idx); final char test = password.charAt(idx);
final int type = Character.getType(test); final int type = Character.getType(test);
if (type == Character.DECIMAL_DIGIT_NUMBER) { if (type == Character.DECIMAL_DIGIT_NUMBER) {
hasDigits = 1; hasDigits = 1;
} else { } else {
if (type == Character.LOWERCASE_LETTER) { if (type == Character.LOWERCASE_LETTER) {
hasLowerCaseChar = 1; hasLowerCaseChar = 1;
} else } else {
if (type == Character.UPPERCASE_LETTER) { if (type == Character.UPPERCASE_LETTER) {
hasUpperCaseChar = 1; hasUpperCaseChar = 1;
} else } else {
hasSpecialChar = 1; 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"); 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 { public class RequiredAttributeException extends Exception {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final String fieldname;
public RequiredAttributeException(final String fieldname) { private final String fieldname;
this.fieldname = fieldname;
}
public String getFieldname() { public RequiredAttributeException(final String fieldname) {
return fieldname; this.fieldname = fieldname;
} }
public String getFieldname() {
return fieldname;
}
} }

View File

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

View File

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

View File

@ -19,64 +19,63 @@ import java.util.logging.Logger;
public class AbstractLDAPServlet extends HttpServlet { 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;
protected LDAPSession ldapSession; private SortedMap<String, User> users;
protected Properties config; private SortedMap<String, Group> groups;
protected void loadData() {
users = new TreeMap<>();
groups = new TreeMap<>();
}
protected User getUser(final String uid) {
return users.get(uid);
}
protected Group getGroup(final String gid) {
return groups.get(gid);
}
@Override protected LDAPSession ldapSession;
public void init() throws ServletException { protected Properties config;
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());
}
}
protected void throwServletException(final HttpSession session, final Exception e) throws ServletException protected void loadData() {
{ users = new TreeMap<>();
session.setAttribute("servletexception", e); //$NON-NLS-1$ groups = new TreeMap<>();
LOG.severe(e.getMessage()); }
throw new ServletException(e);
} protected User getUser(final String uid) {
return users.get(uid);
}
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 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 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.NoGroupMembersException;
import de.jalin.ldapadmin.ldap.UsersDAO; import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapGroup",urlPatterns={"/group/*"}) @WebServlet(name = "LdapGroup", urlPatterns = {"/group/*"})
public class GroupServlet extends AbstractLDAPServlet { public class GroupServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Override @Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException { throws ServletException, IOException {
final String pathInfo = req.getPathInfo(); final String pathInfo = req.getPathInfo();
String groupDN = ""; //$NON-NLS-1$ String groupDN = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') { if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
groupDN = pathInfo.substring(1); groupDN = pathInfo.substring(1);
} }
final HttpSession httpSession = req.getSession(); final HttpSession httpSession = req.getSession();
cleanSession(httpSession); cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$ String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) { if (operation == null || operation.isEmpty()) {
operation = "view"; //$NON-NLS-1$ operation = "view"; //$NON-NLS-1$
} }
httpSession.setAttribute("operation", operation); //$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("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$ 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 GroupsDAO groupsDAO = new GroupsDAO(ldapSession); final UsersDAO usersDAO = new UsersDAO(ldapSession);
final UsersDAO usersDAO = new UsersDAO(ldapSession); try {
try { final SortedMap<String, User> users = usersDAO.loadUsers();
final SortedMap<String, User> users = usersDAO.loadUsers(); httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("users", users); //$NON-NLS-1$ if (groupDN != null && groupDN.length() > 9) {
if (groupDN != null && groupDN.length() > 9) { httpSession.setAttribute("group", groupsDAO.readGroup(groupDN, users)); //$NON-NLS-1$
httpSession.setAttribute("group", groupsDAO.readGroup(groupDN, users)); //$NON-NLS-1$ } else {
} else { httpSession.setAttribute("group", new Group()); //$NON-NLS-1$
httpSession.setAttribute("group", new Group()); //$NON-NLS-1$ }
} } catch (LDAPSessionException e) {
} catch (LDAPSessionException e) { throwServletException(httpSession, e);
throwServletException(httpSession, e); }
} req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
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.LDAPSessionException;
import de.jalin.ldapadmin.ldap.UsersDAO; import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapGroups",urlPatterns={"/groups"}) @WebServlet(name = "LdapGroups", urlPatterns = {"/groups"})
public class GroupsServlet extends AbstractLDAPServlet { 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.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
@WebServlet(name="Logout",urlPatterns={"/logout"}) @WebServlet(name = "Logout", urlPatterns = {"/logout"})
public class LogoutServlet extends AbstractLDAPServlet { 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

@ -5,20 +5,20 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle; import java.util.ResourceBundle;
public class Messages { public class Messages {
private static final String BUNDLE_NAME = "de.jalin.ldapadmin.admin.web.messages"; //$NON-NLS-1$
private final ResourceBundle resourceBundle;
public Messages(final Locale requestLocale) { private static final String BUNDLE_NAME = "de.jalin.ldapadmin.admin.web.messages"; //$NON-NLS-1$
resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, requestLocale);
}
public String getString(final String key) { private final ResourceBundle resourceBundle;
try {
return resourceBundle.getString(key); public Messages(final Locale requestLocale) {
} catch (MissingResourceException e) { resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, requestLocale);
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 { public class NaiveTrustManager implements X509TrustManager {
private static final SSLContext SSL_CONTEXT; private static final SSLContext SSL_CONTEXT;
static { static {
try { try {
SSL_CONTEXT = SSLContext.getInstance("TLSv1.2"); SSL_CONTEXT = SSLContext.getInstance("TLSv1.2");
SSL_CONTEXT.init(null, new TrustManager[] { new NaiveTrustManager() }, null); SSL_CONTEXT.init(null, new TrustManager[]{new NaiveTrustManager()}, null);
SSLContext.setDefault(SSL_CONTEXT); SSLContext.setDefault(SSL_CONTEXT);
} catch (NoSuchAlgorithmException | KeyManagementException e) { } catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("Unable to initialise SSL context", e); throw new RuntimeException("Unable to initialise SSL context", e);
} }
} }
public Socket createSocket(String host, int port) throws IOException, UnknownHostException { public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return SSL_CONTEXT.getSocketFactory().createSocket(host, port); 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.SimplePasswordException;
import de.jalin.ldapadmin.ldap.UsersDAO; import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapProfile",urlPatterns={"/profile", "/profile/*"}) @WebServlet(name = "LdapProfile", urlPatterns = {"/profile", "/profile/*"})
public class ProfileServlet extends AbstractLDAPServlet { public class ProfileServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Override @Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException { throws ServletException, IOException {
final HttpSession httpSession = req.getSession(); final HttpSession httpSession = req.getSession();
String userDN = ""; //$NON-NLS-1$ String userDN = ""; //$NON-NLS-1$
try { try {
final String remoteUID = req.getRemoteUser(); final String remoteUID = req.getRemoteUser();
final List<SearchResult> list = ldapSession.search("ou=users", "uid", remoteUID); //$NON-NLS-1$ //$NON-NLS-2$ final List<SearchResult> list = ldapSession.search("ou=users", "uid", remoteUID); //$NON-NLS-1$ //$NON-NLS-2$
if (list != null && list.size() > 0) { if (list != null && list.size() > 0) {
final SearchResult first = list.get(0); final SearchResult first = list.get(0);
userDN = first.getNameInNamespace(); userDN = first.getNameInNamespace();
} }
cleanSession(httpSession); cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$ String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) { if (operation == null || operation.isEmpty()) {
operation = "profile"; //$NON-NLS-1$ operation = "profile"; //$NON-NLS-1$
} }
httpSession.setAttribute("operation", operation); //$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("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$ httpSession.setAttribute("iddisabled", "disabled"); //$NON-NLS-1$ //$NON-NLS-2$
final UsersDAO usersDAO = new UsersDAO(ldapSession); final UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession); final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
SortedMap<String, User> users = usersDAO.loadUsers(); SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$ httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(users)); //$NON-NLS-1$ httpSession.setAttribute("groups", groupsDAO.loadGroups(users)); //$NON-NLS-1$
httpSession.setAttribute("user", users.get(userDN)); //$NON-NLS-1$ httpSession.setAttribute("user", users.get(userDN)); //$NON-NLS-1$
} catch (LDAPSessionException e) { } catch (LDAPSessionException e) {
throwServletException(httpSession, e); throwServletException(httpSession, e);
} }
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$ req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
} }
@Override @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException { throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale()); final Messages messages = new Messages(req.getLocale());
final HttpSession httpSession = req.getSession(); final HttpSession httpSession = req.getSession();
cleanSession(httpSession); cleanSession(httpSession);
final String pathInfo = req.getPathInfo(); final String pathInfo = req.getPathInfo();
String dn = ""; //$NON-NLS-1$ String dn = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') { if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
dn = pathInfo.substring(1); dn = pathInfo.substring(1);
} }
String operation = req.getParameter("op"); //$NON-NLS-1$ String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) { if (operation == null || operation.isEmpty()) {
operation = "none"; //$NON-NLS-1$ operation = "none"; //$NON-NLS-1$
} }
final UsersDAO usersDAO = new UsersDAO(ldapSession); final UsersDAO usersDAO = new UsersDAO(ldapSession);
final String password = req.getParameter("password"); //$NON-NLS-1$ final String password = req.getParameter("password"); //$NON-NLS-1$
final String password2 = req.getParameter("password2"); //$NON-NLS-1$ final String password2 = req.getParameter("password2"); //$NON-NLS-1$
final User usr = (User) httpSession.getAttribute("user"); //$NON-NLS-1$ final User usr = (User) httpSession.getAttribute("user"); //$NON-NLS-1$
try { try {
if (password != null && !password.isEmpty()) { if (password != null && !password.isEmpty()) {
if (password2 == null || !password2.equals(password)) { if (password2 == null || !password2.equals(password)) {
throw new ValidationException("password2", messages.getString("ProfileServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$ throw new ValidationException("password2", messages.getString("ProfileServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
} else { } else {
usr.setAndValidatePassword(password); usr.setAndValidatePassword(password);
} }
} }
} catch (SimplePasswordException e) { } catch (SimplePasswordException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$ 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$ req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return; return;
} catch (ValidationException e) { } catch (ValidationException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$ 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$ 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$ req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return; return;
} }
try { try {
if ("password".equals(operation)) { //$NON-NLS-1$ if ("password".equals(operation)) { //$NON-NLS-1$
final User oldValue = usersDAO.read(dn); final User oldValue = usersDAO.read(dn);
usr.setLogin(oldValue.getLogin()); usr.setLogin(oldValue.getLogin());
usr.setDn(dn); usr.setDn(dn);
usersDAO.update(usr); usersDAO.update(usr);
httpSession.setAttribute("successmessage", messages.getString("ProfileServlet.password_changed")); //$NON-NLS-1$ //$NON-NLS-2$ 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("operation", "profile"); //$NON-NLS-1$ //$NON-NLS-2$
httpSession.setAttribute("user", usr); //$NON-NLS-1$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp);
} }
} catch (LDAPSessionException e) { } catch (LDAPSessionException e) {
final String excMessage = e.getMessage(); final String excMessage = e.getMessage();
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$ if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("user", usr); //$NON-NLS-1$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ProfileServlet.invalid_reuse")); //$NON-NLS-1$ //$NON-NLS-2$ 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$ req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
return; return;
} }
throwServletException(httpSession, e); 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.SimplePasswordException;
import de.jalin.ldapadmin.ldap.UsersDAO; import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="ResetPassword",urlPatterns={"/passwordreset"}) @WebServlet(name = "ResetPassword", urlPatterns = {"/passwordreset"})
public class ResetPasswordServlet extends AbstractLDAPServlet { 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; @Override
private String smtpPort; public void init() throws ServletException {
private String smtpFrom; super.init();
smtpHost = config.getProperty("smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
@Override smtpPort = config.getProperty("smtp.port", "25"); //$NON-NLS-1$ //$NON-NLS-2$
public void init() throws ServletException { smtpFrom = config.getProperty("smtp.from", "nobody@localhost"); //$NON-NLS-1$ //$NON-NLS-2$
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$ @Override
smtpFrom = config.getProperty("smtp.from", "nobody@localhost"); //$NON-NLS-1$ //$NON-NLS-2$ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
} throws ServletException, IOException {
final HttpSession httpSession = req.getSession();
@Override cleanSession(httpSession);
protected void doGet(HttpServletRequest req, HttpServletResponse resp) final String token = req.getParameter("token"); //$NON-NLS-1$
throws ServletException, IOException { if (token != null && !token.isEmpty()) {
final HttpSession httpSession = req.getSession(); final File passwdResetFile = new File("/tmp/passwd" + token + ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
cleanSession(httpSession); if (passwdResetFile.exists() && passwdResetFile.canRead()) {
final String token = req.getParameter("token"); //$NON-NLS-1$ try (final BufferedReader reader = new BufferedReader(new FileReader(passwdResetFile))) {
if (token != null && !token.isEmpty()) { final String[] uidAndEMail = reader.readLine().split(":"); //$NON-NLS-1$
final File passwdResetFile = new File("/tmp/passwd" + token + ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$ final UsersDAO usrDAO = new UsersDAO(ldapSession);
if (passwdResetFile.exists() && passwdResetFile.canRead()) { final User usr = usrDAO.read("uid=" + uidAndEMail[0] + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$
try (final BufferedReader reader = new BufferedReader(new FileReader(passwdResetFile))) { httpSession.setAttribute("user", usr); //$NON-NLS-1$
final String[] uidAndEMail = reader.readLine().split(":"); //$NON-NLS-1$ req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
final UsersDAO usrDAO = new UsersDAO(ldapSession); return;
final User usr = usrDAO.read("uid=" + uidAndEMail[0] + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (LDAPSessionException e) {
httpSession.setAttribute("user", usr); //$NON-NLS-1$ LOG.warning("no valid password reset request");
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$ httpSession.setAttribute("errormessage", new Messages(req.getLocale()).getString("ResetPasswordServlet.no_valid_passwordreset_request")); //$NON-NLS-1$ //$NON-NLS-2$
return; req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
} catch (LDAPSessionException e) { return;
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);
} }
if (!client.completePendingCommand()) { }
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email")); //$NON-NLS-1$ req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
} }
client.logout();
client.disconnect(); @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.SimplePasswordException;
import de.jalin.ldapadmin.ldap.UsersDAO; import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapUser",urlPatterns={"/user/*"}) @WebServlet(name = "LdapUser", urlPatterns = {"/user/*"})
public class UserServlet extends AbstractLDAPServlet { public class UserServlet extends AbstractLDAPServlet {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Override @Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException { throws ServletException, IOException {
final String pathInfo = req.getPathInfo(); final String pathInfo = req.getPathInfo();
String userDN = ""; //$NON-NLS-1$ String userDN = ""; //$NON-NLS-1$
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') { if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
userDN = pathInfo.substring(1); userDN = pathInfo.substring(1);
} }
final HttpSession httpSession = req.getSession(); final HttpSession httpSession = req.getSession();
cleanSession(httpSession); cleanSession(httpSession);
String operation = req.getParameter("op"); //$NON-NLS-1$ String operation = req.getParameter("op"); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) { if (operation == null || operation.isEmpty()) {
operation = "view"; //$NON-NLS-1$ operation = "view"; //$NON-NLS-1$
} }
httpSession.setAttribute("operation", operation); //$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("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$ 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 UsersDAO usersDAO = new UsersDAO(ldapSession);
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession); final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
try { try {
SortedMap<String, User> users = usersDAO.loadUsers(); SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$ httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(users)); //$NON-NLS-1$ httpSession.setAttribute("groups", groupsDAO.loadGroups(users)); //$NON-NLS-1$
if ("create".equals(operation)) { //$NON-NLS-1$ if ("create".equals(operation)) { //$NON-NLS-1$
httpSession.setAttribute("user", new User()); //$NON-NLS-1$ httpSession.setAttribute("user", new User()); //$NON-NLS-1$
} else { } else {
httpSession.setAttribute("user", users.get(userDN)); //$NON-NLS-1$ httpSession.setAttribute("user", users.get(userDN)); //$NON-NLS-1$
} }
} catch (LDAPSessionException e) { } catch (LDAPSessionException e) {
throwServletException(httpSession, e); throwServletException(httpSession, e);
} }
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$ 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 { @Override
if (phone == null || phone.isEmpty()) { protected void doPost(HttpServletRequest req, HttpServletResponse resp)
return; throws ServletException, IOException {
} final Messages messages = new Messages(req.getLocale());
final String valid = phone.trim(); final HttpSession httpSession = req.getSession();
if (!valid.matches("[0-9\\-\\ \\(\\)]*")) { //$NON-NLS-1$ cleanSession(httpSession);
throw new ValidationException(field, messages.getString("UserServlet.phone_not_valid")); //$NON-NLS-1$ 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 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 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$
}
}
} }

View File

@ -15,27 +15,27 @@ import de.jalin.ldapadmin.ldap.GroupsDAO;
import de.jalin.ldapadmin.ldap.LDAPSessionException; import de.jalin.ldapadmin.ldap.LDAPSessionException;
import de.jalin.ldapadmin.ldap.UsersDAO; import de.jalin.ldapadmin.ldap.UsersDAO;
@WebServlet(name="LdapUsers",urlPatterns={"/users"}) @WebServlet(name = "LdapUsers", urlPatterns = {"/users"})
public class UsersServlet extends AbstractLDAPServlet { 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 { 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;
@BeforeClass private LDAPSession session;
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");
}
@After @BeforeClass
public void tearDown() throws Exception { public static void setupClass() throws Exception {
session.close(); DirectoryServiceRunner.assureServiceRunning("saastest");
session = null; }
}
@Test @Before
public void test() { public void setUp() throws Exception {
final UsersDAO udao = new UsersDAO(session); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
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) { @After
final String uid = fn.substring(0, 3).toLowerCase(); public void tearDown() throws Exception {
final User newUser = new User(); session.close();
newUser.setDn(USERS_DN.replace("${uid}", uid)); session = null;
newUser.setDisplayname(fn + " " + ln); }
newUser.setEmail(fn.toLowerCase() + "." + ln.toLowerCase() + "@example.com");
newUser.setFirstname(fn); @Test
newUser.setLastname(ln); public void test() {
newUser.setLogin(uid); final UsersDAO udao = new UsersDAO(session);
newUser.setMobile("0163 1234567"); final GroupsDAO gdao = new GroupsDAO(session);
newUser.setPhone("030 12345678"); try {
newUser.setPassword("geheim"); final User newUser1 = newUsersInstance("Jan", "Janssen");
return newUser; 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;
}
} }

View File

@ -11,48 +11,48 @@ import de.jalin.ldapadmin.beans.User;
public class TestCreateUser { 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;
@BeforeClass private LDAPSession session;
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");
}
@After @BeforeClass
public void tearDown() throws Exception { public static void setupClass() throws Exception {
session.close(); DirectoryServiceRunner.assureServiceRunning("saastest");
session = null; }
}
@Test @Before
public void test() { public void setUp() throws Exception {
final UsersDAO dao = new UsersDAO(session); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
try { }
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser); @After
final User newUser = new User(); public void tearDown() throws Exception {
newUser.setDn(USERS_DN); session.close();
newUser.setDisplayname("Peter Petersen"); session = null;
newUser.setEmail("peter.petersen@example.com"); }
newUser.setFirstname("Peter");
newUser.setLastname("Petersen"); @Test
newUser.setLogin("pet"); public void test() {
newUser.setMobile("0163 1234567"); final UsersDAO dao = new UsersDAO(session);
newUser.setPhone("030 12345678"); try {
newUser.setPassword("geheim"); final User existingUser = dao.loadUsers().get(USERS_DN);
dao.create(newUser); assertNull("user already exists", existingUser);
final User createdUser = dao.loadUsers().get(USERS_DN); final User newUser = new User();
assertNotNull("should exist", createdUser); newUser.setDn(USERS_DN);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { newUser.setDisplayname("Peter Petersen");
fail(e.getMessage()); 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 { 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;
@BeforeClass private LDAPSession session;
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");
}
@After @BeforeClass
public void tearDown() throws Exception { public static void setupClass() throws Exception {
session.close(); DirectoryServiceRunner.assureServiceRunning("saastest");
session = null; }
}
@Test @Before
public void test() { public void setUp() throws Exception {
final UsersDAO dao = new UsersDAO(session); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
try { }
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser); @After
final User newUser = new User(); public void tearDown() throws Exception {
newUser.setDn(USERS_DN); session.close();
newUser.setDisplayname("Hein Hanssen"); session = null;
newUser.setEmail("hein.hanssen@example.com"); }
newUser.setFirstname("Hein");
newUser.setLastname("Hanssen"); @Test
newUser.setLogin("hei"); public void test() {
newUser.setMobile("0163 4434567"); final UsersDAO dao = new UsersDAO(session);
newUser.setPhone("030 44345678"); try {
newUser.setPassword("geheim"); final User existingUser = dao.loadUsers().get(USERS_DN);
dao.create(newUser); assertNull("user already exists", existingUser);
final User createdUser = dao.loadUsers().get(USERS_DN); final User newUser = new User();
assertNotNull("should exist", createdUser); newUser.setDn(USERS_DN);
dao.delete(createdUser); newUser.setDisplayname("Hein Hanssen");
final User deletedUser = dao.loadUsers().get(USERS_DN); newUser.setEmail("hein.hanssen@example.com");
assertNull("should be removed", deletedUser); newUser.setFirstname("Hein");
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { newUser.setLastname("Hanssen");
fail(e.getMessage()); 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 { 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;
@BeforeClass private LDAPSession session;
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");
}
@After @BeforeClass
public void tearDown() throws Exception { public static void setupClass() throws Exception {
session.close(); DirectoryServiceRunner.assureServiceRunning("saastest");
session = null; }
}
@Test @Before
public void test() { public void setUp() throws Exception {
final UsersDAO dao = new UsersDAO(session); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
try { }
final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser); @After
final User newUser = new User(); public void tearDown() throws Exception {
newUser.setDn(USERS_DN); session.close();
newUser.setDisplayname("Chris Christansen"); session = null;
newUser.setEmail("chris.christansen@example.com"); }
newUser.setFirstname("Chris");
newUser.setLastname("Christansen"); @Test
newUser.setLogin("chr"); public void test() {
newUser.setMobile("0163 8834567"); final UsersDAO dao = new UsersDAO(session);
newUser.setPhone("030 88345678"); try {
newUser.setPassword("geheim"); final User existingUser = dao.loadUsers().get(USERS_DN);
dao.create(newUser); assertNull("user already exists", existingUser);
final User createdUser = dao.loadUsers().get(USERS_DN); final User newUser = new User();
assertNotNull("should exist", createdUser); newUser.setDn(USERS_DN);
final User readUser = dao.read(USERS_DN); newUser.setDisplayname("Chris Christansen");
assertNotNull(readUser); newUser.setEmail("chris.christansen@example.com");
assertTrue("chris.christansen@example.com".equals(readUser.getEmail())); newUser.setFirstname("Chris");
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { newUser.setLastname("Christansen");
fail(e.getMessage()); 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 { 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;
@BeforeClass private LDAPSession session;
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");
}
@After @BeforeClass
public void tearDown() throws Exception { public static void setupClass() throws Exception {
session.close(); DirectoryServiceRunner.assureServiceRunning("saastest");
session = null; }
}
@AfterClass @Before
public static void tearDownClass() throws Exception { 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");
}
@Test @After
public void test() { public void tearDown() throws Exception {
final UsersDAO dao = new UsersDAO(session); session.close();
try { session = null;
final User existingUser = dao.loadUsers().get(USERS_DN); }
assertNull("user already exists", existingUser);
final User newUser = new User(); @AfterClass
newUser.setDn(USERS_DN); public static void tearDownClass() throws Exception {
newUser.setDisplayname("Paul Paulsen"); }
newUser.setEmail("paul.paulsen@example.com");
newUser.setFirstname("Paul"); @Test
newUser.setLastname("Pausen"); public void test() {
newUser.setLogin("pau"); final UsersDAO dao = new UsersDAO(session);
newUser.setMobile("0163 2234567"); try {
newUser.setPhone("030 22345678"); final User existingUser = dao.loadUsers().get(USERS_DN);
newUser.setPassword("geheim"); assertNull("user already exists", existingUser);
dao.create(newUser); final User newUser = new User();
final User createdUser = dao.loadUsers().get(USERS_DN); newUser.setDn(USERS_DN);
assertNotNull("should exist", createdUser); newUser.setDisplayname("Paul Paulsen");
createdUser.setLastname("Paulsen"); newUser.setEmail("paul.paulsen@example.com");
createdUser.setPassword("strenggeheim"); newUser.setFirstname("Paul");
dao.update(createdUser); newUser.setLastname("Pausen");
final User updatedUser = dao.loadUsers().get(USERS_DN); newUser.setLogin("pau");
assertTrue("should be updated", "Paulsen".equals(updatedUser.getLastname())); newUser.setMobile("0163 2234567");
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { newUser.setPhone("030 22345678");
fail(e.getMessage()); 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 { 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");
}
@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 @BeforeClass
public void tearDown() throws Exception { public static void setupClass() throws Exception {
} DirectoryServiceRunner.assureServiceRunning("saastest");
}
@AfterClass @Before
public static void tearDownClass() throws Exception { 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 {
}
@AfterClass
public static void tearDownClass() throws Exception {
// Thread.sleep(10 * 60000L); // Thread.sleep(10 * 60000L);
} }
@Test @Test
public void test() { public void test() {
try { 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 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 UsersDAO dao = new UsersDAO(simpleUserSession);
final User existingUser = dao.loadUsers().get(USERS_DN); final User existingUser = dao.loadUsers().get(USERS_DN);
assertNull("user already exists", existingUser); assertNull("user already exists", existingUser);
final User newUser = new User(); final User newUser = new User();
newUser.setDn(USERS_DN); newUser.setDn(USERS_DN);
newUser.setDisplayname("Micha Michaelsen"); newUser.setDisplayname("Micha Michaelsen");
newUser.setEmail("micha.michaelsen@example.com"); newUser.setEmail("micha.michaelsen@example.com");
newUser.setFirstname("Michael"); newUser.setFirstname("Michael");
newUser.setLastname("Michaelsen"); newUser.setLastname("Michaelsen");
newUser.setLogin("mic"); newUser.setLogin("mic");
newUser.setMobile("0163 2234567"); newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678"); newUser.setPhone("030 22345678");
newUser.setPassword("geheim"); newUser.setPassword("geheim");
try { try {
dao.create(newUser); dao.create(newUser);
dao.loadUsers().get(USERS_DN); dao.loadUsers().get(USERS_DN);
fail("should not exist"); fail("should not exist");
} catch (LDAPSessionException e) { } catch (LDAPSessionException e) {
assertTrue(e.getCause() instanceof NoPermissionException); assertTrue(e.getCause() instanceof NoPermissionException);
} }
simpleUserSession.close(); simpleUserSession.close();
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException | NamingException e) { } catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException | NamingException e) {
fail(e.getMessage()); fail(e.getMessage());
} }
} }
} }

View File

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