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() { public User getUser() {
return user; return user;
} }
public void setUser(User user) { public void setUser(User user) {
this.user = user; this.user = user;
} }
public Group getGroup() { public Group getGroup() {
return group; return group;
} }
public void setGroup(Group group) { public void setGroup(Group group) {
this.group = group; this.group = group;
} }
public String getChecked() { public String getChecked() {
return user != null && group != null && user.getGroups().contains(group.getDn()) ? "checked" : ""; //$NON-NLS-1$ //$NON-NLS-2$ 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() { public User() {
groups = new ArrayList<String>(); groups = new ArrayList<String>();
} }
public User(final String login) { public User(final String login) {
this.login = login; this.login = login;
groups = new ArrayList<String>(); groups = new ArrayList<String>();
} }
public String getLogin() { public String getLogin() {
return login; return login;
} }
public void setLogin(String login) { public void setLogin(String login) {
this.login = login; this.login = login;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public void setAndValidatePassword(String password) throws SimplePasswordException { public void setAndValidatePassword(String password) throws SimplePasswordException {
final PasswordValidator validator = new PasswordValidator(); final PasswordValidator validator = new PasswordValidator();
validator.validate(password); validator.validate(password);
this.password = password; this.password = password;
} }
public String getFirstname() { public String getFirstname() {
return firstname; return firstname;
} }
public void setFirstname(String firstname) { public void setFirstname(String firstname) {
this.firstname = firstname; this.firstname = firstname;
} }
public String getLastname() { public String getLastname() {
return lastname; return lastname;
} }
public void setLastname(String lastname) { public void setLastname(String lastname) {
this.lastname = lastname; this.lastname = lastname;
} }
public String getDisplayname() { public String getDisplayname() {
return displayname; return displayname;
} }
public void setDisplayname(String displayname) { public void setDisplayname(String displayname) {
this.displayname = displayname; this.displayname = displayname;
} }
public String getEmail() { public String getEmail() {
return email; return email;
} }
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
public String getPhone() { public String getPhone() {
return phone; return phone;
} }
public void setPhone(String phone) { public void setPhone(String phone) {
this.phone = phone; this.phone = phone;
} }
public String getMobile() { public String getMobile() {
return mobile; return mobile;
} }
public void setMobile(String mobile) { public void setMobile(String mobile) {
this.mobile = mobile; this.mobile = mobile;
} }
public List<String> getGroups() { public List<String> getGroups() {
return groups; return groups;
} }
public void setGroups(List<String> groups) { public void setGroups(List<String> groups) {
this.groups = groups; this.groups = groups;
} }
@Override @Override
public String toString() { public String toString() {
return getFirstname() + " " + getLastname() + " (" + getLogin() + ", " + getEmail() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ return getFirstname() + " " + getLastname() + " (" + getLogin() + ", " + getEmail() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
} }
@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,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 fieldname;
private final String condition; private final String condition;
public ValidationException(final String fieldname, final String condition) { public ValidationException(final String fieldname, final String condition) {
this.fieldname = fieldname; this.fieldname = fieldname;
this.condition = condition; this.condition = condition;
} }
public String getFieldname() { public String getFieldname() {
return fieldname; return fieldname;
} }
public String getCondition() { public String getCondition() {
return condition; 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() { public String getName() {
return name; 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 { public LDAPSession(final String providerURL, final String principal, final String password) throws LDAPSessionException {
final Properties env = new Properties(); final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$ 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("com.sun.jndi.ldap.connect.pool", "true"); //$NON-NLS-1$ //$NON-NLS-2$
env.put(Context.PROVIDER_URL, providerURL); env.put(Context.PROVIDER_URL, providerURL);
env.put(Context.SECURITY_AUTHENTICATION, "simple"); //$NON-NLS-1$ env.put(Context.SECURITY_AUTHENTICATION, "simple"); //$NON-NLS-1$
env.put(Context.SECURITY_PRINCIPAL, principal); env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_CREDENTIALS, password);
try { try {
ctx = new InitialDirContext(env); ctx = new InitialDirContext(env);
} catch (NamingException e) { } catch (NamingException e) {
throw new LDAPSessionException(e); throw new LDAPSessionException(e);
} }
createOrgUnitNodesIfNotExist(); createOrgUnitNodesIfNotExist();
} }
public String getStringValue(final Attributes attribs, final String attrName) throws LDAPSessionException { public String getStringValue(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName); final Attribute attribute = attribs.get(attrName);
if (attribute == null) { if (attribute == null) {
return null; return null;
} }
try { try {
return (String) attribute.get(); return (String) attribute.get();
} catch (NamingException e) { } catch (NamingException e) {
throw new LDAPSessionException(e); throw new LDAPSessionException(e);
} }
} }
public byte[] getBytesValue(final Attributes attribs, final String attrName) throws LDAPSessionException { public byte[] getBytesValue(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName); final Attribute attribute = attribs.get(attrName);
if (attribute == null) { if (attribute == null) {
return null; return null;
} }
try { try {
return (byte[]) attribute.get(); return (byte[]) attribute.get();
} catch (NamingException e) { } catch (NamingException e) {
throw new LDAPSessionException(e); throw new LDAPSessionException(e);
} }
} }
public List<String> getListOfValues(final Attributes attribs, final String attrName) throws LDAPSessionException { public List<String> getListOfValues(final Attributes attribs, final String attrName) throws LDAPSessionException {
final Attribute attribute = attribs.get(attrName); final Attribute attribute = attribs.get(attrName);
if (attribute == null) { if (attribute == null) {
return null; return null;
} }
try { try {
final int size = attribute.size(); final int size = attribute.size();
List<String> listOfValues = new ArrayList<String>(); List<String> listOfValues;
for (int idx = 0; idx < size; idx++) { listOfValues = new ArrayList<>();
listOfValues.add((String) attribute.get(idx)); for (int idx = 0; idx < size; idx++) {
} listOfValues.add((String) attribute.get(idx));
return listOfValues; }
} catch (NamingException e) { return listOfValues;
throw new LDAPSessionException(e); } catch (NamingException e) {
} throw new LDAPSessionException(e);
} }
}
public String createSubcontext(final String subcontext, final BasicAttributes attributes) throws LDAPSessionException, AlreadyBoundException { public String createSubcontext(final String subcontext, final BasicAttributes attributes) throws LDAPSessionException, AlreadyBoundException {
try { try {
final DirContext dirContext = ctx.createSubcontext(subcontext, attributes); final DirContext dirContext = ctx.createSubcontext(subcontext, attributes);
return dirContext.getNameInNamespace(); return dirContext.getNameInNamespace();
} catch (NameAlreadyBoundException e) { } catch (NameAlreadyBoundException e) {
throw new AlreadyBoundException(subcontext); throw new AlreadyBoundException(subcontext);
} catch (NamingException e) { } catch (NamingException e) {
throw new LDAPSessionException(e); throw new LDAPSessionException(e);
} }
} }
public List<SearchResult> search(final String name, final String attribName, final String attribValue) throws LDAPSessionException { public List<SearchResult> search(final String name, final String attribName, final String attribValue) throws LDAPSessionException {
final List<SearchResult> searchResult = new ArrayList<SearchResult>(); final List<SearchResult> searchResult;
try { searchResult = new ArrayList<>();
Attributes matchingAttributes = new BasicAttributes(); try {
matchingAttributes.put(attribName, attribValue); Attributes matchingAttributes = new BasicAttributes();
final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, matchingAttributes); matchingAttributes.put(attribName, attribValue);
while (searchEnum.hasMore()) { final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, matchingAttributes);
searchResult.add(searchEnum.next()); while (searchEnum.hasMore()) {
} searchResult.add(searchEnum.next());
return searchResult; }
} catch (NamingException e) { return searchResult;
throw new LDAPSessionException(e); } catch (NamingException e) {
} throw new LDAPSessionException(e);
} }
}
public List<SearchResult> search(final String name) throws LDAPSessionException { public List<SearchResult> search(final String name) throws LDAPSessionException {
final List<SearchResult> searchResult = new ArrayList<SearchResult>(); final List<SearchResult> searchResult;
try { searchResult = new ArrayList<>();
final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, null); try {
while (searchEnum.hasMore()) { final NamingEnumeration<SearchResult> searchEnum = ctx.search(name, null);
searchResult.add(searchEnum.next()); while (searchEnum.hasMore()) {
} searchResult.add(searchEnum.next());
return searchResult; }
} catch (NamingException e) { return searchResult;
throw new LDAPSessionException(e); } catch (NamingException e) {
} throw new LDAPSessionException(e);
} }
}
public Attributes getAttributes(final String dn) throws LDAPSessionException { public Attributes getAttributes(final String dn) throws LDAPSessionException {
try { try {
return ctx.getAttributes(dn); return ctx.getAttributes(dn);
} catch (NamingException e) { } catch (NamingException e) {
throw new LDAPSessionException(e); throw new LDAPSessionException(e);
} }
} }
public void modifyAttributes(final String name, final ModificationItem[] mods) throws LDAPSessionException { public void modifyAttributes(final String name, final ModificationItem[] mods) throws LDAPSessionException {
try { try {
ctx.modifyAttributes(name, mods); ctx.modifyAttributes(name, mods);
} catch (NamingException e) { } catch (NamingException e) {
throw new LDAPSessionException(e); throw new LDAPSessionException(e);
} }
} }
public void unbind(final String searchPattern, final String id) throws LDAPSessionException { public void unbind(final String searchPattern, final String id) throws LDAPSessionException {
try { try {
ctx.unbind(searchPattern.replace("${id}", id)); //$NON-NLS-1$ ctx.unbind(searchPattern.replace("${id}", id)); //$NON-NLS-1$
} catch (NamingException e) { } catch (NamingException e) {
throw new LDAPSessionException(e); throw new LDAPSessionException(e);
} }
} }
public void close() throws NamingException { public void close() throws NamingException {
if (ctx != null) { if (ctx != null) {
ctx.close(); ctx.close();
ctx = null; ctx = null;
} }
} }
private void createOrgUnitNodesIfNotExist() throws LDAPSessionException { private void createOrgUnitNodesIfNotExist() throws LDAPSessionException {
try { try {
final BasicAttributes usersAttributes = new BasicAttributes(); final BasicAttributes usersAttributes = new BasicAttributes();
final BasicAttribute usersObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$ final BasicAttribute usersObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
usersObjClass.add("top"); //$NON-NLS-1$ usersObjClass.add("top"); //$NON-NLS-1$
usersObjClass.add("organizationalUnit"); //$NON-NLS-1$ usersObjClass.add("organizationalUnit"); //$NON-NLS-1$
usersAttributes.put(usersObjClass); usersAttributes.put(usersObjClass);
usersAttributes.put("ou", "users"); //$NON-NLS-1$ //$NON-NLS-2$ usersAttributes.put("ou", "users"); //$NON-NLS-1$ //$NON-NLS-2$
ctx.createSubcontext("ou=users", usersAttributes); //$NON-NLS-1$ ctx.createSubcontext("ou=users", usersAttributes); //$NON-NLS-1$
} catch (NamingException e) { } catch (NamingException e) {
if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) { if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) {
throw new LDAPSessionException(e); throw new LDAPSessionException(e);
} }
} }
try { try {
final BasicAttributes groupsAttributes = new BasicAttributes(); final BasicAttributes groupsAttributes = new BasicAttributes();
final BasicAttribute groupsObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$ final BasicAttribute groupsObjClass = new BasicAttribute("objectClass"); //$NON-NLS-1$
groupsObjClass.add("top"); //$NON-NLS-1$ groupsObjClass.add("top"); //$NON-NLS-1$
groupsObjClass.add("organizationalUnit"); //$NON-NLS-1$ groupsObjClass.add("organizationalUnit"); //$NON-NLS-1$
groupsAttributes.put(groupsObjClass); groupsAttributes.put(groupsObjClass);
groupsAttributes.put("ou", "groups"); //$NON-NLS-1$ //$NON-NLS-2$ groupsAttributes.put("ou", "groups"); //$NON-NLS-1$ //$NON-NLS-2$
ctx.createSubcontext("ou=groups", groupsAttributes); //$NON-NLS-1$ ctx.createSubcontext("ou=groups", groupsAttributes); //$NON-NLS-1$
} catch (NamingException e) { } catch (NamingException e) {
if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) { if (!((e instanceof NameAlreadyBoundException) || (e instanceof NoPermissionException))) {
throw new LDAPSessionException(e); 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() { public String getGroupName() {
return groupName; 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; private final String fieldname;
public RequiredAttributeException(final String fieldname) { public RequiredAttributeException(final String fieldname) {
this.fieldname = fieldname; this.fieldname = fieldname;
} }
public String getFieldname() { public String getFieldname() {
return fieldname; 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 public SortedMap<String, User> loadUsers() throws LDAPSessionException {
{ final SortedMap<String, User> usersHash = new TreeMap<String, User>();
final SortedMap<String, User> usersHash = new TreeMap<String, User>(); final List<SearchResult> enumeration = session.search("ou=users"); //$NON-NLS-1$
final List<SearchResult> enumeration = session.search("ou=users"); //$NON-NLS-1$ for (SearchResult result : enumeration) {
for (SearchResult result : enumeration) { final Attributes attribs = result.getAttributes();
final Attributes attribs = result.getAttributes(); final User usr = new User();
final User usr = new User(); usr.setFirstname(session.getStringValue(attribs, "givenName")); //$NON-NLS-1$
usr.setFirstname(session.getStringValue(attribs, "givenName")); //$NON-NLS-1$ usr.setLastname(session.getStringValue(attribs, "sn")); //$NON-NLS-1$
usr.setLastname(session.getStringValue(attribs, "sn")); //$NON-NLS-1$ usr.setEmail(session.getStringValue(attribs, "mail")); //$NON-NLS-1$
usr.setEmail(session.getStringValue(attribs, "mail")); //$NON-NLS-1$ usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$ usr.setPhone(session.getStringValue(attribs, "telephoneNumber")); //$NON-NLS-1$
usr.setPhone(session.getStringValue(attribs, "telephoneNumber")); //$NON-NLS-1$ usr.setMobile(session.getStringValue(attribs, "mobile")); //$NON-NLS-1$
usr.setMobile(session.getStringValue(attribs, "mobile")); //$NON-NLS-1$ usr.setDisplayname(session.getStringValue(attribs, "displayName")); //$NON-NLS-1$
usr.setDisplayname(session.getStringValue(attribs, "displayName")); //$NON-NLS-1$ usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$ usr.setDn(result.getNameInNamespace());
usr.setDn(result.getNameInNamespace()); usersHash.put(usr.getDn(), usr);
usersHash.put(usr.getDn(), usr); }
} return usersHash;
return usersHash; }
}
public void create(final User usr) throws LDAPSessionException, RequiredAttributeException, AlreadyBoundException { 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();
if (!hasValue(uid)) { if (!hasValue(uid)) {
throw new RequiredAttributeException("uid"); //$NON-NLS-1$ throw new RequiredAttributeException("uid"); //$NON-NLS-1$
} }
assert uid != null; assert uid != 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("person"); //$NON-NLS-1$ objClass.add("person"); //$NON-NLS-1$
objClass.add("organizationalPerson"); //$NON-NLS-1$ objClass.add("organizationalPerson"); //$NON-NLS-1$
objClass.add("inetOrgPerson"); //$NON-NLS-1$ objClass.add("inetOrgPerson"); //$NON-NLS-1$
attributes.put(objClass); attributes.put(objClass);
final String firstName = usr.getFirstname(); final String firstName = usr.getFirstname();
if (hasValue(firstName)) { if (hasValue(firstName)) {
attributes.put("givenName", firstName); //$NON-NLS-1$ attributes.put("givenName", firstName); //$NON-NLS-1$
} }
final String lastname = usr.getLastname(); final String lastname = usr.getLastname();
if (!hasValue(lastname)) { if (!hasValue(lastname)) {
throw new RequiredAttributeException("lastname"); //$NON-NLS-1$ throw new RequiredAttributeException("lastname"); //$NON-NLS-1$
} }
attributes.put("sn", lastname); //$NON-NLS-1$ attributes.put("sn", lastname); //$NON-NLS-1$
final String email = usr.getEmail(); final String email = usr.getEmail();
if (hasValue(email)) { if (hasValue(email)) {
attributes.put("mail", email); //$NON-NLS-1$ attributes.put("mail", email); //$NON-NLS-1$
} }
attributes.put("uid", uid); //$NON-NLS-1$ attributes.put("uid", uid); //$NON-NLS-1$
attributes.put("cn", uid); //$NON-NLS-1$ attributes.put("cn", uid); //$NON-NLS-1$
final String telephone = usr.getPhone(); final String telephone = usr.getPhone();
if (hasValue(telephone)) { if (hasValue(telephone)) {
attributes.put("telephoneNumber", telephone); //$NON-NLS-1$ attributes.put("telephoneNumber", telephone); //$NON-NLS-1$
} }
final String mobile = usr.getMobile(); final String mobile = usr.getMobile();
if (hasValue(mobile)) { if (hasValue(mobile)) {
attributes.put("mobile", mobile); //$NON-NLS-1$ attributes.put("mobile", mobile); //$NON-NLS-1$
} }
final String comment = usr.getDisplayname(); final String comment = usr.getDisplayname();
if (hasValue(comment)) { if (hasValue(comment)) {
attributes.put("displayName", comment); //$NON-NLS-1$ attributes.put("displayName", comment); //$NON-NLS-1$
} else { } else {
attributes.put("displayName", firstName == null ? lastname : lastname + ", " + firstName); //$NON-NLS-1$ //$NON-NLS-2$ attributes.put("displayName", firstName == null ? lastname : lastname + ", " + firstName); //$NON-NLS-1$ //$NON-NLS-2$
} }
final String password = usr.getPassword(); final String password = usr.getPassword();
if (!hasValue(password)) { if (!hasValue(password)) {
throw new RequiredAttributeException("password"); //$NON-NLS-1$ throw new RequiredAttributeException("password"); //$NON-NLS-1$
} }
attributes.put("userPassword", 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$ final String dn = session.createSubcontext("uid=${uid},ou=users".replace("${uid}", uid), attributes); //$NON-NLS-1$ //$NON-NLS-2$
usr.setDn(dn); usr.setDn(dn);
} }
public User read(final String dn) throws LDAPSessionException { 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 Attributes attribs = session.getAttributes(dn.substring(0, dn.indexOf("ou=users") + 8)); //$NON-NLS-1$
final User usr = new User(); final User usr = new User();
usr.setFirstname(session.getStringValue(attribs, "givenName")); //$NON-NLS-1$ usr.setFirstname(session.getStringValue(attribs, "givenName")); //$NON-NLS-1$
usr.setLastname(session.getStringValue(attribs, "sn")); //$NON-NLS-1$ usr.setLastname(session.getStringValue(attribs, "sn")); //$NON-NLS-1$
usr.setEmail(session.getStringValue(attribs, "mail")); //$NON-NLS-1$ usr.setEmail(session.getStringValue(attribs, "mail")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$ usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setPhone(session.getStringValue(attribs, "telephoneNumber")); //$NON-NLS-1$ usr.setPhone(session.getStringValue(attribs, "telephoneNumber")); //$NON-NLS-1$
usr.setMobile(session.getStringValue(attribs, "mobile")); //$NON-NLS-1$ usr.setMobile(session.getStringValue(attribs, "mobile")); //$NON-NLS-1$
usr.setDisplayname(session.getStringValue(attribs, "displayName")); //$NON-NLS-1$ usr.setDisplayname(session.getStringValue(attribs, "displayName")); //$NON-NLS-1$
usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$ usr.setLogin(session.getStringValue(attribs, "uid")); //$NON-NLS-1$
usr.setDn(dn); usr.setDn(dn);
return usr; return usr;
} }
public void update(final User usr) throws LDAPSessionException { public void update(final User usr) throws LDAPSessionException {
assert usr != null; assert usr != null;
final String uid = usr.getLogin(); final String uid = usr.getLogin();
assert uid != null; assert uid != null;
final Attributes attribs = session.getAttributes( final Attributes attribs = session.getAttributes(
"uid=${uid},ou=users".replace("${uid}", uid)); //$NON-NLS-1$ //$NON-NLS-2$ "uid=${uid},ou=users".replace("${uid}", uid)); //$NON-NLS-1$ //$NON-NLS-2$
final List<ModificationItem> updates = new ArrayList<ModificationItem>(); final List<ModificationItem> updates = new ArrayList<ModificationItem>();
addStringAttrUpdate(updates, attribs, "displayName", usr.getDisplayname()); //$NON-NLS-1$ addStringAttrUpdate(updates, attribs, "displayName", usr.getDisplayname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "mail", usr.getEmail()); //$NON-NLS-1$ addStringAttrUpdate(updates, attribs, "mail", usr.getEmail()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "givenName", usr.getFirstname()); //$NON-NLS-1$ addStringAttrUpdate(updates, attribs, "givenName", usr.getFirstname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "sn", usr.getLastname()); //$NON-NLS-1$ addStringAttrUpdate(updates, attribs, "sn", usr.getLastname()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "mobile", usr.getMobile()); //$NON-NLS-1$ addStringAttrUpdate(updates, attribs, "mobile", usr.getMobile()); //$NON-NLS-1$
addStringAttrUpdate(updates, attribs, "telephoneNumber", usr.getPhone()); //$NON-NLS-1$ addStringAttrUpdate(updates, attribs, "telephoneNumber", usr.getPhone()); //$NON-NLS-1$
addPasswordUpdate(updates, "userPassword", usr.getPassword()); //$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$ session.modifyAttributes("uid=${uid},ou=users".replace("${uid}", uid), updates.toArray(new ModificationItem[]{})); //$NON-NLS-1$ //$NON-NLS-2$
} }
public void delete(final User user) throws LDAPSessionException { public void delete(final User user) throws LDAPSessionException {
assert user != null; assert user != null;
session.unbind("uid=${id},ou=users", user.getLogin()); //$NON-NLS-1$ session.unbind("uid=${id},ou=users", user.getLogin()); //$NON-NLS-1$
} }
private boolean hasValue(final String email) { private boolean hasValue(final String email) {
return email != null && !email.isEmpty(); return email != null && !email.isEmpty();
} }
private void addStringAttrUpdate(final List<ModificationItem> updates, private void addStringAttrUpdate(final List<ModificationItem> updates,
final Attributes attribs, final String attributeName, final String newValue) throws LDAPSessionException { final Attributes attribs, final String attributeName, final String newValue) throws LDAPSessionException {
final String oldValue = session.getStringValue(attribs, attributeName); final String oldValue = session.getStringValue(attribs, attributeName);
final BasicAttribute basicAttribute = new BasicAttribute(attributeName); final BasicAttribute basicAttribute = new BasicAttribute(attributeName);
if (hasValue(newValue)) { if (hasValue(newValue)) {
if (!newValue.equals(oldValue)) { if (!newValue.equals(oldValue)) {
basicAttribute.add(newValue); basicAttribute.add(newValue);
int ldapOp = DirContext.REPLACE_ATTRIBUTE; int ldapOp = DirContext.REPLACE_ATTRIBUTE;
if (oldValue == null) { if (oldValue == null) {
ldapOp = DirContext.ADD_ATTRIBUTE; ldapOp = DirContext.ADD_ATTRIBUTE;
} }
final ModificationItem modificationItem = new ModificationItem(ldapOp, basicAttribute); final ModificationItem modificationItem = new ModificationItem(ldapOp, basicAttribute);
updates.add(modificationItem); updates.add(modificationItem);
} }
} else { } else {
if (hasValue(oldValue)) { if (hasValue(oldValue)) {
updates.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute)); updates.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute));
} }
} }
} }
private void addPasswordUpdate(final List<ModificationItem> updates, private void addPasswordUpdate(final List<ModificationItem> updates,
final String attributeName, final String newValue) throws LDAPSessionException { final String attributeName, final String newValue) throws LDAPSessionException {
if (hasValue(newValue)) { if (hasValue(newValue)) {
updates.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, updates.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute(attributeName, newValue))); 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, User> users;
private SortedMap<String, Group> groups; private SortedMap<String, Group> groups;
protected LDAPSession ldapSession; protected LDAPSession ldapSession;
protected Properties config; protected Properties config;
protected void loadData() { protected void loadData() {
users = new TreeMap<>(); users = new TreeMap<>();
groups = new TreeMap<>(); groups = new TreeMap<>();
} }
protected User getUser(final String uid) { protected User getUser(final String uid) {
return users.get(uid); return users.get(uid);
} }
protected Group getGroup(final String gid) { protected Group getGroup(final String gid) {
return groups.get(gid); return groups.get(gid);
} }
@Override @Override
public void init() throws ServletException { public void init() throws ServletException {
super.init(); super.init();
final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties"); //$NON-NLS-1$ final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties"); //$NON-NLS-1$
config = new Properties(); config = new Properties();
try { try {
config.load(inputStream); 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$ 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) { } catch (IOException | LDAPSessionException e) {
LOG.severe(e.getMessage()); LOG.severe(e.getMessage());
throw new ServletException(e); throw new ServletException(e);
} }
} }
@Override @Override
public void destroy() { public void destroy() {
super.destroy(); super.destroy();
try { try {
ldapSession.close(); ldapSession.close();
} catch (NamingException e) { } catch (NamingException e) {
LOG.severe(e.getMessage()); LOG.severe(e.getMessage());
} }
} }
protected void throwServletException(final HttpSession session, final Exception e) throws ServletException protected void throwServletException(final HttpSession session, final Exception e) throws ServletException {
{ session.setAttribute("servletexception", e); //$NON-NLS-1$
session.setAttribute("servletexception", e); //$NON-NLS-1$ LOG.severe(e.getMessage());
LOG.severe(e.getMessage()); throw new ServletException(e);
throw new ServletException(e); }
}
protected void cleanSession(final HttpSession httpSession) { protected void cleanSession(final HttpSession httpSession) {
httpSession.removeAttribute("errormessage"); //$NON-NLS-1$ httpSession.removeAttribute("errormessage"); //$NON-NLS-1$
httpSession.removeAttribute("successmessage"); //$NON-NLS-1$ httpSession.removeAttribute("successmessage"); //$NON-NLS-1$
httpSession.removeAttribute("servletexception"); //$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 UsersDAO usersDAO = new UsersDAO(ldapSession);
try {
final SortedMap<String, User> users = usersDAO.loadUsers();
httpSession.setAttribute("users", users); //$NON-NLS-1$
if (groupDN != null && groupDN.length() > 9) {
httpSession.setAttribute("group", groupsDAO.readGroup(groupDN, users)); //$NON-NLS-1$
} else {
httpSession.setAttribute("group", new Group()); //$NON-NLS-1$
}
} catch (LDAPSessionException e) {
throwServletException(httpSession, e);
}
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
}
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession); @Override
final UsersDAO usersDAO = new UsersDAO(ldapSession); protected void doPost(HttpServletRequest req, HttpServletResponse resp)
try { throws ServletException, IOException {
final SortedMap<String, User> users = usersDAO.loadUsers(); final Messages messages = new Messages(req.getLocale());
httpSession.setAttribute("users", users); //$NON-NLS-1$ final String pathInfo = req.getPathInfo();
if (groupDN != null && groupDN.length() > 9) { String dn = ""; //$NON-NLS-1$
httpSession.setAttribute("group", groupsDAO.readGroup(groupDN, users)); //$NON-NLS-1$ if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') {
} else { dn = pathInfo.substring(1);
httpSession.setAttribute("group", new Group()); //$NON-NLS-1$ }
} String operation = req.getParameter("op"); //$NON-NLS-1$
} catch (LDAPSessionException e) { if (operation == null || operation.isEmpty()) {
throwServletException(httpSession, e); operation = "none"; //$NON-NLS-1$
} }
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$ final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
} final Group grp = new Group();
final List<String> members;
@Override members = new ArrayList<>();
protected void doPost(HttpServletRequest req, HttpServletResponse resp) final HttpSession httpSession = req.getSession();
throws ServletException, IOException { cleanSession(httpSession);
final Messages messages = new Messages(req.getLocale()); @SuppressWarnings("unchecked")
final String pathInfo = req.getPathInfo(); final SortedMap<String, User> usersHash = (SortedMap<String, User>) httpSession.getAttribute("users"); //$NON-NLS-1$
String dn = ""; //$NON-NLS-1$ final Iterator<String> userDNIterator = usersHash.keySet().iterator();
if (pathInfo != null && pathInfo.length() > 1 && pathInfo.charAt(0) == '/') { while (userDNIterator.hasNext()) {
dn = pathInfo.substring(1); final String userDN = userDNIterator.next();
} final User usr = usersHash.get(userDN);
String operation = req.getParameter("op"); //$NON-NLS-1$ final String isChecked = req.getParameter("check_user_" + usr.getLogin()); //$NON-NLS-1$
if (operation == null || operation.isEmpty()) { if (isChecked != null && !isChecked.isEmpty()) {
operation = "none"; //$NON-NLS-1$ members.add(usr.getDn());
} }
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession); }
final Group grp = new Group(); grp.setMembers(members);
final List<String> members; try {
members = new ArrayList<>(); if ("edit".equals(operation) && !dn.isEmpty()) { //$NON-NLS-1$
final HttpSession httpSession = req.getSession(); final Group oldValue = groupsDAO.readGroup(dn, usersHash);
cleanSession(httpSession); grp.setDn(dn);
@SuppressWarnings("unchecked") final SortedMap<String, User> usersHash = (SortedMap<String, User>) httpSession.getAttribute("users"); //$NON-NLS-1$ grp.setName(oldValue.getName());
final Iterator<String> userDNIterator = usersHash.keySet().iterator(); if (grp.getMembers().isEmpty()) {
while (userDNIterator.hasNext()) { httpSession.setAttribute("group", grp); //$NON-NLS-1$
final String userDN = userDNIterator.next(); httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
final User usr = usersHash.get(userDN); req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
final String isChecked = req.getParameter("check_user_" + usr.getLogin()); //$NON-NLS-1$ return;
if (isChecked != null && !isChecked.isEmpty()) { }
members.add(usr.getDn()); try {
} groupsDAO.update(grp);
} } catch (NoGroupMembersException e) {
grp.setMembers(members); httpSession.setAttribute("group", grp); //$NON-NLS-1$
try { httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
if ("edit".equals(operation) && !dn.isEmpty()) { //$NON-NLS-1$ req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
final Group oldValue = groupsDAO.readGroup(dn, usersHash); return;
grp.setDn(dn); }
grp.setName(oldValue.getName()); }
if (grp.getMembers().isEmpty()) { if ("delete".equals(operation) && !dn.isEmpty()) { //$NON-NLS-1$
httpSession.setAttribute("group", grp); //$NON-NLS-1$ final Group oldValue = groupsDAO.readGroup(dn, usersHash);
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$ grp.setDn(dn);
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$ grp.setName(oldValue.getName());
return; groupsDAO.delete(grp);
} }
try { if ("create".equals(operation)) { //$NON-NLS-1$
groupsDAO.update(grp); final String grpName = req.getParameter("name"); //$NON-NLS-1$
} catch (NoGroupMembersException e) { grp.setName(grpName);
httpSession.setAttribute("group", grp); //$NON-NLS-1$ if (grp.getMembers().isEmpty()) {
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$ httpSession.setAttribute("group", grp); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$ httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$
return; req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$
} return;
} }
if ("delete".equals(operation) && !dn.isEmpty()) { //$NON-NLS-1$ try {
final Group oldValue = groupsDAO.readGroup(dn, usersHash); groupsDAO.create(grp);
grp.setDn(dn); } catch (AlreadyBoundException e) {
grp.setName(oldValue.getName()); httpSession.setAttribute("group", grp); //$NON-NLS-1$
groupsDAO.delete(grp); 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$
if ("create".equals(operation)) { //$NON-NLS-1$ return;
final String grpName = req.getParameter("name"); //$NON-NLS-1$ }
grp.setName(grpName); resp.sendRedirect(req.getContextPath() + req.getServletPath() + "/" + grp.getDn()); //$NON-NLS-1$
if (grp.getMembers().isEmpty()) { } else {
httpSession.setAttribute("group", grp); //$NON-NLS-1$ if ("delete".equals(operation)) { //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("GroupServlet.no_empty_group")); //$NON-NLS-1$ //$NON-NLS-2$ resp.sendRedirect(req.getContextPath() + "/groups"); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/group.jsp").forward(req, resp); //$NON-NLS-1$ } else {
return; resp.sendRedirect(req.getContextPath() + req.getServletPath() + pathInfo);
} }
try { }
groupsDAO.create(grp); } catch (LDAPSessionException e) {
} catch (AlreadyBoundException e) { throwServletException(httpSession, 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 @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(); cleanSession(httpSession);
cleanSession(httpSession); 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 { final SortedMap<String, User> loadedUsers = usersDAO.loadUsers();
final SortedMap<String, User> loadedUsers = usersDAO.loadUsers(); httpSession.setAttribute("users", loadedUsers); //$NON-NLS-1$
httpSession.setAttribute("users", loadedUsers); //$NON-NLS-1$ httpSession.setAttribute("groups", groupsDAO.loadGroups(loadedUsers)); //$NON-NLS-1$
httpSession.setAttribute("groups", groupsDAO.loadGroups(loadedUsers)); //$NON-NLS-1$ } catch (LDAPSessionException e) {
} catch (LDAPSessionException e) { throwServletException(httpSession, e);
throwServletException(httpSession, e); }
} req.getRequestDispatcher("/WEB-INF/groups.jsp").forward(req, resp); //$NON-NLS-1$
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 @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();
cleanSession(httpSession); cleanSession(httpSession);
httpSession.invalidate(); httpSession.invalidate();
resp.sendRedirect(httpSession.getServletContext().getContextPath() + "/"); //$NON-NLS-1$ resp.sendRedirect(httpSession.getServletContext().getContextPath() + "/"); //$NON-NLS-1$
} }
} }

View File

@ -6,19 +6,19 @@ 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 static final String BUNDLE_NAME = "de.jalin.ldapadmin.admin.web.messages"; //$NON-NLS-1$
private final ResourceBundle resourceBundle; private final ResourceBundle resourceBundle;
public Messages(final Locale requestLocale) { public Messages(final Locale requestLocale) {
resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, requestLocale); resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, requestLocale);
} }
public String getString(final String key) { public String getString(final String key) {
try { try {
return resourceBundle.getString(key); return resourceBundle.getString(key);
} catch (MissingResourceException e) { } catch (MissingResourceException e) {
return '!' + key + '!'; 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 @Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException { throws CertificateException {
} }
@Override @Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException { throws CertificateException {
} }
@Override @Override
public X509Certificate[] getAcceptedIssuers() { public X509Certificate[] getAcceptedIssuers() {
return null; 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$
smtpPort = config.getProperty("smtp.port", "25"); //$NON-NLS-1$ //$NON-NLS-2$
smtpFrom = config.getProperty("smtp.from", "nobody@localhost"); //$NON-NLS-1$ //$NON-NLS-2$
}
@Override @Override
public void init() throws ServletException { protected void doGet(HttpServletRequest req, HttpServletResponse resp)
super.init(); throws ServletException, IOException {
smtpHost = config.getProperty("smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$ final HttpSession httpSession = req.getSession();
smtpPort = config.getProperty("smtp.port", "25"); //$NON-NLS-1$ //$NON-NLS-2$ cleanSession(httpSession);
smtpFrom = config.getProperty("smtp.from", "nobody@localhost"); //$NON-NLS-1$ //$NON-NLS-2$ final String token = req.getParameter("token"); //$NON-NLS-1$
} if (token != null && !token.isEmpty()) {
final File passwdResetFile = new File("/tmp/passwd" + token + ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
@Override if (passwdResetFile.exists() && passwdResetFile.canRead()) {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) try (final BufferedReader reader = new BufferedReader(new FileReader(passwdResetFile))) {
throws ServletException, IOException { final String[] uidAndEMail = reader.readLine().split(":"); //$NON-NLS-1$
final HttpSession httpSession = req.getSession(); final UsersDAO usrDAO = new UsersDAO(ldapSession);
cleanSession(httpSession); final User usr = usrDAO.read("uid=" + uidAndEMail[0] + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$
final String token = req.getParameter("token"); //$NON-NLS-1$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
if (token != null && !token.isEmpty()) { req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
final File passwdResetFile = new File("/tmp/passwd" + token + ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$ return;
if (passwdResetFile.exists() && passwdResetFile.canRead()) { } catch (LDAPSessionException e) {
try (final BufferedReader reader = new BufferedReader(new FileReader(passwdResetFile))) { LOG.warning("no valid password reset request");
final String[] uidAndEMail = reader.readLine().split(":"); //$NON-NLS-1$ httpSession.setAttribute("errormessage", new Messages(req.getLocale()).getString("ResetPasswordServlet.no_valid_passwordreset_request")); //$NON-NLS-1$ //$NON-NLS-2$
final UsersDAO usrDAO = new UsersDAO(ldapSession); req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
final User usr = usrDAO.read("uid=" + uidAndEMail[0] + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$ return;
httpSession.setAttribute("user", usr); //$NON-NLS-1$ }
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (LDAPSessionException e) {
LOG.warning("no valid password reset request");
httpSession.setAttribute("errormessage", new Messages(req.getLocale()).getString("ResetPasswordServlet.no_valid_passwordreset_request")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
}
}
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
}
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final Messages messages = new Messages(req.getLocale());
final HttpSession httpSession = req.getSession();
cleanSession(httpSession);
final UsersDAO usrDAO = new UsersDAO(ldapSession);
final String loginParam = req.getParameter("login"); //$NON-NLS-1$
final User sessUsr = (User) httpSession.getAttribute("user"); //$NON-NLS-1$
if (loginParam != null && sessUsr != null && loginParam.equals(sessUsr.getLogin())) {
final String password1 = req.getParameter("password"); //$NON-NLS-1$
final String password2 = req.getParameter("password2"); //$NON-NLS-1$
if (password1 != null && !password1.isEmpty()) {
if (password2 == null || !password2.equals(password1)) {
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} else {
try {
sessUsr.setAndValidatePassword(password1);
usrDAO.update(sessUsr);
httpSession.setAttribute("successmessage", messages.getString("ResetPasswordServlet.password_changed")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (SimplePasswordException e) {
httpSession.setAttribute("user", sessUsr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
} catch (LDAPSessionException e) {
final String excMessage = e.getMessage();
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("user", sessUsr); //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.invalid_password_reuse")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/new-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
throwServletException(httpSession, e);
}
}
}
}
final String loginOrEMail = req.getParameter("loginoremail"); //$NON-NLS-1$
final File tempFile = File.createTempFile("passwd", ".tmp", new File("/tmp")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
try (final PrintStream printStream = new PrintStream(tempFile)) {
String email = ""; //$NON-NLS-1$
String login = ""; //$NON-NLS-1$
String salutation = ""; //$NON-NLS-1$
if (loginOrEMail != null) {
if (loginOrEMail.contains("@")) { //$NON-NLS-1$
final SortedMap<String,User> usersMap = usrDAO.loadUsers();
final Collection<User> allUsers = usersMap.values();
for (User usr : allUsers) {
if (usr.getEmail() != null && usr.getEmail().equalsIgnoreCase(loginOrEMail)) {
login = usr.getLogin();
email = usr.getEmail();
salutation = usr.getFirstname() + " " + usr.getLastname(); //$NON-NLS-1$
}
}
} else {
final User usr = usrDAO.read("uid=" + loginOrEMail + ",ou=users,"); //$NON-NLS-1$ //$NON-NLS-2$
if (usr != null) {
login = usr.getLogin();
email = usr.getEmail();
salutation = usr.getFirstname() + " " + usr.getLastname(); //$NON-NLS-1$
}
}
if (login.isEmpty() || email.isEmpty()) {
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.error_sending_password_reset")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
printStream.println(login + ":" + email); //$NON-NLS-1$
}
final StringBuffer messageText = new StringBuffer(messages.getString("ResetPasswordServlet.email_greeting")); //$NON-NLS-1$
messageText.append(salutation);
messageText.append(messages.getString("ResetPasswordServlet.email_content")); //$NON-NLS-1$
messageText.append(req.getRequestURL().toString().replaceAll("^http\\:", "https://"));
messageText.append("?token="); //$NON-NLS-1$
final String filename = tempFile.getName();
messageText.append(filename.substring(6,filename.length()-4));
messageText.append(messages.getString("ResetPasswordServlet.email_signature")); //$NON-NLS-1$
smtpSend(smtpHost, smtpPort, messages, smtpFrom, email, messages.getString("ResetPasswordServlet.email_subject"), messageText.toString()); //$NON-NLS-1$ //$NON-NLS-2$
} catch (LDAPSessionException | IOException e) {
LOG.severe("smtp problem");
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.error_sending_password_reset")); //$NON-NLS-1$ //$NON-NLS-2$
req.getRequestDispatcher("/WEB-INF/reset-password.jsp").forward(req, resp); //$NON-NLS-1$
return;
}
httpSession.invalidate();
resp.sendRedirect(httpSession.getServletContext().getContextPath() + "/"); //$NON-NLS-1$
}
private static void smtpSend(final String smtpHost, final String smtpPort, final Messages messages, final String fromAddress, final String toAddress, final String subject, final String text) throws IOException {
final SMTPClient client = new SMTPClient();
final String canonicalHostName = InetAddress.getLocalHost().getHostName();
client.connect(smtpHost, Integer.parseInt(smtpPort));
int reply = client.getReplyCode();
if (!SMTPReply.isPositiveCompletion(reply)) {
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email_server")); //$NON-NLS-1$
}
client.login(canonicalHostName);
client.setSender(fromAddress.trim());
client.addRecipient(toAddress.trim());
final Writer sendMessageData = client.sendMessageData();
if (sendMessageData == null) {
throw new IOException(messages.getString("ResetPasswordServlet.error_sending_email_relay")); //$NON-NLS-1$
}
try (PrintWriter wr = new PrintWriter(sendMessageData)) {
final SimpleSMTPHeader header = new SimpleSMTPHeader(fromAddress, toAddress, subject);
header.addHeaderField("Content-Type", "text/plain; charset=ISO-8859-15");
header.addHeaderField("Content-Transfer-Encoding", "8bit");
wr.write(header.toString());
wr.write(text);
} }
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 @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 login = req.getParameter("login"); //$NON-NLS-1$ final String login = req.getParameter("login"); //$NON-NLS-1$
final String firstname = req.getParameter("firstname"); //$NON-NLS-1$ final String firstname = req.getParameter("firstname"); //$NON-NLS-1$
final String lastname = req.getParameter("lastname"); //$NON-NLS-1$ final String lastname = req.getParameter("lastname"); //$NON-NLS-1$
final String email = req.getParameter("email"); //$NON-NLS-1$ final String email = req.getParameter("email"); //$NON-NLS-1$
final String phone = req.getParameter("phone"); //$NON-NLS-1$ final String phone = req.getParameter("phone"); //$NON-NLS-1$
final String mobile = req.getParameter("mobile"); //$NON-NLS-1$ final String mobile = req.getParameter("mobile"); //$NON-NLS-1$
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 = new User(); final User usr = new User();
if (!dn.isEmpty()) { if (!dn.isEmpty()) {
usr.setDn(dn); usr.setDn(dn);
} }
usr.setLogin(login); usr.setLogin(login);
usr.setFirstname(firstname); usr.setFirstname(firstname);
usr.setLastname(lastname); usr.setLastname(lastname);
usr.setDisplayname(lastname + ", " + firstname); //$NON-NLS-1$ usr.setDisplayname(lastname + ", " + firstname); //$NON-NLS-1$
usr.setEmail(email); usr.setEmail(email);
usr.setPhone(phone); usr.setPhone(phone);
usr.setMobile(mobile); usr.setMobile(mobile);
final List<String> memberships; final List<String> memberships;
memberships = new ArrayList<>(); memberships = new ArrayList<>();
@SuppressWarnings("unchecked") final SortedMap<String, Group> groupsHash = (SortedMap<String, Group>) httpSession.getAttribute("groups"); //$NON-NLS-1$ @SuppressWarnings("unchecked")
final Iterator<String> groupDNIterator = groupsHash.keySet().iterator(); final SortedMap<String, Group> groupsHash = (SortedMap<String, Group>) httpSession.getAttribute("groups"); //$NON-NLS-1$
while (groupDNIterator.hasNext()) { final Iterator<String> groupDNIterator = groupsHash.keySet().iterator();
final String groupDN = groupDNIterator.next(); while (groupDNIterator.hasNext()) {
final Group grp = groupsHash.get(groupDN); final String groupDN = groupDNIterator.next();
final String isChecked = req.getParameter("check_group_" + grp.getName()); //$NON-NLS-1$ final Group grp = groupsHash.get(groupDN);
if (isChecked != null && !isChecked.isEmpty()) { final String isChecked = req.getParameter("check_group_" + grp.getName()); //$NON-NLS-1$
memberships.add(grp.getDn()); if (isChecked != null && !isChecked.isEmpty()) {
} memberships.add(grp.getDn());
} }
usr.setGroups(memberships); }
try { usr.setGroups(memberships);
validatePhone(messages, "phone", phone); //$NON-NLS-1$ try {
validatePhone(messages, "mobile", mobile); //$NON-NLS-1$ validatePhone(messages, "phone", phone); //$NON-NLS-1$
validateEMail(messages, email); validatePhone(messages, "mobile", mobile); //$NON-NLS-1$
validateLastName(messages, lastname); validateEMail(messages, email);
if (password != null && !password.isEmpty()) { validateLastName(messages, lastname);
if (password2 == null || !password2.equals(password)) { if (password != null && !password.isEmpty()) {
throw new ValidationException("password2", messages.getString("UserServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$ if (password2 == null || !password2.equals(password)) {
} else { throw new ValidationException("password2", messages.getString("UserServlet.passwords_donot_match")); //$NON-NLS-1$ //$NON-NLS-2$
usr.setAndValidatePassword(password); } else {
} usr.setAndValidatePassword(password);
} }
} catch (SimplePasswordException e) { }
httpSession.setAttribute("user", usr); //$NON-NLS-1$ } catch (SimplePasswordException e) {
httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$ httpSession.setAttribute("errormessage", messages.getString("ResetPasswordServlet.simple_password")); //$NON-NLS-1$ //$NON-NLS-2$
return; req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
} catch (ValidationException e) { return;
httpSession.setAttribute("user", usr); //$NON-NLS-1$ } catch (ValidationException e) {
httpSession.setAttribute("errormessage", messages.getString("UserServlet.input_field") + " \"" + e.getFieldname() + "\" " + e.getCondition()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$ httpSession.setAttribute("errormessage", messages.getString("UserServlet.input_field") + " \"" + e.getFieldname() + "\" " + e.getCondition()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return; req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
} return;
final GroupsDAO groupsDAO = new GroupsDAO(ldapSession); }
try { final GroupsDAO groupsDAO = new GroupsDAO(ldapSession);
if ("edit".equals(operation)) { //$NON-NLS-1$ try {
final User oldValue = usersDAO.read(dn); if ("edit".equals(operation)) { //$NON-NLS-1$
usr.setLogin(oldValue.getLogin()); final User oldValue = usersDAO.read(dn);
usr.setDn(dn); usr.setLogin(oldValue.getLogin());
usersDAO.update(usr); usr.setDn(dn);
groupsDAO.updateMemberships(usr); usersDAO.update(usr);
} groupsDAO.updateMemberships(usr);
if ("delete".equals(operation)) { //$NON-NLS-1$ }
final User oldValue = usersDAO.read(dn); if ("delete".equals(operation)) { //$NON-NLS-1$
usr.setLogin(oldValue.getLogin()); final User oldValue = usersDAO.read(dn);
usr.setDn(dn); usr.setLogin(oldValue.getLogin());
usr.getGroups().clear(); usr.setDn(dn);
groupsDAO.updateMemberships(usr); usr.getGroups().clear();
usersDAO.delete(usr); groupsDAO.updateMemberships(usr);
} usersDAO.delete(usr);
if ("create".equals(operation)) { //$NON-NLS-1$ }
usr.setLogin(login); if ("create".equals(operation)) { //$NON-NLS-1$
usersDAO.create(usr); usr.setLogin(login);
groupsDAO.updateMemberships(usr); usersDAO.create(usr);
resp.sendRedirect(req.getContextPath() + req.getServletPath() + "/" + usr.getDn()); //$NON-NLS-1$ groupsDAO.updateMemberships(usr);
} else { resp.sendRedirect(req.getContextPath() + req.getServletPath() + "/" + usr.getDn()); //$NON-NLS-1$
if ("delete".equals(operation)) { //$NON-NLS-1$ } else {
resp.sendRedirect(req.getContextPath() + "/users"); //$NON-NLS-1$ if ("delete".equals(operation)) { //$NON-NLS-1$
} else { resp.sendRedirect(req.getContextPath() + "/users"); //$NON-NLS-1$
resp.sendRedirect(req.getContextPath() + req.getServletPath() + pathInfo); } else {
} resp.sendRedirect(req.getContextPath() + req.getServletPath() + pathInfo);
} }
} catch (LDAPSessionException e) { }
final String excMessage = e.getMessage(); } catch (LDAPSessionException e) {
if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$ final String excMessage = e.getMessage();
httpSession.setAttribute("user", usr); //$NON-NLS-1$ if (excMessage != null && excMessage.contains("invalid reuse of password")) { //$NON-NLS-1$
httpSession.setAttribute("errormessage", messages.getString("UserServlet.invalid_password_reuse")); //$NON-NLS-1$ //$NON-NLS-2$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$ httpSession.setAttribute("errormessage", messages.getString("UserServlet.invalid_password_reuse")); //$NON-NLS-1$ //$NON-NLS-2$
return; req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
} return;
throwServletException(httpSession, e); }
} catch (NoGroupMembersException e) { throwServletException(httpSession, e);
httpSession.setAttribute("user", usr); //$NON-NLS-1$ } catch (NoGroupMembersException e) {
httpSession.setAttribute("errormessage", messages.getString("UserServlet.group_last_member")); //$NON-NLS-1$ //$NON-NLS-2$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$ httpSession.setAttribute("errormessage", messages.getString("UserServlet.group_last_member")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (RequiredAttributeException e) { req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
httpSession.setAttribute("user", usr); //$NON-NLS-1$ } catch (RequiredAttributeException e) {
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$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$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$
} catch (AlreadyBoundException e) { req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$NON-NLS-1$
httpSession.setAttribute("user", usr); //$NON-NLS-1$ } catch (AlreadyBoundException e) {
httpSession.setAttribute("errormessage", messages.getString("UserServlet.user_exists")); //$NON-NLS-1$ //$NON-NLS-2$ httpSession.setAttribute("user", usr); //$NON-NLS-1$
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp); //$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 { private void validatePhone(final Messages messages, final String field, final String phone) throws ValidationException {
if (phone == null || phone.isEmpty()) { if (phone == null || phone.isEmpty()) {
return; return;
} }
final String valid = phone.trim(); final String valid = phone.trim();
if (!valid.matches("[0-9\\-\\ \\(\\)]*")) { //$NON-NLS-1$ if (!valid.matches("[0-9\\-\\ \\(\\)]*")) { //$NON-NLS-1$
throw new ValidationException(field, messages.getString("UserServlet.phone_not_valid")); //$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 { private void validateEMail(final Messages messages, final String email) throws ValidationException {
if (email == null || email.isEmpty()) { if (email == null || email.isEmpty()) {
return; return;
} }
final String valid = email.trim(); final String valid = email.trim();
if (!valid.matches("[A-Za-z0-9_+\\.\\-]*@[a-z0-9\\.\\-üöäß]*")) { //$NON-NLS-1$ 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$ 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 { private void validateLastName(final Messages messages, final String lastname) throws ValidationException {
if (lastname == null || lastname.isEmpty()) { if (lastname == null || lastname.isEmpty()) {
throw new ValidationException("lastname", messages.getString("UserServlet.is_required")); //$NON-NLS-1$ //$NON-NLS-2$ 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 @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();
cleanSession(httpSession); cleanSession(httpSession);
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 {
final SortedMap<String, User> users = usersDAO.loadUsers(); final SortedMap<String, User> users = usersDAO.loadUsers();
final SortedMap<String,Group> groups = groupsDAO.loadGroups(users); final SortedMap<String, Group> groups = groupsDAO.loadGroups(users);
httpSession.setAttribute("users", users); //$NON-NLS-1$ httpSession.setAttribute("users", users); //$NON-NLS-1$
httpSession.setAttribute("groups", groups); //$NON-NLS-1$ httpSession.setAttribute("groups", groups); //$NON-NLS-1$
} catch (LDAPSessionException e) { } catch (LDAPSessionException e) {
throwServletException(httpSession, e); throwServletException(httpSession, e);
} }
req.getRequestDispatcher("/WEB-INF/users.jsp").forward(req, resp); //$NON-NLS-1$ 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; private LDAPSession session;
@BeforeClass @BeforeClass
public static void setupClass() throws Exception { public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest"); DirectoryServiceRunner.assureServiceRunning("saastest");
} }
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim"); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
session.close(); session.close();
session = null; session = null;
} }
@Test @Test
public void test() { public void test() {
final UsersDAO udao = new UsersDAO(session); final UsersDAO udao = new UsersDAO(session);
final GroupsDAO gdao = new GroupsDAO(session); final GroupsDAO gdao = new GroupsDAO(session);
try { try {
final User newUser1 = newUsersInstance("Jan", "Janssen"); final User newUser1 = newUsersInstance("Jan", "Janssen");
udao.create(newUser1); udao.create(newUser1);
final User newUser2 = newUsersInstance("Jens", "Jenssen"); final User newUser2 = newUsersInstance("Jens", "Jenssen");
udao.create(newUser2); udao.create(newUser2);
Group login = new Group(); Group login = new Group();
login.setName("login"); login.setName("login");
login.setMembers(Arrays.asList(new String[] { newUser1.getDn(), newUser2.getDn() })); login.setMembers(Arrays.asList(new String[]{newUser1.getDn(), newUser2.getDn()}));
gdao.create(login); gdao.create(login);
Group admins = new Group(); Group admins = new Group();
admins.setName("admins"); admins.setName("admins");
admins.setMembers(Arrays.asList(new String[] { newUser1.getDn(), newUser2.getDn() })); admins.setMembers(Arrays.asList(new String[]{newUser1.getDn(), newUser2.getDn()}));
gdao.create(admins); gdao.create(admins);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { } catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage()); fail(e.getMessage());
} }
} }
private User newUsersInstance(final String fn, final String ln) { private User newUsersInstance(final String fn, final String ln) {
final String uid = fn.substring(0, 3).toLowerCase(); final String uid = fn.substring(0, 3).toLowerCase();
final User newUser = new User(); final User newUser = new User();
newUser.setDn(USERS_DN.replace("${uid}", uid)); newUser.setDn(USERS_DN.replace("${uid}", uid));
newUser.setDisplayname(fn + " " + ln); newUser.setDisplayname(fn + " " + ln);
newUser.setEmail(fn.toLowerCase() + "." + ln.toLowerCase() + "@example.com"); newUser.setEmail(fn.toLowerCase() + "." + ln.toLowerCase() + "@example.com");
newUser.setFirstname(fn); newUser.setFirstname(fn);
newUser.setLastname(ln); newUser.setLastname(ln);
newUser.setLogin(uid); newUser.setLogin(uid);
newUser.setMobile("0163 1234567"); newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678"); newUser.setPhone("030 12345678");
newUser.setPassword("geheim"); newUser.setPassword("geheim");
return newUser; 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; private LDAPSession session;
@BeforeClass @BeforeClass
public static void setupClass() throws Exception { public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest"); DirectoryServiceRunner.assureServiceRunning("saastest");
} }
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim"); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
session.close(); session.close();
session = null; session = null;
} }
@Test @Test
public void test() { public void test() {
final UsersDAO dao = new UsersDAO(session); final UsersDAO dao = new UsersDAO(session);
try { try {
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("Peter Petersen"); newUser.setDisplayname("Peter Petersen");
newUser.setEmail("peter.petersen@example.com"); newUser.setEmail("peter.petersen@example.com");
newUser.setFirstname("Peter"); newUser.setFirstname("Peter");
newUser.setLastname("Petersen"); newUser.setLastname("Petersen");
newUser.setLogin("pet"); newUser.setLogin("pet");
newUser.setMobile("0163 1234567"); newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678"); newUser.setPhone("030 12345678");
newUser.setPassword("geheim"); newUser.setPassword("geheim");
dao.create(newUser); dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN); final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser); assertNotNull("should exist", createdUser);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { } catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage()); 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; private LDAPSession session;
@BeforeClass @BeforeClass
public static void setupClass() throws Exception { public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest"); DirectoryServiceRunner.assureServiceRunning("saastest");
} }
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim"); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
session.close(); session.close();
session = null; session = null;
} }
@Test @Test
public void test() { public void test() {
final UsersDAO dao = new UsersDAO(session); final UsersDAO dao = new UsersDAO(session);
try { try {
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("Hein Hanssen"); newUser.setDisplayname("Hein Hanssen");
newUser.setEmail("hein.hanssen@example.com"); newUser.setEmail("hein.hanssen@example.com");
newUser.setFirstname("Hein"); newUser.setFirstname("Hein");
newUser.setLastname("Hanssen"); newUser.setLastname("Hanssen");
newUser.setLogin("hei"); newUser.setLogin("hei");
newUser.setMobile("0163 4434567"); newUser.setMobile("0163 4434567");
newUser.setPhone("030 44345678"); newUser.setPhone("030 44345678");
newUser.setPassword("geheim"); newUser.setPassword("geheim");
dao.create(newUser); dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN); final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser); assertNotNull("should exist", createdUser);
dao.delete(createdUser); dao.delete(createdUser);
final User deletedUser = dao.loadUsers().get(USERS_DN); final User deletedUser = dao.loadUsers().get(USERS_DN);
assertNull("should be removed", deletedUser); assertNull("should be removed", deletedUser);
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { } catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage()); 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; private LDAPSession session;
@BeforeClass @BeforeClass
public static void setupClass() throws Exception { public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest"); DirectoryServiceRunner.assureServiceRunning("saastest");
} }
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim"); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
session.close(); session.close();
session = null; session = null;
} }
@Test @Test
public void test() { public void test() {
final UsersDAO dao = new UsersDAO(session); final UsersDAO dao = new UsersDAO(session);
try { try {
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("Chris Christansen"); newUser.setDisplayname("Chris Christansen");
newUser.setEmail("chris.christansen@example.com"); newUser.setEmail("chris.christansen@example.com");
newUser.setFirstname("Chris"); newUser.setFirstname("Chris");
newUser.setLastname("Christansen"); newUser.setLastname("Christansen");
newUser.setLogin("chr"); newUser.setLogin("chr");
newUser.setMobile("0163 8834567"); newUser.setMobile("0163 8834567");
newUser.setPhone("030 88345678"); newUser.setPhone("030 88345678");
newUser.setPassword("geheim"); newUser.setPassword("geheim");
dao.create(newUser); dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN); final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser); assertNotNull("should exist", createdUser);
final User readUser = dao.read(USERS_DN); final User readUser = dao.read(USERS_DN);
assertNotNull(readUser); assertNotNull(readUser);
assertTrue("chris.christansen@example.com".equals(readUser.getEmail())); assertTrue("chris.christansen@example.com".equals(readUser.getEmail()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { } catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage()); 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; private LDAPSession session;
@BeforeClass @BeforeClass
public static void setupClass() throws Exception { public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest"); DirectoryServiceRunner.assureServiceRunning("saastest");
} }
@Before @Before
public void setUp() 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"); 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 @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
session.close(); session.close();
session = null; session = null;
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() throws Exception {
} }
@Test @Test
public void test() { public void test() {
final UsersDAO dao = new UsersDAO(session); final UsersDAO dao = new UsersDAO(session);
try { try {
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("Paul Paulsen"); newUser.setDisplayname("Paul Paulsen");
newUser.setEmail("paul.paulsen@example.com"); newUser.setEmail("paul.paulsen@example.com");
newUser.setFirstname("Paul"); newUser.setFirstname("Paul");
newUser.setLastname("Pausen"); newUser.setLastname("Pausen");
newUser.setLogin("pau"); newUser.setLogin("pau");
newUser.setMobile("0163 2234567"); newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678"); newUser.setPhone("030 22345678");
newUser.setPassword("geheim"); newUser.setPassword("geheim");
dao.create(newUser); dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN); final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser); assertNotNull("should exist", createdUser);
createdUser.setLastname("Paulsen"); createdUser.setLastname("Paulsen");
createdUser.setPassword("strenggeheim"); createdUser.setPassword("strenggeheim");
dao.update(createdUser); dao.update(createdUser);
final User updatedUser = dao.loadUsers().get(USERS_DN); final User updatedUser = dao.loadUsers().get(USERS_DN);
assertTrue("should be updated", "Paulsen".equals(updatedUser.getLastname())); assertTrue("should be updated", "Paulsen".equals(updatedUser.getLastname()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { } catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage()); 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 @BeforeClass
public static void setupClass() throws Exception { public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest"); DirectoryServiceRunner.assureServiceRunning("saastest");
} }
@Before @Before
public void setUp() 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 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 UsersDAO dao = new UsersDAO(bindUserSession);
final User newUser = new User(); final User newUser = new User();
newUser.setDn(USERS_DN); newUser.setDn(USERS_DN);
newUser.setDisplayname("Paul Petersen"); newUser.setDisplayname("Paul Petersen");
newUser.setEmail("paul.petersen@example.com"); newUser.setEmail("paul.petersen@example.com");
newUser.setFirstname("Paul"); newUser.setFirstname("Paul");
newUser.setLastname("Petersen"); newUser.setLastname("Petersen");
newUser.setLogin("plp"); newUser.setLogin("plp");
newUser.setMobile("0163 1234567"); newUser.setMobile("0163 1234567");
newUser.setPhone("030 12345678"); newUser.setPhone("030 12345678");
newUser.setPassword("geheim"); newUser.setPassword("geheim");
dao.create(newUser); dao.create(newUser);
bindUserSession.close(); bindUserSession.close();
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { 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; private LDAPSession session;
@BeforeClass @BeforeClass
public static void setupClass() throws Exception { public static void setupClass() throws Exception {
DirectoryServiceRunner.assureServiceRunning("saastest"); DirectoryServiceRunner.assureServiceRunning("saastest");
} }
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim"); session = new LDAPSession("ldap://localhost:10389/dc=saastest,dc=example,dc=com", "uid=admin,ou=system", "streng-geheim");
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
session.close(); session.close();
session = null; session = null;
} }
@Test @Test
public void test() { public void test() {
final UsersDAO dao = new UsersDAO(session); final UsersDAO dao = new UsersDAO(session);
try { try {
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("Klaas Clahsen"); newUser.setDisplayname("Klaas Clahsen");
newUser.setEmail("klaas.clahsen@example.com"); newUser.setEmail("klaas.clahsen@example.com");
newUser.setFirstname("Klaas"); newUser.setFirstname("Klaas");
newUser.setLastname("Klahsen"); newUser.setLastname("Klahsen");
newUser.setLogin("kla"); newUser.setLogin("kla");
newUser.setMobile("0163 2234567"); newUser.setMobile("0163 2234567");
newUser.setPhone("030 22345678"); newUser.setPhone("030 22345678");
newUser.setPassword("geheim"); newUser.setPassword("geheim");
dao.create(newUser); dao.create(newUser);
final User createdUser = dao.loadUsers().get(USERS_DN); final User createdUser = dao.loadUsers().get(USERS_DN);
assertNotNull("should exist", createdUser); assertNotNull("should exist", createdUser);
createdUser.setLastname("Clahsen"); createdUser.setLastname("Clahsen");
createdUser.setPassword("strenggeheim"); createdUser.setPassword("strenggeheim");
dao.update(createdUser); dao.update(createdUser);
final User updatedUser = dao.loadUsers().get(USERS_DN); final User updatedUser = dao.loadUsers().get(USERS_DN);
assertTrue("should be updated", "Clahsen".equals(updatedUser.getLastname())); assertTrue("should be updated", "Clahsen".equals(updatedUser.getLastname()));
} catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) { } catch (LDAPSessionException | RequiredAttributeException | AlreadyBoundException e) {
fail(e.getMessage()); fail(e.getMessage());
} }
} }
} }