Project

General

Profile

1 4080 daigle
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements administrative 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.util;
28
29
import java.util.Calendar;
30
import java.util.Vector;
31
32
import javax.servlet.http.HttpServletRequest;
33
import javax.servlet.http.HttpSession;
34
35
import edu.ucsb.nceas.metacat.AuthSession;
36 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
37 4080 daigle
import edu.ucsb.nceas.metacat.service.SessionService;
38 5015 daigle
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
39
import edu.ucsb.nceas.metacat.shared.ServiceException;
40 4080 daigle
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
41
import edu.ucsb.nceas.utilities.StringUtil;
42
43 4589 daigle
public class AuthUtil {
44 4080 daigle
45
	private static Vector<String> administrators = null;
46
	private static Vector<String> moderators = null;
47
	private static Vector<String> allowedSubmitters = null;
48
	private static Vector<String> deniedSubmitters = null;
49
50
	/**
51
	 * private constructor - all methods are static so there is no no need to
52
	 * instantiate.
53
	 */
54 4589 daigle
	private AuthUtil() {}
55 4080 daigle
56
	/**
57
	 * Get the administrators from metacat.properties
58
	 *
59
	 * @return a Vector of Strings holding the administrators
60
	 */
61 4854 daigle
	public static Vector<String> getAdministrators() throws MetacatUtilException {
62 4080 daigle
		if (administrators == null) {
63
			populateAdministrators();
64
		}
65
		return administrators;
66
	}
67
68
	/**
69
	 * Get the allowed submitters from metacat.properties
70
	 *
71
	 * @return a Vector of Strings holding the submitters
72
	 */
73 4854 daigle
	public static Vector<String> getAllowedSubmitters() throws MetacatUtilException {
74 4080 daigle
		if (allowedSubmitters == null) {
75
			populateAllowedSubmitters();
76
		}
77
		return allowedSubmitters;
78
	}
79
80
	/**
81
	 * Get the denied submitters from metacat.properties
82
	 *
83
	 * @return a Vector of Strings holding the denied submitters
84
	 */
85 4854 daigle
	public static Vector<String> getDeniedSubmitters() throws MetacatUtilException {
86 4080 daigle
		if (deniedSubmitters == null) {
87
			populateDeniedSubmitters();
88
		}
89
		return deniedSubmitters;
90
	}
91
92
	/**
93 4627 daigle
	 * Get the moderators from metacat.properties
94
	 *
95
	 * @return a Vector of Strings holding the moderators
96
	 */
97 4854 daigle
	public static Vector<String> getModerators() throws MetacatUtilException {
98 4627 daigle
		if (moderators == null) {
99
			populateModerators();
100
		}
101
		return moderators;
102
	}
103
104
	/**
105 4080 daigle
	 * Get the vector of administrator credentials from metacat.properties
106
	 * and put into global administrators list
107
	 */
108 4854 daigle
	private static void populateAdministrators() throws MetacatUtilException {
109 4080 daigle
		String administratorString = null;
110
		try {
111
			administratorString =
112 4589 daigle
				PropertyService.getProperty("auth.administrators");
113 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
114 4854 daigle
			throw new MetacatUtilException("Could not get metacat property: auth.administrators. "
115 4080 daigle
							+ "There will be no registered metacat adminstrators: "
116
							+ pnfe.getMessage());
117
		}
118
		administrators = StringUtil.toVector(administratorString, ':');
119
	}
120
121
	/**
122
	 * Get the vector of allowed submitter credentials from metacat.properties
123
	 * and put into global allowedSubmitters list
124
	 */
125 4854 daigle
	private static void populateAllowedSubmitters() throws MetacatUtilException {
126 4080 daigle
		String allowedSubmitterString = null;
127
		try {
128 4589 daigle
			allowedSubmitterString = PropertyService.getProperty("auth.allowedSubmitters");
129 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
130 4854 daigle
			throw new MetacatUtilException("Could not get metacat property: auth.allowedSubmitters. "
131 4080 daigle
					+ "Anyone will be allowed to submit: "
132
					+ pnfe.getMessage());
133
		}
134
		allowedSubmitters = StringUtil.toVector(allowedSubmitterString, ':');
135
	}
136
137
	/**
138
	 * Get the vector of denied submitter credentials from metacat.properties
139
	 * and put into global deniedSubmitters list
140
	 */
141 4854 daigle
	private static void populateDeniedSubmitters() throws MetacatUtilException {
142 4080 daigle
		String deniedSubmitterString = null;
143
		try {
144 4589 daigle
			deniedSubmitterString = PropertyService.getProperty("auth.deniedSubmitters");
145 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
146 4854 daigle
			throw new MetacatUtilException("Could not get metacat property: auth.deniedSubmitters: "
147 4080 daigle
					+ pnfe.getMessage());
148
		}
149
		deniedSubmitters = StringUtil.toVector(deniedSubmitterString, ':');
150
	}
151 4627 daigle
152
	/**
153
	 * Get the vector of moderator credentials from metacat.properties
154
	 * and put into global administrators list
155
	 */
156 4854 daigle
	private static void populateModerators() throws MetacatUtilException {
157 4627 daigle
		String moderatorString = null;
158
		try {
159
			moderatorString =
160
				PropertyService.getProperty("auth.moderators");
161
		} catch (PropertyNotFoundException pnfe) {
162 4854 daigle
			throw new MetacatUtilException("Could not get metacat property: auth.moderators. "
163 4627 daigle
							+ "There will be no registered metacat moderators: "
164
							+ pnfe.getMessage());
165
		}
166
		moderators = StringUtil.toVector(moderatorString, ':');
167
	}
168 4080 daigle
169
	/**
170
	 * log the user in against ldap.  If the login is successful, add
171
	 * the session information to the session list in SessionUtil.
172
	 *
173
	 * @param request the http request.
174
	 */
175 4854 daigle
	public static boolean logUserIn(HttpServletRequest request, String userName, String password) throws MetacatUtilException {
176 4080 daigle
		AuthSession authSession = null;
177
178
		// make sure we have username and password.
179 4589 daigle
		if (userName == null || password == null) {
180 4854 daigle
			throw new MetacatUtilException("null username or password when logging user in");
181 4080 daigle
		}
182
183
		// Create auth session
184
		try {
185
			authSession = new AuthSession();
186
		} catch (Exception e) {
187 4854 daigle
			throw new MetacatUtilException("Could not instantiate AuthSession: "
188 4080 daigle
					+ e.getMessage());
189
		}
190
		// authenticate user against ldap
191 4628 daigle
		if(!authSession.authenticate(request, userName,password)) {
192 4854 daigle
			throw new MetacatUtilException(authSession.getMessage());
193 4628 daigle
		}
194 4080 daigle
195 4628 daigle
		// if login was successful, add the session information to the
196 4080 daigle
		// global session list.
197 4628 daigle
		HttpSession session = authSession.getSessions();
198
		String sessionId = session.getId();
199 4780 daigle
200
		try {
201 4628 daigle
		SessionService.registerSession(sessionId,
202
				(String) session.getAttribute("username"),
203
				(String[]) session.getAttribute("groupnames"),
204 5070 daigle
				(String) session.getAttribute("password"),
205
				(String) session.getAttribute("name"));
206 4780 daigle
		} catch (ServiceException se) {
207 4854 daigle
			throw new MetacatUtilException("Problem registering session: " + se.getMessage());
208 4780 daigle
		}
209 4080 daigle
210 4628 daigle
		return true;
211 4080 daigle
	}
212
213
	/**
214
	 * Checks to see if the user is logged in by grabbing the session from the
215
	 * request and seeing if it exists in the global session list.
216
	 *
217
	 * @param request the http request that holds the login session
218
	 * @return boolean that is true if the user is logged in, false otherwise
219
	 */
220 4854 daigle
	public static boolean isUserLoggedIn(HttpServletRequest request) throws MetacatUtilException{
221 4080 daigle
		SessionData sessionData = null;
222
		String sessionId = request.getSession().getId();
223
224
		try {
225
226
			if (sessionId != null && SessionService.isSessionRegistered(sessionId)) {
227
				// get the registered session data
228
				sessionData = SessionService.getRegisteredSession(sessionId);
229
230
				// get the timeout limit
231
				String sessionTimeout = PropertyService.getProperty("auth.timeoutMinutes");
232
				int sessionTimeoutInt = Integer.parseInt(sessionTimeout);
233
234
				// get the last time the session was accessed
235
				Calendar lastAccessedTime = sessionData.getLastAccessedTime();
236
				// get the current time and set back "sessionTimoutInt" minutes
237
				Calendar now = Calendar.getInstance();
238
				now.add(Calendar.MINUTE, 0 - sessionTimeoutInt);
239
240
				// if the last accessed time is before now minus the timeout,
241
				// the session has expired. Unregister it and return false.
242
				if (lastAccessedTime.before(now)) {
243
					SessionService.unRegisterSession(sessionId);
244
					return false;
245
				}
246
247
				return true;
248
			}
249
250
		} catch (PropertyNotFoundException pnfe) {
251 4854 daigle
			throw new MetacatUtilException("Could not determine if user is logged in because "
252 4080 daigle
					+ "of property error: " + pnfe.getMessage());
253
		} catch (NumberFormatException nfe) {
254 4854 daigle
			throw new MetacatUtilException("Could not determine if user is logged in because "
255 4080 daigle
					+ "of number conversion error: " + nfe.getMessage());
256
		}
257
258
		return false;
259
	}
260
261
	/**
262
	 * Checks to see if the user is logged in as admin by first checking if the
263
	 * user is logged in and then seeing if the user's account is on the
264
	 * administrators list in metacat.properties.
265
	 *
266
	 * @param request
267
	 *            the http request that holds the login session
268
	 * @return boolean that is true if the user is logged in as admin, false
269
	 *         otherwise
270
	 */
271 4854 daigle
	public static boolean isUserLoggedInAsAdmin(HttpServletRequest request) throws MetacatUtilException {
272 4080 daigle
		if (!isUserLoggedIn(request)) {
273
			return false;
274
		}
275
276
		String userName = getUserName(request);
277
		boolean isAdmin = isAdministrator(userName, null);
278
279
		return isAdmin;
280
	}
281
282
	/**
283
	 * Gets the user name from the login session on the http request
284
	 *
285
	 * @param request
286
	 *            the http request that holds the login session
287
	 * @return String that holds the user name
288
	 */
289
	public static String getUserName(HttpServletRequest request) {
290
		String userName = (String)request.getSession().getAttribute("username");
291
292
		return userName;
293
	}
294
295
	/**
296
	 * Gets the user group names from the login session on the http request
297
	 *
298
	 * @param request
299
	 *            the http request that holds the login session
300
	 * @return String array that holds the user groups
301
	 */
302
	public static String[] getGroupNames(HttpServletRequest request) {
303
		String sessionId = request.getSession().getId();;
304
		SessionData sessionData = SessionService.getRegisteredSession(sessionId);
305
		String[] groupNames = { "" };
306
307
		if (sessionData != null) {
308
			groupNames = sessionData.getGroupNames();
309
		}
310
311
		return groupNames;
312
	}
313
314
	/**
315
	 * Creates an ldap credentail string from the username, organization
316
	 * and dn list.
317
	 *
318
	 * @param username the user name
319
	 * @param organization the organization
320
	 * @param dnList a list of dns
321
	 * @return String holding the ldap login string
322
	 */
323
	public static String createLDAPString(String username, String organization,
324 4854 daigle
			Vector<String> dnList) throws MetacatUtilException {
325 4080 daigle
326
		if (username == null || organization == null || dnList == null || dnList.size() == 0) {
327 4854 daigle
			throw new MetacatUtilException("Could not generate LDAP user string.  One of the following is null: username, organization or dnlist");
328 4080 daigle
		}
329
330
		String ldapString = "uid=" + username + ",o=" + organization;
331
332
		for (String dn : dnList) {
333
			ldapString += "," + dn;
334
		}
335
336
		return ldapString;
337
	}
338
339
	/**
340
	 * Reports whether LDAP is fully configured.
341
	 *
342
	 * @return a boolean that is true if all sections are configured and false
343
	 *         otherwise
344
	 */
345 4854 daigle
	public static boolean isAuthConfigured() throws MetacatUtilException {
346 4589 daigle
		String authConfiguredString = PropertyService.UNCONFIGURED;
347 4080 daigle
		try {
348 4589 daigle
			authConfiguredString = PropertyService.getProperty("configutil.authConfigured");
349 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
350 4854 daigle
			throw new MetacatUtilException("Could not determine if LDAP is configured: "
351 4080 daigle
					+ pnfe.getMessage());
352
		}
353 4589 daigle
		return !authConfiguredString.equals(PropertyService.UNCONFIGURED);
354 4080 daigle
	}
355
356
	/**
357
	 * Check if the specified user is part of the administrators list
358
	 *
359
	 * @param username
360
	 *            the user login credentails
361
	 * @param groups
362
	 *            a list of the user's groups
363
	 */
364
	public static boolean isAdministrator(String username, String[] groups)
365 4854 daigle
			throws MetacatUtilException {
366 4080 daigle
		return onAccessList(getAdministrators(), username, groups);
367
	}
368
369
	/**
370
	 * Check if the specified user is part of the moderators list
371
	 *
372
	 * @param username
373
	 *            the user login credentails
374
	 * @param groups
375
	 *            a list of the user's groups
376
	 */
377 4854 daigle
	public static boolean isModerator(String username, String[] groups) throws MetacatUtilException{
378 4627 daigle
		return onAccessList(getModerators(), username, groups);
379 4080 daigle
	}
380
381
	/**
382
	 * Check if the specified user is part of the moderators list
383
	 *
384
	 * @param username
385
	 *            the user login credentails
386
	 * @param groups
387
	 *            a list of the user's groups
388
	 */
389
	public static boolean isAllowedSubmitter(String username, String[] groups)
390 4854 daigle
			throws MetacatUtilException {
391 4080 daigle
		if (getAllowedSubmitters().size() == 0) {
392
			// no allowedSubmitters list specified -
393
			// hence everyone should be allowed
394
			return true;
395
		}
396
		return (onAccessList(getAllowedSubmitters(), username, groups));
397
	}
398
399
	/**
400
	 * Check if the specified user is part of the moderators list
401
	 *
402
	 * @param username
403
	 *            the user login credentails
404
	 * @param groups
405
	 *            a list of the user's groups
406
	 */
407
	public static boolean isDeniedSubmitter(String username, String[] groups)
408 4854 daigle
			throws MetacatUtilException {
409 4080 daigle
		return (onAccessList(getDeniedSubmitters(), username, groups));
410
	}
411
412
	/**
413
	 * Check if the specified user can insert the document
414
	 *
415
	 * @param username
416
	 *            the user login credentails
417
	 * @param groups
418
	 *            a list of the user's groups
419
	 */
420
	public static boolean canInsertOrUpdate(String username, String[] groups)
421 4854 daigle
			throws MetacatUtilException {
422 4080 daigle
		return (isAllowedSubmitter(username, groups) && !isDeniedSubmitter(username,
423
				groups));
424
	}
425
426
	/**
427
	 * Check if the user is on a given access list.  This is true if either the
428
	 * user or the user's group is on the list.
429
	 *
430
	 * @param accessList the list we want to check against
431
	 * @param username the name of the user we want to check
432
	 * @param groups a list of the user's groups
433
	 */
434
	private static boolean onAccessList(Vector<String> accessList, String username,
435
			String[] groups) {
436
437
		// this should never happen.  All calls to this method should use the
438
		// appropriate getter to retrieve the accessList.  That should guarentee
439
		// that the access is at least an empty Vector.
440
		if (accessList == null) {
441
			return false;
442
		}
443
444
		// Check that the user is authenticated as an administrator account
445
		for (String accessString : accessList) {
446
			// check the given admin dn is a group dn...
447
			if (groups != null && accessString.startsWith("cn=")) {
448
				// is a group dn
449
				for (int j = 0; j < groups.length; j++) {
450 4984 daigle
					if (groups[j] != null && groups[j].equals(accessString)) {
451 4080 daigle
						return true;
452
					}
453
				}
454
			} else {
455
				// is a user dn
456
				if (username != null && username.equals(accessString)) {
457
					return true;
458
				}
459
			}
460
		}
461
		return false;
462
	}
463
464
}