test runnung

This commit is contained in:
Peter Hormanns 2019-07-16 20:00:30 +02:00
parent af96a136a1
commit 90d4d77e4b
91 changed files with 3848 additions and 0 deletions

1
.gitignore vendored
View File

@ -4,3 +4,4 @@ pom.xml.releaseBackup
pom.xml.versionsBackup pom.xml.versionsBackup
pom.xml.next pom.xml.next
release.properties release.properties
ldap-data*

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

4
README.md Normal file
View File

@ -0,0 +1,4 @@
## LDAP Admin Application
Webapplikation zur Pflege von LDAP-Accounts und Gruppen,
eingebetteter Apache Directory Server

12
etc/jetty.xml Normal file
View File

@ -0,0 +1,12 @@
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<Call name="addBean">
<Arg>
<New class="org.eclipse.jetty.security.HashLoginService">
<Set name="name">Administration Area</Set>
<Set name="config"><SystemProperty name="jetty.home" default="."/>/etc/realm.properties</Set>
</New>
</Arg>
</Call>
</Configure>

1
etc/realm.properties Normal file
View File

@ -0,0 +1 @@
peter: Test123,login,admins

View File

@ -0,0 +1,53 @@
version: 1
dn: dc=saastest,dc=example,dc=com
objectclass: top
objectclass: domain
administrativeRole: accessControlSpecificArea
dc: saastest
dn: cn=saastestAuthenticationRequirementsACISubentry,dc=saastest,dc=example,dc=com
objectClass: accessControlSubentry
objectClass: subentry
objectClass: top
subtreeSpecification: { }
prescriptiveACI: { identificationTag "subtreeFullAccessACI", precedence 11, authenticationLevel simple, itemOrUserFirst userFirst: { userClasses { name { "uid=application,ou=bind,dc=saastest,dc=example,dc=com" } }, userPermissions { { protectedItems { entry, allUserAttributeTypesAndValues }, grantsAndDenials { grantCompare, grantBrowse, grantRename, grantRemove, grantAdd, grantRead, grantFilterMatch, grantReturnDN, grantModify } } } } }
prescriptiveACI: { identificationTag "allUsersACI", precedence 9, authenticationLevel none, itemOrUserFirst userFirst: { userClasses { allUsers }, userPermissions { { protectedItems { attributeType { userPassword } }, grantsAndDenials { denyRead, denyFilterMatch, denyCompare } }, { protectedItems { entry, allUserAttributeTypesAndValues }, grantsAndDenials { grantCompare, grantBrowse,grantDiscloseOnError, grantRead, grantFilterMatch, grantReturnDN } } } } }
cn: saastestAuthenticationRequirementsACISubentry
dn: ou=groups,dc=saastest,dc=example,dc=com
objectClass: top
objectClass: organizationalUnit
ou: groups
dn: ou=users,dc=saastest,dc=example,dc=com
objectClass: top
objectClass: organizationalUnit
ou: users
dn: ou=bind,dc=saastest,dc=example,dc=com
objectClass: top
objectClass: organizationalUnit
ou: bind
dn: uid=admin,ou=users,dc=saastest,dc=example,dc=com
objectClass: top
objectClass: inetOrgPerson
objectClass: person
objectClass: organizationalPerson
cn: system administrator
sn: administrator
displayName: Directory Superuser
uid: admin
userPassword: admin-secret
dn: uid=application,ou=bind,dc=saastest,dc=example,dc=com
objectClass: top
objectClass: inetOrgPerson
objectClass: person
objectClass: organizationalPerson
cn: application bind user
sn: administrator
displayName: Application User
uid: application
userPassword: app-secret

7
ldif/master-passwd.ldif Normal file
View File

@ -0,0 +1,7 @@
version:1
dn: uid=admin,ou=system
changetype: modify
replace: userPassword
userPassword: streng-geheim
-

121
pom.xml Normal file
View File

@ -0,0 +1,121 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.jalin.ldapadmin</groupId>
<artifactId>ldapadmin</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>LDAP Admin Webapp</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<env>dev</env>
</properties>
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-service</artifactId>
<version>2.0.0.AM25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<archiveClasses>true</archiveClasses>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.19.v20190610</version>
<configuration>
<jettyXml>etc/jetty.xml</jettyXml>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument></compilerArgument>
</configuration>
</plugin>
</plugins>
<finalName>ldapadmin</finalName>
</build>
</project>

View File

@ -0,0 +1 @@
filtered.stage=dev

View File

@ -0,0 +1 @@
filtered.stage=prod

View File

@ -0,0 +1 @@
filtered.stage=test

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,13 @@
package de.jalin.ldapadmin.ldap;
import javax.naming.NamingException;
public class LDAPSessionException extends Exception {
private static final long serialVersionUID = 1L;
public LDAPSessionException(NamingException e) {
super(e);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,4 @@
provider.url=ldap://localhost:10389/dc=example,dc=com
security.principal=uid=admin,ou=system
security.password=secret
smtp.host=localhost

View File

@ -0,0 +1,3 @@
access.denied.title=Access denied
access.denied.text=You don't have access rights to the pages for user and group administration.
access.denied.logout=logout user {0}

View File

@ -0,0 +1,3 @@
access.denied.title=Zugriff verweigert
access.denied.text=Sie haben keine Zugriffsrechte auf die Seiten zur Benutzer- und Gruppenverwaltung.
access.denied.logout=als Benutzer {0} abmelden

View File

@ -0,0 +1,3 @@
access.denied.title=Access denied
access.denied.text=You don't have access rights to the pages for user and group administration.
access.denied.logout=logout user {0}

View File

@ -0,0 +1,2 @@
contact.title=LDAP Administration
contact.text=We 'll answer your questions gladly.

View File

@ -0,0 +1,2 @@
contact.title=LDAP Administration
contact.text=Ihre Fragen beantworten wir Ihnen gern.

View File

@ -0,0 +1,2 @@
contact.title=LDAP Administration
contact.text=We 'll answer your questions gladly.

View File

@ -0,0 +1 @@
exception.title=Unexpected error

View File

@ -0,0 +1 @@
exception.title=Nicht erwarteter Fehler

View File

@ -0,0 +1 @@
exception.title=Unexpected error

View File

@ -0,0 +1,14 @@
groups.title=Groups
groups.group.title=Group
groups.create=create new group
groups.column.name=Group name
groups.column.members=Members
groups.column.operations=Operations
groups.operations.edit=update
groups.operations.update=edit group members
groups.operations.submit=submit
groups.operations.delete=delete
groups.error.title=Error!
groups.confirm.delete=Should this group be deleted?
groups.label.name=Group name
groups.label.members=Members

View File

@ -0,0 +1,14 @@
groups.title=Gruppen
groups.group.title=Gruppe
groups.create=neue Gruppe
groups.column.name=Gruppen-Kennung
groups.column.members=Mitglieder
groups.column.operations=
groups.operations.edit=ändern
groups.operations.update=Mitglieder zuordnen
groups.operations.submit=speichern
groups.operations.delete=löschen
groups.error.title=Fehler!
groups.confirm.delete=Soll diese Gruppe gelöscht werden?
groups.label.name=Gruppen-Kennung
groups.label.members=Mitglieder

View File

@ -0,0 +1,14 @@
groups.title=Groups
groups.group.title=Group
groups.create=create new group
groups.column.name=Group name
groups.column.members=Members
groups.column.operations=Operations
groups.operations.edit=update
groups.operations.update=edit group members
groups.operations.submit=submit
groups.operations.delete=delete
groups.error.title=Error!
groups.confirm.delete=Should this group be deleted?
groups.label.name=Group name
groups.label.members=Members

View File

@ -0,0 +1,13 @@
login.title=LDAP Admin
login.username=Login name
login.password=Password
login.password.repeat=Repeat password
login.reset.password=Reset password
login.error.title=Error!
login.error.message=Login failed. Check your credentials.
login.submit=login
login.password.change=Change password
password.reset.title=Restore password
password.reset.loginoremail=Login or EMail
password.reset.submit=Send password link
password.error.title=Error

View File

@ -0,0 +1,13 @@
login.title=LDAP Administration Anmeldung
login.username=Anmelde-Kennung
login.password=Passwort
login.password.repeat=Passwort-Wiederholung
login.reset.password=Passwort zur\u00fccksetzen
login.error.title=Fehler!
login.error.message=Anmeldung fehlgeschlagen. Bitte pr\u00fcfen Sie Ihre Anmelde-Daten.
login.submit=Anmelden
login.password.change=Passwort \u00e4ndern
password.reset.title=Passwort zur\u00fccksetzen
password.reset.loginoremail=Anmelde-Kennung oder E-Mail
password.reset.submit=Sende Passwort-Link
password.error.title=Fehler

View File

@ -0,0 +1,13 @@
login.title=LDAO Administration Login
login.username=Login name
login.password=Password
login.password.repeat=Repeat password
login.reset.password=Reset password
login.error.title=Error!
login.error.message=Login failed. Check your credentials.
login.submit=login
login.password.change=Change password
password.reset.title=Restore password
password.reset.loginoremail=Login or EMail
password.reset.submit=Send password link
password.error.title=Error

View File

@ -0,0 +1,2 @@
menu.title=LDAP Admin
menu.text=You can reach your applications via the following references

View File

@ -0,0 +1,2 @@
menu.title=LDAP Admin
menu.text=Sie finden Ihre Anwendungen \u00fcber die folgenden Links

View File

@ -0,0 +1,2 @@
menu.title=LDAP Admin
menu.text=You can reach your applications via the following references

View File

@ -0,0 +1,6 @@
navbar.title=LDAP Admin
navbar.toggle=Toggle navigation
navbar.item.groups=Groups
navbar.item.users=Users
navbar.item.profile=Profile
navbar.item.contact=Contact

View File

@ -0,0 +1,6 @@
navbar.title=LDAP Admin
navbar.toggle=Menue umschalten
navbar.item.groups=Gruppen
navbar.item.users=Benutzer
navbar.item.profile=mein Profil
navbar.item.contact=Kontakt

View File

@ -0,0 +1,6 @@
navbar.title=LDAP Admin
navbar.toggle=Toggle navigation
navbar.item.groups=Groups
navbar.item.users=Users
navbar.item.profile=Profile
navbar.item.contact=Contact

View File

@ -0,0 +1,23 @@
users.title=Users
users.create=create new user
users.column.login=Login
users.column.firstname=First name
users.column.lastname=Last name
users.column.groups=Groups
users.column.operations=Operations
users.label.login=Login name
users.label.firstname=First name
users.label.lastname=Last name
users.label.email=EMail address
users.label.phone=Phone
users.label.mobile=Mobile
users.label.password=Password
users.label.password.repeat=Repeat password
users.label.memberof=Member of
users.operations.edit=edit
users.operations.delete=delete
users.operations.update=submit
users.operations.changepassword=change password
users.confirm.delete=Should this user be deleted?
users.title.new=New user
users.error.title=Error!

View File

@ -0,0 +1,23 @@
users.title=Benutzer
users.create=neuer Benutzer
users.column.login=Anmelde-Kennung
users.column.firstname=Vorname
users.column.lastname=Nachname
users.column.groups=Gruppen
users.column.operations=
users.label.login=Anmelde-Kennung
users.label.firstname=Vorname
users.label.lastname=Nachname
users.label.email=E-Mail Adresse
users.label.phone=Telefon
users.label.mobile=Handy
users.label.password=Passwort
users.label.password.repeat=Passwort-Wiederholung
users.label.memberof=Gruppen-Mitgliedschaft
users.operations.edit=bearbeiten
users.operations.delete=löschen
users.operations.update=speichern
users.operations.changepassword=Passwort ändern
users.confirm.delete=Soll dieser Benutzer gelöscht werden?
users.title.new=Neuer Benutzer
users.error.title=Fehler!

View File

@ -0,0 +1,23 @@
users.title=Users
users.create=create new user
users.column.login=Login
users.column.firstname=First name
users.column.lastname=Last name
users.column.groups=Groups
users.column.operations=Operations
users.label.login=Login name
users.label.firstname=First name
users.label.lastname=Last name
users.label.email=EMail address
users.label.phone=Phone
users.label.mobile=Mobile
users.label.password=Password
users.label.password.repeat=Repeat password
users.label.memberof=Member of
users.operations.edit=edit
users.operations.delete=delete
users.operations.update=submit
users.operations.changepassword=change password
users.confirm.delete=Should this user be deleted?
users.title.new=New user
users.error.title=Error!

View File

@ -0,0 +1,28 @@
GroupServlet.no_empty_group=A groups is required to have members
GroupServlet.group_exists=This group already exists
ProfileServlet.inputfield=Field
ProfileServlet.invalid_reuse=Invalid reuse of a password known from history
ProfileServlet.password_changed=Password changed
ProfileServlet.passwords_donot_match=Passwords do not match
ResetPasswordServlet.email_content=\!\n\nYou want to reset your password?\n\nUse the follwing link:\n
ResetPasswordServlet.email_greeting=Dear
ResetPasswordServlet.email_signature=\n\nYour LDAP-service\n
ResetPasswordServlet.email_subject=reset LDAP password
ResetPasswordServlet.error_sending_email=Could not sent email
ResetPasswordServlet.error_sending_email_relay=Could not sent email (relay-error)
ResetPasswordServlet.error_sending_email_server=Could not reach email service
ResetPasswordServlet.error_sending_password_reset=Error sending email
ResetPasswordServlet.invalid_password_reuse=Invalid reuse of a password known from history. A new password is required.
ResetPasswordServlet.no_valid_passwordreset_request=Could not find a valid password request.
ResetPasswordServlet.password_changed=Password changed
ResetPasswordServlet.passwords_donot_match=Passwords do not match
ResetPasswordServlet.simple_password=Your password is too simple. It should contain at least one lowercase and uppercase letter and a digit / secial character and a minimum length of 12 characters
UserServlet.email_not_valid=No valid email address given
UserServlet.group_last_member=A group is required to have members
UserServlet.user_exists=This user already exists
UserServlet.input_field=Field
UserServlet.invalid_password_reuse=Invalid reuse of a password known from history. A new password is required.
UserServlet.is_required=is required
UserServlet.passwords_donot_match=Passwords do not match
UserServlet.phone_not_valid=is not valid, valid examples: '(040) 123456-789', '030 1234567'
UserServlet.the_input_field=Field

View File

@ -0,0 +1,28 @@
GroupServlet.no_empty_group=Eine Gruppe muss mindestens ein Mitglied haben.
GroupServlet.group_exists=Eine Gruppe mit diesem Namen existiert bereits.
ProfileServlet.inputfield=Eingabefeld
ProfileServlet.invalid_reuse=Dieses Passwort haben Sie bereits verwendet. Die Passwort-Richtlinie erfordert es, dass Sie ein neues Passwort ausw\u00e4hlen.
ProfileServlet.password_changed=Neues Passwort gespeichert
ProfileServlet.passwords_donot_match=stimmt nicht mit der ersten Passwort-Eingabe \u00fcberein
ResetPasswordServlet.email_content=\!\n\nSie wollen Ihr Passwort zur\u00fccksetzen?\n\nDann folgen Sie bitte dem folgenden Link:\n
ResetPasswordServlet.email_greeting=Hallo
ResetPasswordServlet.email_signature=\n\nIhr LDAP-Service\n
ResetPasswordServlet.email_subject=LDAP Passwort-Anforderung
ResetPasswordServlet.error_sending_email=Konnte Mail nicht senden
ResetPasswordServlet.error_sending_email_relay=Konnte Mail nicht senden (SMTP-Relay-Problem)
ResetPasswordServlet.error_sending_email_server=Konnte Mail Server nicht erreichen
ResetPasswordServlet.error_sending_password_reset=Fehler beim Versand der E-Mail f\u00fcr das Setzen eines neuen Passworts.
ResetPasswordServlet.invalid_password_reuse=Das Passwort wurde bereits verwendet. Die Passwort-Richtlinie verlangt die Definition eines neuen Passworts.
ResetPasswordServlet.no_valid_passwordreset_request=Es konnte keine g\u00fcltige Anforderung f\u00fcr ein neues Passwort zugeordnet werden.
ResetPasswordServlet.password_changed=Ihr neues Passwort ist gespeichert.
ResetPasswordServlet.passwords_donot_match=Die beiden Passwort-Eingaben stimmen nicht \u00fcberein.
ResetPasswordServlet.simple_password=Ihr Passwort ist zu einfach. Es sollte mindestens einen Klein- und Gro\u00dfbuchstaben und eine Ziffer oder Sonderzeichen enthalten sowie eine Mindestl\u00e4nge von 12 Zeichen aufweisen
UserServlet.email_not_valid=Die E-Mail-Adresse ist nicht g\u00fcltig.
UserServlet.group_last_member=Das letze Mitglied kann nicht aus der Gruppe entfernt werden. Gruppen m\u00fcssen mindestens ein Mitglied haben.
UserServlet.user_exists=Einen Benutzer mit dieser Kennung gibt es bereits.
UserServlet.input_field=Eingabefeld
UserServlet.invalid_password_reuse=Das Passwort wurde bereits verwendet. Die Passwort-Richtlinie erfordert, dass Sie ein neues Passwort vergeben.
UserServlet.is_required=muss gef\u00fcllt werden.
UserServlet.passwords_donot_match=Passwort stimmt nicht mit der ersten Eingabe \u00fcberein
UserServlet.phone_not_valid=Das Eingabeformat f\u00fcr die Telefonnummer ist nicht korrekt, bitte formatieren Sie wie im Beispiel: '(040) 123456-789' oder '030 1234567'
UserServlet.the_input_field=Das Eingabefeld

View File

@ -0,0 +1,28 @@
GroupServlet.no_empty_group=A groups is required to have members
GroupServlet.group_exists=This group already exists
ProfileServlet.inputfield=Field
ProfileServlet.invalid_reuse=Invalid reuse of a password known from history
ProfileServlet.password_changed=Password changed
ProfileServlet.passwords_donot_match=Passwords do not match
ResetPasswordServlet.email_content=\!\n\nYou want to reset your password?\n\nUse the follwing link:\n
ResetPasswordServlet.email_greeting=Dear
ResetPasswordServlet.email_signature=\n\nYour LDAP-service\n
ResetPasswordServlet.email_subject=reset LDAP password
ResetPasswordServlet.error_sending_email=Could not sent email
ResetPasswordServlet.error_sending_email_relay=Could not sent email (relay-error)
ResetPasswordServlet.error_sending_email_server=Could not reach email service
ResetPasswordServlet.error_sending_password_reset=Error sending email
ResetPasswordServlet.invalid_password_reuse=Invalid reuse of a password known from history. A new password is required.
ResetPasswordServlet.no_valid_passwordreset_request=Could not find a valid password request.
ResetPasswordServlet.password_changed=Password changed
ResetPasswordServlet.passwords_donot_match=Passwords do not match
ResetPasswordServlet.simple_password=Your password is too simple. It should contain at least one lowercase and uppercase letter and a digit / secial character and a minimum length of 12 characters
UserServlet.email_not_valid=No valid email address given
UserServlet.group_last_member=A group is required to have members
UserServlet.user_exists=This user already exists
UserServlet.input_field=Field
UserServlet.invalid_password_reuse=Invalid reuse of a password known from history. A new password is required.
UserServlet.is_required=is required
UserServlet.passwords_donot_match=Passwords do not match
UserServlet.phone_not_valid=is not valid, valid examples: '(040) 123456-789', '030 1234567'
UserServlet.the_input_field=Field

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,4 @@
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/ldapadmin"/>

View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<session-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/css/*</url-pattern>
<url-pattern>/webjars/*</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/contact.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>403</error-code>
<location>/access-denied.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/servlet-exception.jsp</location>
</error-page>
<error-page>
<error-code>503</error-code>
<location>/servlet-exception.jsp</location>
</error-page>
<security-constraint>
<web-resource-collection>
<web-resource-name>Public access</web-resource-name>
<url-pattern>*.css</url-pattern>
<url-pattern>*.js</url-pattern>
<url-pattern>/css/*</url-pattern>
<url-pattern>/webjars/*</url-pattern>
<url-pattern>/logout</url-pattern>
<url-pattern>/access-denied.jsp</url-pattern>
<url-pattern>/contact.jsp</url-pattern>
<url-pattern>/passwordreset</url-pattern>
<url-pattern>/servlet-exception.jsp</url-pattern>
</web-resource-collection>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Profile Area</web-resource-name>
<url-pattern>/profile</url-pattern>
<url-pattern>/profile/*</url-pattern>
<url-pattern>/</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admins</role-name>
<role-name>login</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Administrative Area</web-resource-name>
<url-pattern>/users</url-pattern>
<url-pattern>/users/*</url-pattern>
<url-pattern>/groups</url-pattern>
<url-pattern>/groups/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admins</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Administration Area</realm-name>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/loginfail.jsp</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>admins</role-name>
</security-role>
<security-role>
<role-name>login</role-name>
</security-role>
</web-app>

View File

@ -0,0 +1,20 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.accessdenied"/>
<!DOCTYPE html>
<html lang="${language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<c:url var="logouturl" value="/logout" />
<!-- Page Content -->
<div class="container">
<h1><fmt:message key="access.denied.title"/></h1>
<p><fmt:message key="access.denied.text"/></p>
<a href="${ logouturl }"><fmt:message key="access.denied.logout"><fmt:param value="${pageContext.request.remoteUser}"/></fmt:message></a>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,19 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.contact"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<!-- Page Content -->
<div class="container">
<h1><fmt:message key="contact.title"/></h1>
<p><fmt:message key="contact.text"/></p>
<a href="mailto:service@example.com">E-Mail an <em>service@example.com</em></a>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,13 @@
body { padding-top: 70px; }
.additional-space-top { margin-top:12px; }
.additional-space-bottom { margin-bottom:12px; }
.alert {
padding: 8px 35px 8px 14px;
margin-bottom: 18px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
background-color: #fcf8e3;
border: 1px solid #fbeed5;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}

73
src/main/webapp/group.jsp Normal file
View File

@ -0,0 +1,73 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.groups"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<c:url var="formaction" value="/group/${group.dn}?op=${operation}" />
<div class="container">
<h1 class="col-sm-offset-3"><fmt:message key="groups.group.title"/> ${group.name}</h1>
<c:if test="${ not empty errormessage }">
<div class="alert col-sm-offset-3">
<a class="close" data-dismiss="alert">×</a>
<strong><fmt:message key="groups.error.title"/></strong> ${errormessage}
</div>
</c:if>
<c:if test="${ operation eq 'view' }">
<div class="control-group">
<div class="btn-group col-sm-12">
<c:url var="editgroupurl" value="/group/${group.dn}?op=edit" />
<a href="${editgroupurl}" class="btn btn-default pull-right additional-space-bottom"><fmt:message key="groups.operations.update"/></a>
</div>
</div>
</c:if>
<c:if test="${ operation eq 'delete' }">
<div class="control-group">
<div class="col-sm-12">
<p class="col-sm-offset-3"><fmt:message key="groups.confirm.delete"/></p>
</div>
</div>
</c:if>
<c:if test="${ operation ne 'view' }">
<div class="additional-space-top">&nbsp;</div>
</c:if>
<div class="control-group">
<form class="form-horizontal" method="post" action="${formaction}">
<fieldset ${formdisabled} class="col-sm-12">
<div class="form-group">
<label for="name" class="col-sm-3 control-label"><fmt:message key="groups.label.name"/></label>
<div class="col-sm-9">
<input ${iddisabled}
type="text" class="form-control" id="name" name="name"
value="${group.name}" placeholder="Group name">
</div>
</div>
<div class="form-group">
<label for="membership" class="col-sm-3 control-label"><fmt:message key="groups.label.members"/></label>
<div class="col-sm-9" id ="membership">
<c:forEach items="${users}" var="userentry" >
<div class="checkbox">
<jsp:useBean id="checker" class="de.jalin.ldapadmin.admin.beans.MembershipCheck" />
<jsp:setProperty property="user" name="checker" value="${userentry.value}" />
<jsp:setProperty property="group" name="checker" value="${group}" />
<label><input type="checkbox" id="${userentry.value.login}" name="check_user_${userentry.value.login}" ${checker.checked}>${userentry.value.firstname} ${userentry.value.lastname} (${userentry.value.login})</label>
</div>
</c:forEach>
</div>
</div>
<c:if test="${ formdisabled ne 'disabled' }">
<button type="submit" class="col-sm-offset-3 btn btn-primary additional-space-top"><fmt:message key="groups.operations.submit"/></button>
</c:if>
</fieldset>
<c:if test="${ operation eq 'delete' }">
<button type="submit" class="col-sm-offset-3 btn btn-primary additional-space-top"><fmt:message key="groups.operations.delete"/></button>
</c:if>
</form>
</div>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,38 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.groups"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<div class="container">
<h1><fmt:message key="groups.title"/></h1>
<div class="control-group">
<c:url var="newgroupurl" value="/group/?op=create" />
<a href="${newgroupurl}" class="btn btn-default pull-right additional-space-bottom"><fmt:message key="groups.create"/></a>
</div>
<table class="table table-hover">
<tr><th><fmt:message key="groups.column.name"/></th><th><fmt:message key="groups.column.members"/></th><th><fmt:message key="groups.column.operations"/></th></tr>
<c:forEach items="${groups}" var="groupentry">
<tr>
<td>${groupentry.value.name}</td>
<td>
<ul>
<c:forEach items="${groupentry.value.members}" var="userdn">
<c:url var="userurl" value="/user/${userdn}" />
<li><a href="${userurl}">${users[userdn].lastname}, ${users[userdn].firstname} (${users[userdn].login})</a></li>
</c:forEach>
</ul>
</td>
<c:url var="updgroupurl" value="/group/${groupentry.key}?op=edit" />
<c:url var="delgroupurl" value="/group/${groupentry.key}?op=delete" />
<td><a href="${updgroupurl}"><fmt:message key="groups.operations.edit"/></a> <a href="${delgroupurl}"><fmt:message key="groups.operations.delete"/></a></td>
</tr>
</c:forEach>
</table>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

44
src/main/webapp/login.jsp Normal file
View File

@ -0,0 +1,44 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.login"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/empty-navbar.jsp"/>
<!-- Page Content -->
<c:url var="formaction" value="j_security_check" />
<c:url var="passwordreset" value="/passwordreset" />
<div class="container">
<h1><fmt:message key="login.title"/></h1>
<div class="control-group col-sm-8 additional-space-top">
<form class="form-horizontal" method="post" action="${formaction}">
<fieldset class="">
<div class="form-group">
<label for="j_username" class="col-sm-4 control-label"><fmt:message key="login.username"/></label>
<div class="col-sm-8">
<input
type="text" class="form-control" id="j_username" name="j_username"
value="" placeholder="Login name">
</div>
</div>
<div class="form-group">
<label for="j_password" class="col-sm-4 control-label"><fmt:message key="login.password"/></label>
<div class="col-sm-8">
<input
type="password" class="form-control" id="j_password" name="j_password"
value="" placeholder="Password">
</div>
</div>
<button type="submit" class="col-sm-offset-4 btn btn-primary additional-space-top"><fmt:message key="login.submit"/></button>
<div class="form-group additional-space-top">
<a href="${passwordreset}" class="col-sm-offset-4"><fmt:message key="login.reset.password"/></a>
</div>
</fieldset>
</form>
</div>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,48 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.login"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/empty-navbar.jsp"/>
<!-- Page Content -->
<c:url var="formaction" value="j_security_check" />
<c:url var="passwordreset" value="/passwordreset" />
<div class="container">
<h1><fmt:message key="login.title"/></h1>
<div class="alert">
<a class="close" data-dismiss="alert">×</a>
<strong><fmt:message key="login.error.title"/></strong><fmt:message key="login.error.message"/>
</div>
<div class="control-group col-sm-6 additional-space-top">
<form class="form-horizontal" method="post" action="${formaction}">
<fieldset class="">
<div class="form-group">
<label for="j_username" class="col-sm-4 control-label"><fmt:message key="login.username"/></label>
<div class="col-sm-8">
<input
type="text" class="form-control" id="j_username" name="j_username"
value="" placeholder="Login name">
</div>
</div>
<div class="form-group">
<label for="j_password" class="col-sm-4 control-label"><fmt:message key="login.password"/></label>
<div class="col-sm-8">
<input
type="password" class="form-control" id="j_password" name="j_password"
value="" placeholder="Password">
</div>
</div>
<button type="submit" class="col-sm-offset-4 btn btn-primary additional-space-top"><fmt:message key="login.submit"/></button>
<div class="form-group additional-space-top">
<a href="${passwordreset}" class="col-sm-offset-4"><fmt:message key="login.reset.password"/></a>
</div>
</fieldset>
</form>
</div>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,63 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.login"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<c:url var="formaction" value="/passwordreset" />
<div class="container">
<h1 class="col-sm-offset-3">${user.firstname} ${user.lastname}</h1>
<c:if test="${ not empty errormessage }">
<div class="alert alert-error col-sm-offset-3">
<a class="close" data-dismiss="alert">×</a>
<strong><fmt:message key="login.error.title"/></strong> ${errormessage}
</div>
</c:if>
<c:if test="${ not empty successmessage }">
<div class="alert alert-success col-sm-offset-3">
<a class="close" data-dismiss="alert">×</a>
${successmessage}
</div>
</c:if>
<div class="additional-space-top">&nbsp;</div>
<div class="control-group">
<form class="form-horizontal" method="post" action="${formaction}">
<fieldset class="col-sm-12">
<div class="form-group">
<label for="logindis" class="col-sm-3 control-label"><fmt:message key="login.username"/></label>
<div class="col-sm-9">
<input disabled
type="text" class="form-control" id="logindis" name="logindis"
value="${user.login}" placeholder="Enter login">
<input
type="hidden" class="form-control" id="login" name="login"
value="${user.login}" placeholder="Enter login">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-3 control-label"><fmt:message key="login.password"/></label>
<div class="col-sm-9">
<input
type="password" class="form-control" id="password" name="password"
value="" placeholder="Enter password">
</div>
</div>
<div class="form-group">
<label for="password2" class="col-sm-3 control-label"><fmt:message key="login.password.repeat"/></label>
<div class="col-sm-9">
<input
type="password" class="form-control" id="password2" name="password2"
value="" placeholder="Repeat password">
</div>
</div>
<button type="submit" class="col-sm-offset-3 btn btn-primary additional-space-top"><fmt:message key="login.password.change"/></button>
</fieldset>
</form>
</div>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,37 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.login"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<c:url var="formaction" value="/passwordreset" />
<div class="container">
<h1 class="col-sm-offset-3"><fmt:message key="password.reset.title"/></h1>
<c:if test="${ not empty errormessage }">
<div class="alert alert-error col-sm-offset-3">
<a class="close" data-dismiss="alert">×</a>
<strong><fmt:message key="password.error.title"/></strong> ${errormessage}
</div>
</c:if>
<div class="control-group">
<form class="form-horizontal" method="post" action="${formaction}">
<fieldset class="col-sm-12">
<div class="form-group">
<label for="login" class="col-sm-3 control-label"><fmt:message key="password.reset.loginoremail"/></label>
<div class="col-sm-5">
<input
type="text" class="form-control" id="loginoremail" name="loginoremail"
value="" placeholder="Enter login or email address">
</div>
</div>
</fieldset>
<button type="submit" class="col-sm-offset-3 btn btn-primary additional-space-top"><fmt:message key="password.reset.submit"/></button>
</form>
</div>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,24 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.exception"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<c:url var="logouturl" value="/logout" />
<!-- Page Content -->
<div class="container">
<h1><fmt:message key="exception.title" /></h1>
<p>${servletexception.message}</p>
<p>
<c:forEach var="stackItem" items="${servletexception.stackTrace}">
<c:out value="${stackItem}"/><br/>
</c:forEach>
</p>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,27 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.navbar"/>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only"><fmt:message key="navbar.toggle"/></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<c:url value="/menu.jsp"/>"><fmt:message key="navbar.title"/></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="<c:url value="/profile"/>"><fmt:message key="navbar.item.profile"/></a>
</li>
<li>
<a href="<c:url value="/contact.jsp"/>"><fmt:message key="navbar.item.contact"/></a>
</li>
</ul>
</div>
</div>
</nav>

View File

@ -0,0 +1,4 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script type="text/javascript" src="<%= request.getContextPath() %>/webjars/jquery/3.4.1/jquery.min.js" ></script>
<script type="text/javascript" src="<%= request.getContextPath() %>/webjars/bootstrap/3.4.1/js/bootstrap.min.js" ></script>

View File

@ -0,0 +1,15 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.navbar"/>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title><fmt:message key="navbar.title"/></title>
<!-- Bootstrap-CSS -->
<link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/webjars/bootstrap/3.4.1/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/css/style.css" />
</head>

View File

@ -0,0 +1,33 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.navbar"/>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only"><fmt:message key="navbar.toggle"/></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<c:url value="/contact.jsp"/>"><fmt:message key="navbar.title"/></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="<c:url value="/users"/>"><fmt:message key="navbar.item.users"/></a>
</li>
<li>
<a href="<c:url value="/groups"/>"><fmt:message key="navbar.item.groups"/></a>
</li>
<li>
<a href="<c:url value="/profile"/>"><fmt:message key="navbar.item.profile"/></a>
</li>
<li>
<a href="<c:url value="/contact.jsp"/>"><fmt:message key="navbar.item.contact"/></a>
</li>
</ul>
</div>
</div>
</nav>

152
src/main/webapp/user.jsp Normal file
View File

@ -0,0 +1,152 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.users"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<c:url var="formaction" value="/user/${user.dn}?op=${operation}" />
<c:if test="${ operation eq 'password' }">
<c:url var="formaction" value="/profile/${user.dn}?op=${operation}" />
</c:if>
<div class="container">
<h1 class="col-sm-offset-3">${user.firstname} ${user.lastname}<c:if test="${ operation eq 'create' }"><fmt:message key="users.title.new"/></c:if></h1>
<c:if test="${ not empty errormessage }">
<div class="alert alert-error col-sm-offset-3">
<a class="close" data-dismiss="alert">×</a>
<strong><fmt:message key="users.error.title"/></strong> ${errormessage}
</div>
</c:if>
<c:if test="${ not empty successmessage }">
<div class="alert alert-success col-sm-offset-3">
<a class="close" data-dismiss="alert">×</a>
${successmessage}
</div>
</c:if>
<c:if test="${ operation eq 'profile' }">
<div class="control-group">
<div class="btn-group col-sm-12">
<c:url var="edituserurl" value="/profile/${user.dn}?op=password" />
<a href="${edituserurl}" class="btn btn-default pull-right additional-space-bottom"><fmt:message key="users.operations.changepassword"/></a>
</div>
</div>
</c:if>
<c:if test="${ operation eq 'view' }">
<div class="control-group">
<div class="btn-group col-sm-12">
<c:url var="edituserurl" value="/user/${user.dn}?op=edit" />
<a href="${edituserurl}" class="btn btn-default pull-right additional-space-bottom"><fmt:message key="users.operations.edit"/></a>
</div>
</div>
</c:if>
<c:if test="${ operation eq 'delete' }">
<div class="control-group">
<div class="col-sm-12">
<p class="col-sm-offset-3"><fmt:message key="users.confirm.delete"/></p>
</div>
</div>
</c:if>
<c:if test="${ (operation ne 'view') and (operation ne 'profile') }">
<div class="additional-space-top">&nbsp;</div>
</c:if>
<div class="control-group">
<form class="form-horizontal" method="post" action="${formaction}">
<fieldset ${formdisabled} class="col-sm-12">
<div class="form-group">
<label for="login" class="col-sm-3 control-label"><fmt:message key="users.label.login"/></label>
<div class="col-sm-9">
<input ${iddisabled}
type="text" class="form-control" id="login" name="login"
value="${user.login}" placeholder="Enter login">
</div>
</div>
<c:if test="${ operation ne 'password' }">
<div class="form-group">
<label for="firstname" class="col-sm-3 control-label"><fmt:message key="users.label.firstname"/></label>
<div class="col-sm-9">
<input
type="text" class="form-control" id="firstname" name="firstname"
value="${user.firstname}" placeholder="Enter firstname">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-3 control-label"><fmt:message key="users.label.lastname"/></label>
<div class="col-sm-9">
<input
type="text" class="form-control" id="lastname" name="lastname"
value="${user.lastname}" placeholder="Enter lastname">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-3 control-label"><fmt:message key="users.label.email"/></label>
<div class="col-sm-9">
<input
type="email" class="form-control" id="email" name="email"
value="${user.email}" placeholder="Enter email">
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-3 control-label"><fmt:message key="users.label.phone"/></label>
<div class="col-sm-9">
<input
type="tel" class="form-control" id="phone" name="phone"
value="${user.phone}" placeholder="Enter phone">
</div>
</div>
<div class="form-group">
<label for="mobile" class="col-sm-3 control-label"><fmt:message key="users.label.mobile"/></label>
<div class="col-sm-9">
<input
type="tel" class="form-control" id="mobile" name="mobile"
value="${user.mobile}" placeholder="Enter mobile">
</div>
</div>
</c:if>
<c:if test="${ (operation eq 'create') or (operation eq 'edit') or (operation eq 'password') }">
<div class="form-group">
<label for="password" class="col-sm-3 control-label"><fmt:message key="users.label.password"/></label>
<div class="col-sm-9">
<input
type="password" class="form-control" id="password" name="password"
value="" placeholder="Enter password">
</div>
</div>
<div class="form-group">
<label for="password2" class="col-sm-3 control-label"><fmt:message key="users.label.password.repeat"/></label>
<div class="col-sm-9">
<input
type="password" class="form-control" id="password2" name="password2"
value="" placeholder="Repeat password">
</div>
</div>
</c:if>
<c:if test="${ operation ne 'password' }">
<div class="form-group">
<label for="membership" class="col-sm-3 control-label"><fmt:message key="users.label.memberof"/></label>
<div class="col-sm-9" id ="membership">
<c:forEach items="${groups}" var="groupentry" >
<div class="checkbox">
<jsp:useBean id="checker" class="de.jalin.ldapadmin.admin.beans.MembershipCheck" />
<jsp:setProperty property="user" name="checker" value="${user}" />
<jsp:setProperty property="group" name="checker" value="${groupentry.value}" />
<label><input type="checkbox" id="${groupentry.value.name}" name="check_group_${groupentry.value.name}" ${checker.checked}>${groupentry.value.name}</label>
</div>
</c:forEach>
</div>
</div>
</c:if>
<c:if test="${ formdisabled ne 'disabled' }">
<button type="submit" class="col-sm-offset-3 btn btn-primary additional-space-top"><fmt:message key="users.operations.update"/></button>
</c:if>
</fieldset>
<c:if test="${ operation eq 'delete' }">
<button type="submit" class="col-sm-offset-3 btn btn-primary additional-space-top"><fmt:message key="users.operations.delete"/></button>
</c:if>
</form>
</div>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

40
src/main/webapp/users.jsp Normal file
View File

@ -0,0 +1,40 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="de.jalin.ldapadmin.users"/>
<!DOCTYPE html>
<html lang="{language}">
<jsp:include page="template/header.jsp"/>
<body>
<jsp:include page="template/navbar.jsp"/>
<div class="container">
<h1><fmt:message key="users.title"/></h1>
<div class="control-group">
<c:url var="newuserurl" value="/user/?op=create" />
<a href="${newuserurl}" class="btn btn-default pull-right additional-space-bottom"><fmt:message key="users.create"/></a>
</div>
<table class="table table-hover">
<tr><th><fmt:message key="users.column.login"/></th><th><fmt:message key="users.column.firstname"/></th><th><fmt:message key="users.column.lastname"/></th><th><fmt:message key="users.column.groups"/></th><th><fmt:message key="users.column.operations"/></th></tr>
<c:forEach items="${users}" var="userentry">
<tr>
<td>${userentry.value.login}</td>
<td>${userentry.value.firstname}</td>
<td>${userentry.value.lastname}</td>
<td>
<ul>
<c:forEach items="${userentry.value.groups}" var="groupdn">
<c:url var="groupurl" value="/group/${groupdn}"/>
<li><a href="${groupurl}">${groups[groupdn].name}</a></li>
</c:forEach>
</ul>
</td>
<c:url var="upduserurl" value="/user/${userentry.key}?op=edit"/>
<c:url var="deluserurl" value="/user/${userentry.key}?op=delete"/>
<td><a href="${upduserurl}"><fmt:message key="users.operations.edit"/></a> <a href="${deluserurl}"><fmt:message key="users.operations.delete"/></a></td>
</tr>
</c:forEach>
</table>
</div>
<jsp:include page="template/footer.jsp"/>
</body>
</html>

View File

@ -0,0 +1,126 @@
package de.jalin.ldapadmin.ldap;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import net.sf.ehcache.Cache;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.schema.SchemaManager;
import org.apache.directory.server.core.api.CacheService;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.api.partition.Partition;
import org.apache.directory.server.core.factory.DefaultDirectoryServiceFactory;
import org.apache.directory.server.core.factory.JdbmPartitionFactory;
import org.apache.directory.server.core.shared.DefaultDnFactory;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.protocol.shared.store.LdifFileLoader;
import org.apache.directory.server.protocol.shared.store.LdifLoadFilter;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
public class DirectoryServiceRunner
{
private static DirectoryServiceRunner serviceRunner = null;
private final DirectoryService service;
public DirectoryServiceRunner(final String dnString, final String ip, final String port) throws Exception
{
service = initService();
addPartition("ou=config", "config");
addPartition(dnString, "example");
service.startup();
loadData();
startServer(ip, port);
}
private DirectoryService initService() throws Exception {
final DefaultDirectoryServiceFactory factory = new DefaultDirectoryServiceFactory();
factory.init("example");
final DirectoryService directoryService = factory.getDirectoryService();
directoryService.setShutdownHookEnabled(true);
directoryService.getChangeLog().setEnabled(false);
directoryService.setAccessControlEnabled(true);
directoryService.setAllowAnonymousAccess(false);
directoryService.setPasswordHidden(true);
return directoryService;
}
private void addPartition(final String dnString, final String partitionId) throws LdapInvalidDnException, Exception {
final JdbmPartitionFactory partitionFactory = new JdbmPartitionFactory();
final SchemaManager schemaManager = service.getSchemaManager();
final CacheService cacheService = service.getCacheService();
final Cache cache = cacheService.getCache("dnCache");
final DefaultDnFactory defaultDnFactory = new DefaultDnFactory(schemaManager, cache);
final Partition partition = partitionFactory.createPartition(schemaManager, defaultDnFactory, partitionId, dnString, 400, new File("ldap-data." + Double.valueOf(Math.random()).hashCode()));
service.addPartition(partition);
}
private void startServer(final String ip, final String port) throws Exception {
final LdapServer ldapServer = new LdapServer();
ldapServer.setTransports(new TcpTransport(ip, Integer.parseInt(port)));
ldapServer.setDirectoryService(service);
ldapServer.start();
}
private void loadData() {
final File ldifDirectory = new File("ldif");
if (ldifDirectory.exists() && ldifDirectory.isDirectory()) {
final File[] ldifFiles = ldifDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return name.endsWith(".ldif");
}
});
for (final File ldifFile : ldifFiles) {
final LdifFileLoader ldifFileLoader = new LdifFileLoader(service.getAdminSession(), ldifFile, (List<? extends LdifLoadFilter>) new ArrayList<LdifLoadFilter>());
ldifFileLoader.execute();
System.out.println(ldifFile.getName() + " loaded");
}
}
}
public static void assureServiceRunning(final String name) throws DirectoryServiceException
{
if (serviceRunner == null) {
final String dnName = "dc=" + name + ",dc=example,dc=com";
try {
serviceRunner = new DirectoryServiceRunner(dnName, "127.0.0.1", "10389");
} catch (Exception e) {
throw new DirectoryServiceException(e);
}
}
}
public static void main(final String[] args)
{
final String dnString = "dc=" + args[0] + ",dc=example,dc=com";
final String ip = args[1];
final String port = args[2];
try
{
final DirectoryServiceRunner ads = new DirectoryServiceRunner(dnString, ip, port);
final Entry result = ads.service.getAdminSession().lookup(new Dn(dnString));
System.out.println( "Found entry : " + result );
}
catch ( Exception e )
{
System.err.println(e.getMessage());
}
}
static class DirectoryServiceException extends Exception {
private static final long serialVersionUID = 1L;
public DirectoryServiceException(final Throwable exc) {
super(exc);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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