Project

General

Profile

1 4080 daigle
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements ldap configuration methods
4
 *  Copyright: 2008 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Michael Daigle
7
 *
8
 *   '$Author$'
9
 *     '$Date$'
10
 * '$Revision$'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26
27
package edu.ucsb.nceas.metacat.admin;
28
29 4547 daigle
import java.net.ConnectException;
30 4080 daigle
import java.util.Set;
31
import java.util.SortedMap;
32
import java.util.Vector;
33
34
import javax.servlet.http.HttpServletRequest;
35
import javax.servlet.http.HttpServletResponse;
36
37
import org.apache.log4j.Logger;
38
39 4590 daigle
import edu.ucsb.nceas.metacat.AuthSession;
40 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
41 5076 daigle
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
42 4080 daigle
import edu.ucsb.nceas.metacat.util.RequestUtil;
43
import edu.ucsb.nceas.utilities.GeneralPropertyException;
44
import edu.ucsb.nceas.utilities.MetaDataProperty;
45
import edu.ucsb.nceas.utilities.PropertiesMetaData;
46
import edu.ucsb.nceas.utilities.SortedProperties;
47 4547 daigle
import edu.ucsb.nceas.utilities.StringUtil;
48 4080 daigle
49
/**
50 4590 daigle
 * Control the display of the Authentication configuration page and the processing
51 4080 daigle
 * of the configuration values.
52
 */
53 5027 daigle
public class AuthAdmin extends MetacatAdmin {
54 4080 daigle
55 4590 daigle
	private static AuthAdmin authAdmin = null;
56
	private static Logger logMetacat = Logger.getLogger(AuthAdmin.class);
57 8532 tao
	private static final String AUTHCLASSKEY = "auth.class";
58
	public static final String FILECLASS = "edu.ucsb.nceas.metacat.authentication.AuthFile";
59
    public static final String LDAPCLASS = "edu.ucsb.nceas.metacat.AuthLdap";
60 4080 daigle
	/**
61
	 * private constructor since this is a singleton
62
	 */
63 4590 daigle
	private AuthAdmin() {}
64 4080 daigle
65
	/**
66
	 * Get the single instance of the MetaCatConfig.
67
	 *
68
	 * @return the single instance of MetaCatConfig
69
	 */
70 4590 daigle
	public static AuthAdmin getInstance() {
71
		if (authAdmin == null) {
72
			authAdmin = new AuthAdmin();
73 4080 daigle
		}
74 4590 daigle
		return authAdmin;
75 4080 daigle
	}
76
77
	/**
78 4590 daigle
	 * Handle configuration of the Authentication properties
79 4080 daigle
	 *
80
	 * @param request
81
	 *            the http request information
82
	 * @param response
83
	 *            the http response to be sent back to the client
84
	 */
85 4590 daigle
	public void configureAuth(HttpServletRequest request,
86 4080 daigle
			HttpServletResponse response) throws AdminException {
87
88
		String processForm = request.getParameter("processForm");
89
		String formErrors = (String) request.getAttribute("formErrors");
90
91
		if (processForm == null || !processForm.equals("true") || formErrors != null) {
92
			// The servlet configuration parameters have not been set, or there
93
			// were form errors on the last attempt to configure, so redirect to
94
			// the web form for configuring metacat
95
96
			try {
97
				// Load the properties metadata file so that the JSP page can
98 4159 daigle
				// use the metadata to construct the editing form
99 4590 daigle
				PropertiesMetaData metadata = PropertyService.getAuthMetaData();
100 4080 daigle
				request.setAttribute("metadata", metadata);
101
				request.setAttribute("groupMap", metadata.getGroups());
102
103 4590 daigle
				// add the list of auth options and their values to the request
104
				Vector<String> propertyNames = PropertyService.getPropertyNamesByGroup("auth");
105 4080 daigle
				for (String name : propertyNames) {
106
					request.setAttribute(name, PropertyService.getProperty(name));
107
				}
108 4751 daigle
109
				// add the list of organization options and their values to the request.  This is because
110
				// currently we use the organization.unaffiliated values to configure metacat client for
111
				// password change and account creation.  Eventually, these should get moved to organization
112
				// level configuration.
113
				Vector<String> orgPropertyNames = PropertyService.getPropertyNamesByGroup("organization");
114
				for (String name : orgPropertyNames) {
115
					request.setAttribute(name, PropertyService.getProperty(name));
116
				}
117 4080 daigle
118
				// Check for any backup properties and apply them to the request.
119
				// These are properties from previous configurations. They keep
120
				// the user from having to re-enter all values when upgrading.
121
				// If this is a first time install, getBackupProperties will return
122
				// null.
123 4590 daigle
				SortedProperties backupProperties = PropertyService.getAuthBackupProperties();
124 4080 daigle
				if (backupProperties != null) {
125
					Vector<String> backupKeys = backupProperties.getPropertyNames();
126
					for (String key : backupKeys) {
127
						String value = backupProperties.getProperty(key);
128
						if (value != null) {
129
							request.setAttribute(key, value);
130
						}
131
					}
132
				}
133
				// Forward the request to the JSP page
134
				RequestUtil.forwardRequest(request, response,
135 5027 daigle
						"/admin/auth-configuration.jsp", null);
136 5030 daigle
			} catch (GeneralPropertyException gpe) {
137
				throw new AdminException("AuthAdmin.configureAuth - Problem getting property " +
138
						"while initializing LDAP properties page: " + gpe.getMessage());
139 5076 daigle
			} catch (MetacatUtilException mue) {
140
				throw new AdminException("AuthAdmin.configureAuth - Utility problem while initializing "
141
						+ "LDAP properties page:" + mue.getMessage());
142
			}
143 4080 daigle
		} else {
144
			// The configuration form is being submitted and needs to be
145
			// processed.
146
			Vector<String> processingSuccess = new Vector<String>();
147
			Vector<String> processingErrors = new Vector<String>();
148
			Vector<String> validationErrors = new Vector<String>();
149
150
			try {
151
				// For each property, check if it is changed and save it
152 4590 daigle
				PropertiesMetaData authMetaData = PropertyService
153
						.getAuthMetaData();
154 4080 daigle
155
				// process the fields for the global options (group 1)
156 4590 daigle
				SortedMap<Integer, MetaDataProperty> globalPropertyMap = authMetaData
157 4080 daigle
						.getPropertiesInGroup(1);
158
				Set<Integer> globalPropertyIndexes = globalPropertyMap.keySet();
159
				for (Integer globalPropertyIndex : globalPropertyIndexes) {
160
					String globalPropertyKey = globalPropertyMap.get(
161
							globalPropertyIndex).getKey();
162
					PropertyService.checkAndSetProperty(request,
163
							globalPropertyKey);
164
				}
165 4751 daigle
166 8532 tao
				//String authClassName = request.getParameter(AUTHCLASSKEY);
167
				//System.out.println("the auth class name from the request is "+authClassName);
168
				// process the fields for the file-based options (group 2)
169
				SortedMap<Integer, MetaDataProperty> filePropertyMap = authMetaData
170 4751 daigle
						.getPropertiesInGroup(2);
171 8532 tao
				Set<Integer> filePropertyIndexes = filePropertyMap.keySet();
172
				for (Integer filePropertyIndex : filePropertyIndexes) {
173
					String filePropertyKey = filePropertyMap.get(
174
							filePropertyIndex).getKey();
175 4751 daigle
					PropertyService.checkAndSetProperty(request,
176 8532 tao
							filePropertyKey);
177 4751 daigle
				}
178 8532 tao
179
				// process the fields for the ldap-based options (group 3)
180
                SortedMap<Integer, MetaDataProperty> ldapPropertyMap = authMetaData
181
                        .getPropertiesInGroup(3);
182
                Set<Integer> ldapPropertyIndexes = ldapPropertyMap.keySet();
183
                for (Integer ldapPropertyIndex : ldapPropertyIndexes) {
184
                    String ldapPropertyKey = ldapPropertyMap.get(
185
                            ldapPropertyIndex).getKey();
186
                    PropertyService.checkAndSetProperty(request,
187
                            ldapPropertyKey);
188
                }
189 4080 daigle
190
				// we need to write the options from memory to the properties
191
				// file
192
				PropertyService.persistProperties();
193
194
				// Validate that the options provided are legitimate. Note that
195
				// we've allowed them to persist their entries. As of this point
196
				// there is no other easy way to go back to the configure form
197
				// and preserve their entries.
198
				validationErrors.addAll(validateOptions(request));
199
200
201
				// Write out the configurable properties to a backup file
202
				// outside the install directory.  Note that we allow them to
203
				// do this even if they have validation errors.  They will
204
				// need to go back and fix the errors before they can run metacat.
205 4705 daigle
206
				// This is a special case, since it is possible that the backup directory
207
				// may not have been specified yet.  If not, authentication values need to be
208
				// persisted by the BackupAdmin when the backup directory is specified.
209
				String backupDir = PropertyService.getProperty("application.backupDir");
210
				if (backupDir != null) {
211
					PropertyService.persistAuthBackupProperties(request.getSession()
212 4080 daigle
						.getServletContext());
213 4705 daigle
				}
214 4080 daigle
215
			} catch (GeneralPropertyException gpe) {
216 5030 daigle
				String errorMessage = "AuthAdmin.configureAuth - Problem getting or setting property while "
217 4080 daigle
					+ "processing LDAP properties page: " + gpe.getMessage();
218
				logMetacat.error(errorMessage);
219
				processingErrors.add(errorMessage);
220 4159 daigle
			}
221 4080 daigle
222
			try {
223
				if (validationErrors.size() > 0 || processingErrors.size() > 0) {
224
					RequestUtil.clearRequestMessages(request);
225
					RequestUtil.setRequestFormErrors(request, validationErrors);
226
					RequestUtil.setRequestErrors(request, processingErrors);
227 5027 daigle
					RequestUtil.forwardRequest(request, response, "/admin", null);
228 4080 daigle
				} else {
229
					// Now that the options have been set, change the
230 4590 daigle
					// 'authConfigured' option to 'true'
231
					PropertyService.setProperty("configutil.authConfigured",
232 4080 daigle
							PropertyService.CONFIGURED);
233
234
					// Reload the main metacat configuration page
235 4590 daigle
					processingSuccess.add("Authentication successfully configured");
236 4080 daigle
					RequestUtil.clearRequestMessages(request);
237
					RequestUtil.setRequestSuccess(request, processingSuccess);
238
					RequestUtil.forwardRequest(request, response,
239 5027 daigle
							"/admin?configureType=configure&processForm=false", null);
240 4080 daigle
				}
241 5076 daigle
			} catch (MetacatUtilException mue) {
242
				throw new AdminException("AuthAdmin.configureAuth - utility problem forwarding request while "
243
						+ "processing LDAP properties page: " + mue.getMessage());
244 4084 daigle
			} catch (GeneralPropertyException gpe) {
245 5030 daigle
				String errorMessage = "AuthAdmin.configureAuth - Problem getting or setting property while "
246 4590 daigle
					+ "processing Authentication properties page: " + gpe.getMessage();
247 4084 daigle
				logMetacat.error(errorMessage);
248
				processingErrors.add(errorMessage);
249 4080 daigle
			}
250
		}
251
	}
252
253
	/**
254
	 * Validate the most important configuration options submitted by the user.
255
	 *
256
	 * @return a vector holding error message for any fields that fail
257
	 *         validation.
258
	 */
259
	protected Vector<String> validateOptions(HttpServletRequest request) {
260
		Vector<String> errorVector = new Vector<String>();
261
262 4590 daigle
		String adminUsers = request.getParameter("auth.administrators");
263 4547 daigle
		Vector<String> adminUserList = StringUtil.toVector(adminUsers, ':');
264 4080 daigle
265 4547 daigle
		try {
266 4590 daigle
			AuthSession authSession = new AuthSession();
267 4547 daigle
			for (String adminUser : adminUserList) {
268
				try {
269 4590 daigle
					authSession.getAttributes(adminUser);
270 4547 daigle
				} catch (ConnectException ce) {
271
					if (ce.getMessage() != null
272
							&& ce.getMessage().contains("NameNotFoundException")) {
273 8530 tao
						errorVector.add("User : " + adminUser + " is not in the specified identity service."+
274
							" If you chose to use the AuthFile as the authentication class, please add the user to the password file first.");
275 4547 daigle
					} else {
276
						errorVector.add("Connection error while verifying Metacat " +
277
								"Administrators : " + ce.getMessage());
278
					}
279
				}
280
			}
281
		} catch (InstantiationException ie) {
282 6932 jones
			errorVector.add("AuthAdmin.validateOptions - InstantiationException while verifying Metacat Administrators : "
283 4547 daigle
							+ ie.getMessage());
284 6932 jones
		} catch (IllegalAccessException e) {
285
		    errorVector.add("AuthAdmin.validateOptions - IllegalAccessException : "
286
                  + e.getMessage());
287
        } catch (ClassNotFoundException e) {
288
            errorVector.add("AuthAdmin.validateOptions - ClassNotFoundException : "
289
                  + e.getMessage());
290 8534 tao
        } catch (Exception e) {
291
            errorVector.add("AuthAdmin.validateOptions - An exception : "+e.getMessage());
292 6932 jones
        }
293 4547 daigle
294 4080 daigle
		return errorVector;
295
	}
296
}