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
import edu.ucsb.nceas.metacat.service.PropertyService;
37
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
				(String) session.getAttribute("password"));
205 4780 daigle
		} catch (ServiceException se) {
206 4854 daigle
			throw new MetacatUtilException("Problem registering session: " + se.getMessage());
207 4780 daigle
		}
208 4080 daigle
209 4628 daigle
		return true;
210 4080 daigle
	}
211
212
	/**
213
	 * Checks to see if the user is logged in by grabbing the session from the
214
	 * request and seeing if it exists in the global session list.
215
	 *
216
	 * @param request the http request that holds the login session
217
	 * @return boolean that is true if the user is logged in, false otherwise
218
	 */
219 4854 daigle
	public static boolean isUserLoggedIn(HttpServletRequest request) throws MetacatUtilException{
220 4080 daigle
		SessionData sessionData = null;
221
		String sessionId = request.getSession().getId();
222
223
		try {
224
225
			if (sessionId != null && SessionService.isSessionRegistered(sessionId)) {
226
				// get the registered session data
227
				sessionData = SessionService.getRegisteredSession(sessionId);
228
229
				// get the timeout limit
230
				String sessionTimeout = PropertyService.getProperty("auth.timeoutMinutes");
231
				int sessionTimeoutInt = Integer.parseInt(sessionTimeout);
232
233
				// get the last time the session was accessed
234
				Calendar lastAccessedTime = sessionData.getLastAccessedTime();
235
				// get the current time and set back "sessionTimoutInt" minutes
236
				Calendar now = Calendar.getInstance();
237
				now.add(Calendar.MINUTE, 0 - sessionTimeoutInt);
238
239
				// if the last accessed time is before now minus the timeout,
240
				// the session has expired. Unregister it and return false.
241
				if (lastAccessedTime.before(now)) {
242
					SessionService.unRegisterSession(sessionId);
243
					return false;
244
				}
245
246
				return true;
247
			}
248
249
		} catch (PropertyNotFoundException pnfe) {
250 4854 daigle
			throw new MetacatUtilException("Could not determine if user is logged in because "
251 4080 daigle
					+ "of property error: " + pnfe.getMessage());
252
		} catch (NumberFormatException nfe) {
253 4854 daigle
			throw new MetacatUtilException("Could not determine if user is logged in because "
254 4080 daigle
					+ "of number conversion error: " + nfe.getMessage());
255
		}
256
257
		return false;
258
	}
259
260
	/**
261
	 * Checks to see if the user is logged in as admin by first checking if the
262
	 * user is logged in and then seeing if the user's account is on the
263
	 * administrators list in metacat.properties.
264
	 *
265
	 * @param request
266
	 *            the http request that holds the login session
267
	 * @return boolean that is true if the user is logged in as admin, false
268
	 *         otherwise
269
	 */
270 4854 daigle
	public static boolean isUserLoggedInAsAdmin(HttpServletRequest request) throws MetacatUtilException {
271 4080 daigle
		if (!isUserLoggedIn(request)) {
272
			return false;
273
		}
274
275
		String userName = getUserName(request);
276
		boolean isAdmin = isAdministrator(userName, null);
277
278
		return isAdmin;
279
	}
280
281
	/**
282
	 * Gets the user name from the login session on the http request
283
	 *
284
	 * @param request
285
	 *            the http request that holds the login session
286
	 * @return String that holds the user name
287
	 */
288
	public static String getUserName(HttpServletRequest request) {
289
		String userName = (String)request.getSession().getAttribute("username");
290
291
		return userName;
292
	}
293
294
	/**
295
	 * Gets the user group names from the login session on the http request
296
	 *
297
	 * @param request
298
	 *            the http request that holds the login session
299
	 * @return String array that holds the user groups
300
	 */
301
	public static String[] getGroupNames(HttpServletRequest request) {
302
		String sessionId = request.getSession().getId();;
303
		SessionData sessionData = SessionService.getRegisteredSession(sessionId);
304
		String[] groupNames = { "" };
305
306
		if (sessionData != null) {
307
			groupNames = sessionData.getGroupNames();
308
		}
309
310
		return groupNames;
311
	}
312
313
	/**
314
	 * Creates an ldap credentail string from the username, organization
315
	 * and dn list.
316
	 *
317
	 * @param username the user name
318
	 * @param organization the organization
319
	 * @param dnList a list of dns
320
	 * @return String holding the ldap login string
321
	 */
322
	public static String createLDAPString(String username, String organization,
323 4854 daigle
			Vector<String> dnList) throws MetacatUtilException {
324 4080 daigle
325
		if (username == null || organization == null || dnList == null || dnList.size() == 0) {
326 4854 daigle
			throw new MetacatUtilException("Could not generate LDAP user string.  One of the following is null: username, organization or dnlist");
327 4080 daigle
		}
328
329
		String ldapString = "uid=" + username + ",o=" + organization;
330
331
		for (String dn : dnList) {
332
			ldapString += "," + dn;
333
		}
334
335
		return ldapString;
336
	}
337
338
	/**
339
	 * Reports whether LDAP is fully configured.
340
	 *
341
	 * @return a boolean that is true if all sections are configured and false
342
	 *         otherwise
343
	 */
344 4854 daigle
	public static boolean isAuthConfigured() throws MetacatUtilException {
345 4589 daigle
		String authConfiguredString = PropertyService.UNCONFIGURED;
346 4080 daigle
		try {
347 4589 daigle
			authConfiguredString = PropertyService.getProperty("configutil.authConfigured");
348 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
349 4854 daigle
			throw new MetacatUtilException("Could not determine if LDAP is configured: "
350 4080 daigle
					+ pnfe.getMessage());
351
		}
352 4589 daigle
		return !authConfiguredString.equals(PropertyService.UNCONFIGURED);
353 4080 daigle
	}
354
355
	/**
356
	 * Check if the specified user is part of the administrators list
357
	 *
358
	 * @param username
359
	 *            the user login credentails
360
	 * @param groups
361
	 *            a list of the user's groups
362
	 */
363
	public static boolean isAdministrator(String username, String[] groups)
364 4854 daigle
			throws MetacatUtilException {
365 4080 daigle
		return onAccessList(getAdministrators(), username, groups);
366
	}
367
368
	/**
369
	 * Check if the specified user is part of the moderators list
370
	 *
371
	 * @param username
372
	 *            the user login credentails
373
	 * @param groups
374
	 *            a list of the user's groups
375
	 */
376 4854 daigle
	public static boolean isModerator(String username, String[] groups) throws MetacatUtilException{
377 4627 daigle
		return onAccessList(getModerators(), username, groups);
378 4080 daigle
	}
379
380
	/**
381
	 * Check if the specified user is part of the moderators list
382
	 *
383
	 * @param username
384
	 *            the user login credentails
385
	 * @param groups
386
	 *            a list of the user's groups
387
	 */
388
	public static boolean isAllowedSubmitter(String username, String[] groups)
389 4854 daigle
			throws MetacatUtilException {
390 4080 daigle
		if (getAllowedSubmitters().size() == 0) {
391
			// no allowedSubmitters list specified -
392
			// hence everyone should be allowed
393
			return true;
394
		}
395
		return (onAccessList(getAllowedSubmitters(), username, groups));
396
	}
397
398
	/**
399
	 * Check if the specified user is part of the moderators list
400
	 *
401
	 * @param username
402
	 *            the user login credentails
403
	 * @param groups
404
	 *            a list of the user's groups
405
	 */
406
	public static boolean isDeniedSubmitter(String username, String[] groups)
407 4854 daigle
			throws MetacatUtilException {
408 4080 daigle
		return (onAccessList(getDeniedSubmitters(), username, groups));
409
	}
410
411
	/**
412
	 * Check if the specified user can insert the document
413
	 *
414
	 * @param username
415
	 *            the user login credentails
416
	 * @param groups
417
	 *            a list of the user's groups
418
	 */
419
	public static boolean canInsertOrUpdate(String username, String[] groups)
420 4854 daigle
			throws MetacatUtilException {
421 4080 daigle
		return (isAllowedSubmitter(username, groups) && !isDeniedSubmitter(username,
422
				groups));
423
	}
424
425
	/**
426
	 * Check if the user is on a given access list.  This is true if either the
427
	 * user or the user's group is on the list.
428
	 *
429
	 * @param accessList the list we want to check against
430
	 * @param username the name of the user we want to check
431
	 * @param groups a list of the user's groups
432
	 */
433
	private static boolean onAccessList(Vector<String> accessList, String username,
434
			String[] groups) {
435
436
		// this should never happen.  All calls to this method should use the
437
		// appropriate getter to retrieve the accessList.  That should guarentee
438
		// that the access is at least an empty Vector.
439
		if (accessList == null) {
440
			return false;
441
		}
442
443
		// Check that the user is authenticated as an administrator account
444
		for (String accessString : accessList) {
445
			// check the given admin dn is a group dn...
446
			if (groups != null && accessString.startsWith("cn=")) {
447
				// is a group dn
448
				for (int j = 0; j < groups.length; j++) {
449 4984 daigle
					if (groups[j] != null && groups[j].equals(accessString)) {
450 4080 daigle
						return true;
451
					}
452
				}
453
			} else {
454
				// is a user dn
455
				if (username != null && username.equals(accessString)) {
456
					return true;
457
				}
458
			}
459
		}
460
		return false;
461
	}
462
463
}