Fix dspace-api module per new code style

This commit is contained in:
Tim Donohue
2018-02-14 10:53:46 -06:00
parent 8ffc97f7f9
commit 8a48f782ea
1051 changed files with 53347 additions and 63373 deletions

View File

@@ -12,7 +12,6 @@ import java.sql.SQLException;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
@@ -47,11 +46,11 @@ import org.dspace.eperson.service.GroupService;
* This combined LDAP authentication method supersedes both the 'LDAPAuthentication'
* and the 'LDAPHierarchicalAuthentication' methods. It's capable of both:
* - authenticaton against a flat LDAP tree where all users are in the same unit
* (if search.user or search.password is not set)
* - authentication against structured hierarchical LDAP trees of users.
* An initial bind is required using a user name and password in order to
* search the tree and find the DN of the user. A second bind is then required to
* check the credentials of the user by binding directly to their DN.
* (if search.user or search.password is not set)
* - authentication against structured hierarchical LDAP trees of users.
* An initial bind is required using a user name and password in order to
* search the tree and find the DN of the user. A second bind is then required to
* check the credentials of the user by binding directly to their DN.
*
* @author Stuart Lewis, Chris Yates, Alex Barbieri, Flavio Botelho, Reuben Pasquini, Samuel Ottenhoff, Ivan Masár
* @version $Revision$
@@ -59,51 +58,54 @@ import org.dspace.eperson.service.GroupService;
public class LDAPAuthentication
implements AuthenticationMethod {
/** log4j category */
/**
* log4j category
*/
private static Logger log = Logger.getLogger(LDAPAuthentication.class);
protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService();
protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance()
.getAuthenticationService();
protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
/**
* Let a real auth method return true if it wants.
*
* @throws SQLException if database error
*/
@Override
public boolean canSelfRegister(Context context,
HttpServletRequest request,
String username)
throws SQLException
{
throws SQLException {
// Looks to see if autoregister is set or not
return ConfigurationManager.getBooleanProperty("authentication-ldap", "autoregister");
}
/**
* Nothing here, initialization is done when auto-registering.
*
* @throws SQLException if database error
*/
@Override
public void initEPerson(Context context, HttpServletRequest request,
EPerson eperson)
throws SQLException
{
EPerson eperson)
throws SQLException {
// XXX should we try to initialize netid based on email addr,
// XXX for eperson created by some other method??
}
/**
* Cannot change LDAP password through dspace, right?
*
* @throws SQLException if database error
*/
@Override
public boolean allowSetPassword(Context context,
HttpServletRequest request,
String username)
throws SQLException
{
throws SQLException {
// XXX is this right?
return false;
}
@@ -112,8 +114,7 @@ public class LDAPAuthentication
* This is an explicit method.
*/
@Override
public boolean isImplicit()
{
public boolean isImplicit() {
return false;
}
@@ -122,33 +123,26 @@ public class LDAPAuthentication
* the login.specialgroup key.
*/
@Override
public List<Group> getSpecialGroups(Context context, HttpServletRequest request)
{
public List<Group> getSpecialGroups(Context context, HttpServletRequest request) {
// Prevents anonymous users from being added to this group, and the second check
// ensures they are LDAP users
try
{
if (!context.getCurrentUser().getNetid().equals(""))
{
try {
if (!context.getCurrentUser().getNetid().equals("")) {
String groupName = ConfigurationManager.getProperty("authentication-ldap", "login.specialgroup");
if ((groupName != null) && (!groupName.trim().equals("")))
{
if ((groupName != null) && (!groupName.trim().equals(""))) {
Group ldapGroup = groupService.findByName(context, groupName);
if (ldapGroup == null)
{
if (ldapGroup == null) {
// Oops - the group isn't there.
log.warn(LogManager.getHeader(context,
"ldap_specialgroup",
"Group defined in login.specialgroup does not exist"));
"ldap_specialgroup",
"Group defined in login.specialgroup does not exist"));
return ListUtils.EMPTY_LIST;
} else
{
} else {
return Arrays.asList(ldapGroup);
}
}
}
}
catch (Exception npe) {
} catch (Exception npe) {
// The user is not an LDAP user, so we don't need to worry about them
}
return ListUtils.EMPTY_LIST;
@@ -193,24 +187,20 @@ public class LDAPAuthentication
String password,
String realm,
HttpServletRequest request)
throws SQLException
{
log.info(LogManager.getHeader(context, "auth", "attempting trivial auth of user="+netid));
throws SQLException {
log.info(LogManager.getHeader(context, "auth", "attempting trivial auth of user=" + netid));
// Skip out when no netid or password is given.
if (netid == null || password == null)
{
if (netid == null || password == null) {
return BAD_ARGS;
}
// Locate the eperson
EPerson eperson = null;
try
{
eperson = ePersonService.findByNetid(context, netid.toLowerCase());
}
catch (SQLException e)
{
try {
eperson = ePersonService.findByNetid(context, netid.toLowerCase());
} catch (SQLException e) {
// ignore
}
SpeakerToLDAP ldap = new SpeakerToLDAP(log);
@@ -222,93 +212,77 @@ public class LDAPAuthentication
String idField = ConfigurationManager.getProperty("authentication-ldap", "id_field");
String dn = "";
// If adminUser is blank and anonymous search is not allowed, then we can't search so construct the DN instead of searching it
if ((StringUtils.isBlank(adminUser) || StringUtils.isBlank(adminPassword)) && !anonymousSearch)
{
// If adminUser is blank and anonymous search is not allowed, then we can't search so construct the DN
// instead of searching it
if ((StringUtils.isBlank(adminUser) || StringUtils.isBlank(adminPassword)) && !anonymousSearch) {
dn = idField + "=" + netid + "," + objectContext;
}
else
{
} else {
dn = ldap.getDNOfUser(adminUser, adminPassword, context, netid);
}
// Check a DN was found
if ((dn == null) || (dn.trim().equals("")))
{
if ((dn == null) || (dn.trim().equals(""))) {
log.info(LogManager
.getHeader(context, "failed_login", "no DN found for user " + netid));
.getHeader(context, "failed_login", "no DN found for user " + netid));
return BAD_CREDENTIALS;
}
// if they entered a netid that matches an eperson
if (eperson != null)
{
if (eperson != null) {
// e-mail address corresponds to active account
if (eperson.getRequireCertificate())
{
if (eperson.getRequireCertificate()) {
return CERT_REQUIRED;
}
else if (!eperson.canLogIn())
{
} else if (!eperson.canLogIn()) {
return BAD_ARGS;
}
if (ldap.ldapAuthenticate(dn, password, context))
{
if (ldap.ldapAuthenticate(dn, password, context)) {
context.setCurrentUser(eperson);
// assign user to groups based on ldap dn
assignGroups(dn, ldap.ldapGroup, context);
log.info(LogManager
.getHeader(context, "authenticate", "type=ldap"));
.getHeader(context, "authenticate", "type=ldap"));
return SUCCESS;
}
else
{
} else {
return BAD_CREDENTIALS;
}
}
else
{
} else {
// the user does not already exist so try and authenticate them
// with ldap and create an eperson for them
if (ldap.ldapAuthenticate(dn, password, context))
{
if (ldap.ldapAuthenticate(dn, password, context)) {
// Register the new user automatically
log.info(LogManager.getHeader(context,
"autoregister", "netid=" + netid));
"autoregister", "netid=" + netid));
String email = ldap.ldapEmail;
// Check if we were able to determine an email address from LDAP
if (StringUtils.isEmpty(email))
{
// If no email, check if we have a "netid_email_domain". If so, append it to the netid to create email
if (StringUtils.isNotEmpty(ConfigurationManager.getProperty("authentication-ldap", "netid_email_domain")))
{
if (StringUtils.isEmpty(email)) {
// If no email, check if we have a "netid_email_domain". If so, append it to the netid to create
// email
if (StringUtils
.isNotEmpty(ConfigurationManager.getProperty("authentication-ldap", "netid_email_domain"))) {
email = netid + ConfigurationManager.getProperty("authentication-ldap", "netid_email_domain");
}
else
{
} else {
// We don't have a valid email address. We'll default it to 'netid' but log a warning
log.warn(LogManager.getHeader(context, "autoregister",
"Unable to locate email address for account '" + netid + "', so it has been set to '" + netid + "'. " +
"Please check the LDAP 'email_field' OR consider configuring 'netid_email_domain'."));
"Unable to locate email address for account '" + netid + "', so" +
" it has been set to '" + netid + "'. " +
"Please check the LDAP 'email_field' OR consider " +
"configuring 'netid_email_domain'."));
email = netid;
}
}
if (StringUtils.isNotEmpty(email))
{
try
{
if (StringUtils.isNotEmpty(email)) {
try {
eperson = ePersonService.findByEmail(context, email);
if (eperson!=null)
{
if (eperson != null) {
log.info(LogManager.getHeader(context,
"type=ldap-login", "type=ldap_but_already_email"));
"type=ldap-login", "type=ldap_but_already_email"));
context.turnOffAuthorisationSystem();
eperson.setNetid(netid.toLowerCase());
ePersonService.update(context, eperson);
@@ -320,30 +294,22 @@ public class LDAPAuthentication
assignGroups(dn, ldap.ldapGroup, context);
return SUCCESS;
}
else
{
if (canSelfRegister(context, request, netid))
{
} else {
if (canSelfRegister(context, request, netid)) {
// TEMPORARILY turn off authorisation
try
{
try {
context.turnOffAuthorisationSystem();
eperson = ePersonService.create(context);
if (StringUtils.isNotEmpty(email))
{
if (StringUtils.isNotEmpty(email)) {
eperson.setEmail(email);
}
if (StringUtils.isNotEmpty(ldap.ldapGivenName))
{
if (StringUtils.isNotEmpty(ldap.ldapGivenName)) {
eperson.setFirstName(context, ldap.ldapGivenName);
}
if (StringUtils.isNotEmpty(ldap.ldapSurname))
{
if (StringUtils.isNotEmpty(ldap.ldapSurname)) {
eperson.setLastName(context, ldap.ldapSurname);
}
if (StringUtils.isNotEmpty(ldap.ldapPhone))
{
if (StringUtils.isNotEmpty(ldap.ldapPhone)) {
ePersonService.setMetadata(context, eperson, "phone", ldap.ldapPhone);
}
eperson.setNetid(netid.toLowerCase());
@@ -355,35 +321,25 @@ public class LDAPAuthentication
// assign user to groups based on ldap dn
assignGroups(dn, ldap.ldapGroup, context);
}
catch (AuthorizeException e)
{
} catch (AuthorizeException e) {
return NO_SUCH_USER;
}
finally
{
} finally {
context.restoreAuthSystemState();
}
log.info(LogManager.getHeader(context, "authenticate",
"type=ldap-login, created ePerson"));
"type=ldap-login, created ePerson"));
return SUCCESS;
}
else
{
} else {
// No auto-registration for valid certs
log.info(LogManager.getHeader(context,
"failed_login", "type=ldap_but_no_record"));
"failed_login", "type=ldap_but_no_record"));
return NO_SUCH_USER;
}
}
}
catch (AuthorizeException e)
{
} catch (AuthorizeException e) {
eperson = null;
}
finally
{
} finally {
context.restoreAuthSystemState();
}
}
@@ -406,7 +362,9 @@ public class LDAPAuthentication
protected String ldapPhone = null;
protected String ldapGroup = null;
/** LDAP settings */
/**
* LDAP settings
*/
String ldap_provider_url = ConfigurationManager.getProperty("authentication-ldap", "provider_url");
String ldap_id_field = ConfigurationManager.getProperty("authentication-ldap", "id_field");
String ldap_search_context = ConfigurationManager.getProperty("authentication-ldap", "search_context");
@@ -416,33 +374,27 @@ public class LDAPAuthentication
String ldap_givenname_field = ConfigurationManager.getProperty("authentication-ldap", "givenname_field");
String ldap_surname_field = ConfigurationManager.getProperty("authentication-ldap", "surname_field");
String ldap_phone_field = ConfigurationManager.getProperty("authentication-ldap", "phone_field");
String ldap_group_field = ConfigurationManager.getProperty("authentication-ldap", "login.groupmap.attribute");
String ldap_group_field = ConfigurationManager.getProperty("authentication-ldap", "login.groupmap.attribute");
boolean useTLS = ConfigurationManager.getBooleanProperty("authentication-ldap", "starttls", false);
SpeakerToLDAP(Logger thelog)
{
SpeakerToLDAP(Logger thelog) {
log = thelog;
}
protected String getDNOfUser(String adminUser, String adminPassword, Context context, String netid)
{
protected String getDNOfUser(String adminUser, String adminPassword, Context context, String netid) {
// The resultant DN
String resultDN;
// The search scope to use (default to 0)
int ldap_search_scope_value = 0;
try
{
try {
ldap_search_scope_value = Integer.parseInt(ldap_search_scope.trim());
}
catch (NumberFormatException e)
{
} catch (NumberFormatException e) {
// Log the error if it has been set but is invalid
if (ldap_search_scope != null)
{
if (ldap_search_scope != null) {
log.warn(LogManager.getHeader(context,
"ldap_authentication", "invalid search scope: " + ldap_search_scope));
"ldap_authentication", "invalid search scope: " + ldap_search_scope));
}
}
@@ -450,45 +402,38 @@ public class LDAPAuthentication
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url);
LdapContext ctx = null;
StartTlsResponse startTLSResponse = null;
try
{
try {
if ((adminUser != null) && (!adminUser.trim().equals("")) &&
(adminPassword != null) && (!adminPassword.trim().equals("")))
{
if(useTLS)
{
(adminPassword != null) && (!adminPassword.trim().equals(""))) {
if (useTLS) {
ctx = new InitialLdapContext(env, null);
// start TLS
startTLSResponse = (StartTlsResponse) ctx
.extendedOperation(new StartTlsRequest());
.extendedOperation(new StartTlsRequest());
startTLSResponse.negotiate();
// perform simple client authentication
ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL,
adminUser);
adminUser);
ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
adminPassword);
}
else
{
adminPassword);
} else {
// Use admin credentials for search// Authenticate
env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
env.put(javax.naming.Context.SECURITY_PRINCIPAL, adminUser);
env.put(javax.naming.Context.SECURITY_CREDENTIALS, adminPassword);
}
}
else
{
} else {
// Use anonymous authentication
env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "none");
}
if (ctx == null) {
// Create initial context
ctx = new InitialLdapContext(env, null);
@@ -498,24 +443,20 @@ public class LDAPAuthentication
matchAttrs.put(new BasicAttribute(ldap_id_field, netid));
// look up attributes
try
{
try {
SearchControls ctrls = new SearchControls();
ctrls.setSearchScope(ldap_search_scope_value);
String searchName = "";
if(useTLS)
{
if (useTLS) {
searchName = ldap_search_context;
}
else
{
} else {
searchName = ldap_provider_url + ldap_search_context;
}
NamingEnumeration<SearchResult> answer = ctx.search(
searchName,
"(&({0}={1}))", new Object[] { ldap_id_field,
netid }, ctrls);
searchName,
"(&({0}={1}))", new Object[] {ldap_id_field,
netid}, ctrls);
while (answer.hasMoreElements()) {
SearchResult sr = answer.next();
@@ -526,46 +467,41 @@ public class LDAPAuthentication
}
String attlist[] = {ldap_email_field, ldap_givenname_field,
ldap_surname_field, ldap_phone_field, ldap_group_field};
ldap_surname_field, ldap_phone_field, ldap_group_field};
Attributes atts = sr.getAttributes();
Attribute att;
if (attlist[0] != null) {
att = atts.get(attlist[0]);
if (att != null)
{
if (att != null) {
ldapEmail = (String) att.get();
}
}
if (attlist[1] != null) {
att = atts.get(attlist[1]);
if (att != null)
{
if (att != null) {
ldapGivenName = (String) att.get();
}
}
if (attlist[2] != null) {
att = atts.get(attlist[2]);
if (att != null)
{
if (att != null) {
ldapSurname = (String) att.get();
}
}
if (attlist[3] != null) {
att = atts.get(attlist[3]);
if (att != null)
{
if (att != null) {
ldapPhone = (String) att.get();
}
}
if (attlist[4] != null) {
att = atts.get(attlist[4]);
if (att != null)
{
if (att != null) {
ldapGroup = (String) att.get();
}
}
@@ -579,37 +515,27 @@ public class LDAPAuthentication
return resultDN;
}
}
}
catch (NamingException e)
{
} catch (NamingException e) {
// if the lookup fails go ahead and create a new record for them because the authentication
// succeeded
log.warn(LogManager.getHeader(context,
"ldap_attribute_lookup", "type=failed_search "
+ e));
"ldap_attribute_lookup", "type=failed_search "
+ e));
}
}
catch (NamingException | IOException e)
{
} catch (NamingException | IOException e) {
log.warn(LogManager.getHeader(context,
"ldap_authentication", "type=failed_auth " + e));
}
finally
{
"ldap_authentication", "type=failed_auth " + e));
} finally {
// Close the context when we're done
try
{
if (startTLSResponse != null)
{
try {
if (startTLSResponse != null) {
startTLSResponse.close();
}
if (ctx != null)
{
if (ctx != null) {
ctx.close();
}
}
catch (NamingException | IOException e)
{
} catch (NamingException | IOException e) {
// ignore
}
}
@@ -621,87 +547,78 @@ public class LDAPAuthentication
* contact the ldap server and attempt to authenticate
*/
protected boolean ldapAuthenticate(String netid, String password,
Context context) {
Context context) {
if (!password.equals("")) {
LdapContext ctx = null;
StartTlsResponse startTLSResponse = null;
// Set up environment for creating initial context
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url);
try
{
if(useTLS)
{
try {
if (useTLS) {
ctx = new InitialLdapContext(env, null);
// start TLS
startTLSResponse = (StartTlsResponse) ctx
.extendedOperation(new StartTlsRequest());
.extendedOperation(new StartTlsRequest());
startTLSResponse.negotiate();
// perform simple client authentication
ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL,
netid);
netid);
ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
password);
password);
ctx.addToEnvironment(javax.naming.Context.AUTHORITATIVE, "true");
ctx.addToEnvironment(javax.naming.Context.REFERRAL, "follow");
// dummy operation to check if authentication has succeeded
ctx.getAttributes("");
}
else if (!useTLS)
{
} else if (!useTLS) {
// Authenticate
env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
env.put(javax.naming.Context.SECURITY_PRINCIPAL, netid);
env.put(javax.naming.Context.SECURITY_CREDENTIALS, password);
env.put(javax.naming.Context.AUTHORITATIVE, "true");
env.put(javax.naming.Context.REFERRAL, "follow");
// Try to bind
ctx = new InitialLdapContext(env, null);
}
}
catch (NamingException | IOException e)
{
} catch (NamingException | IOException e) {
// something went wrong (like wrong password) so return false
log.warn(LogManager.getHeader(context,
"ldap_authentication", "type=failed_auth " + e));
"ldap_authentication", "type=failed_auth " + e));
return false;
} finally
{
} finally {
// Close the context when we're done
try {
if (startTLSResponse != null)
{
if (startTLSResponse != null) {
startTLSResponse.close();
}
if (ctx != null)
{
if (ctx != null) {
ctx.close();
}
} catch (NamingException | IOException e) {}
} catch (NamingException | IOException e) {
// ignore
}
}
} else
{
} else {
return false;
}
return true;
}
}
}
/*
* Returns the URL of an external login page which is not applicable for this authn method.
*
*
* Note: Prior to DSpace 7, this method return the page of login servlet.
*
* @param context
@@ -717,9 +634,8 @@ public class LDAPAuthentication
*/
@Override
public String loginPageURL(Context context,
HttpServletRequest request,
HttpServletResponse response)
{
HttpServletRequest request,
HttpServletResponse response) {
return null;
}
@@ -727,54 +643,47 @@ public class LDAPAuthentication
* Add authenticated users to the group defined in dspace.cfg by
* the authentication-ldap.login.groupmap.* key.
*/
private void assignGroups(String dn, String group, Context context)
{
if (StringUtils.isNotBlank(dn))
{
private void assignGroups(String dn, String group, Context context) {
if (StringUtils.isNotBlank(dn)) {
System.out.println("dn:" + dn);
int i = 1;
String groupMap = ConfigurationManager.getProperty("authentication-ldap", "login.groupmap." + i);
boolean cmp;
while (groupMap != null)
{
while (groupMap != null) {
String t[] = groupMap.split(":");
String ldapSearchString = t[0];
String dspaceGroupName = t[1];
if (group == null) {
cmp = StringUtils.containsIgnoreCase(dn, ldapSearchString + ",");
} else {
cmp = StringUtils.equalsIgnoreCase(group, ldapSearchString);
}
if (cmp)
{
// assign user to this group
try
{
if (cmp) {
// assign user to this group
try {
Group ldapGroup = groupService.findByName(context, dspaceGroupName);
if (ldapGroup != null)
{
if (ldapGroup != null) {
groupService.addMember(context, ldapGroup, context.getCurrentUser());
groupService.update(context, ldapGroup);
}
else
{
} else {
// The group does not exist
log.warn(LogManager.getHeader(context,
"ldap_assignGroupsBasedOnLdapDn",
"Group defined in authentication-ldap.login.groupmap." + i + " does not exist :: " + dspaceGroupName));
"ldap_assignGroupsBasedOnLdapDn",
"Group defined in authentication-ldap.login.groupmap." + i
+ " does not exist :: " + dspaceGroupName));
}
}
catch (AuthorizeException ae)
{
log.debug(LogManager.getHeader(context, "assignGroupsBasedOnLdapDn could not authorize addition to group", dspaceGroupName));
}
catch (SQLException e)
{
log.debug(LogManager.getHeader(context, "assignGroupsBasedOnLdapDn could not find group", dspaceGroupName));
} catch (AuthorizeException ae) {
log.debug(LogManager.getHeader(context,
"assignGroupsBasedOnLdapDn could not authorize addition to " +
"group",
dspaceGroupName));
} catch (SQLException e) {
log.debug(LogManager.getHeader(context, "assignGroupsBasedOnLdapDn could not find group",
dspaceGroupName));
}
}