Project

General

Profile

1
/**
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: daigle $'
9
 *     '$Date: 2008-11-19 15:25:09 -0800 (Wed, 19 Nov 2008) $'
10
 * '$Revision: 4589 $'
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.naming.AuthenticationException;
33
import javax.naming.NamingException;
34
import javax.servlet.http.HttpServletRequest;
35
import javax.servlet.http.HttpSession;
36

    
37
import edu.ucsb.nceas.metacat.AuthLdap;
38
import edu.ucsb.nceas.metacat.AuthSession;
39
import edu.ucsb.nceas.metacat.service.PropertyService;
40
import edu.ucsb.nceas.metacat.service.SessionService;
41
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
42
import edu.ucsb.nceas.utilities.StringUtil;
43

    
44
public class AuthUtil {
45

    
46
	private static Vector<String> administrators = null;
47
	private static Vector<String> moderators = null;
48
	private static Vector<String> allowedSubmitters = null;
49
	private static Vector<String> deniedSubmitters = null;
50

    
51
	/**
52
	 * private constructor - all methods are static so there is no no need to
53
	 * instantiate.
54
	 */
55
	private AuthUtil() {}
56

    
57
	/**
58
	 * Get the administrators from metacat.properties
59
	 * 
60
	 * @return a Vector of Strings holding the administrators
61
	 */
62
	public static Vector<String> getAdministrators() throws UtilException {
63
		if (administrators == null) {
64
			populateAdministrators();
65
		}
66
		return administrators;
67
	}
68
	
69
	/**
70
	 * Get the allowed submitters from metacat.properties
71
	 * 
72
	 * @return a Vector of Strings holding the submitters
73
	 */
74
	public static Vector<String> getAllowedSubmitters() throws UtilException {
75
		if (allowedSubmitters == null) {			
76
			populateAllowedSubmitters();	
77
		}
78
		return allowedSubmitters;
79
	}
80
	
81
	/**
82
	 * Get the denied submitters from metacat.properties
83
	 * 
84
	 * @return a Vector of Strings holding the denied submitters
85
	 */
86
	public static Vector<String> getDeniedSubmitters() throws UtilException {
87
		if (deniedSubmitters == null) {
88
			populateDeniedSubmitters();
89
		}
90
		return deniedSubmitters;
91
	}
92
	
93
	/**
94
	 * Get the vector of administrator credentials from metacat.properties
95
	 * and put into global administrators list
96
	 */
97
	private static void populateAdministrators() throws UtilException {
98
		String administratorString = null;
99
		try {
100
			administratorString = 
101
				PropertyService.getProperty("auth.administrators");
102
		} catch (PropertyNotFoundException pnfe) {
103
			throw new UtilException("Could not get metacat property: auth.administrators. "
104
							+ "There will be no registered metacat adminstrators: "
105
							+ pnfe.getMessage());
106
		}
107
		administrators = StringUtil.toVector(administratorString, ':');
108
	}
109
	
110
	/**
111
	 * Get the vector of allowed submitter credentials from metacat.properties
112
	 * and put into global allowedSubmitters list
113
	 */
114
	private static void populateAllowedSubmitters() throws UtilException {
115
		String allowedSubmitterString = null;
116
		try {
117
			allowedSubmitterString = PropertyService.getProperty("auth.allowedSubmitters");
118
		} catch (PropertyNotFoundException pnfe) {
119
			throw new UtilException("Could not get metacat property: auth.allowedSubmitters. "
120
					+ "Anyone will be allowed to submit: "
121
					+ pnfe.getMessage());
122
		}		
123
		allowedSubmitters = StringUtil.toVector(allowedSubmitterString, ':');		
124
	}
125
	
126
	/**
127
	 * Get the vector of denied submitter credentials from metacat.properties
128
	 * and put into global deniedSubmitters list
129
	 */
130
	private static void populateDeniedSubmitters() throws UtilException {
131
		String deniedSubmitterString = null;
132
		try {
133
			deniedSubmitterString = PropertyService.getProperty("auth.deniedSubmitters");
134
		} catch (PropertyNotFoundException pnfe) {
135
			throw new UtilException("Could not get metacat property: auth.deniedSubmitters: "
136
					+ pnfe.getMessage());
137
		}		
138
		deniedSubmitters = StringUtil.toVector(deniedSubmitterString, ':');		
139
	}
140

    
141
//	/**
142
//	 * Validate connectivity to the ldap server. This does not test user
143
//	 * authentication. Validation methods return a string error message if there
144
//	 * is an issue. This allows the calling code to run several validations and
145
//	 * compile the errors into a list that can be displayed on a web page if
146
//	 * desired.
147
//	 * 
148
//	 * @param ldapurl
149
//	 *            the url of the ldap server
150
//	 * @param ldapbase
151
//	 *            the ldap base value to test
152
//	 * @return a string holding error message if validation fails.
153
//	 */
154
//	public static String validateLDAPConnectivity(String ldapurl,
155
//			String ldapbase) {
156
//		try {
157
//			AuthLdap authLdap = new AuthLdap();
158
//			authLdap.testCredentials(
159
//					"uid=bogusname,o=NCEAS,dc=ecoinformatics,dc=org",
160
//					"boguspassword", ldapurl, ldapbase);
161
//		} catch (AuthenticationException ae) {
162
//			// Do nothing here. We are using dummy uid and password, so we
163
//			// expect authentication exceptions
164
//		} catch (javax.naming.InvalidNameException ine) {
165
//			return "An invalid domain name was provided: " + ine.getMessage();
166
//		} catch (NamingException ne) {
167
//			return "An invalid ldap name was provided: " + ne.getMessage();
168
//		} catch (InstantiationException ie) {
169
//			return "Could not instantiate AuthLdap: " + ie.getMessage();
170
//		}
171
//
172
//		return null;
173
//	}
174

    
175
	/**
176
	 * log the user in against ldap.  If the login is successful, add
177
	 * the session information to the session list in SessionUtil.
178
	 * 
179
	 * @param request the http request.
180
	 */
181
	public static boolean logUserIn(HttpServletRequest request, String userName, String password) throws UtilException {
182
		AuthSession authSession = null;
183

    
184
		// make sure we have username and password.
185
		if (userName == null || password == null) {
186
			throw new UtilException("null username, password, or dn list when logging user in");
187
		}
188

    
189
		// put the login credentials into an LDAP string
190
//		String ldapString = createLDAPString(userName, organization, dnList);
191

    
192
		// Create auth session
193
		try {
194
			authSession = new AuthSession();
195
		} catch (Exception e) {
196
			throw new UtilException("Could not instantiate AuthSession: "
197
					+ e.getMessage());
198
		}
199
		// authenticate user against ldap
200
		boolean isValid = authSession.authenticate(request, userName,
201
				password);
202
		
203
		// if login was successful, add the session information to the 
204
		// global session list.
205
		if (isValid) {
206
			HttpSession session = authSession.getSessions();
207
			String sessionId = session.getId();
208
			SessionService.registerSession(sessionId, 
209
					(String) session.getAttribute("username"), 
210
					(String[]) session.getAttribute("groupnames"),
211
					(String) session.getAttribute("password"));
212
		}
213
		
214
		return isValid;
215
	}
216

    
217
	/**
218
	 * Checks to see if the user is logged in by grabbing the session from the
219
	 * request and seeing if it exists in the global session list.
220
	 * 
221
	 * @param request the http request that holds the login session
222
	 * @return boolean that is true if the user is logged in, false otherwise
223
	 */
224
	public static boolean isUserLoggedIn(HttpServletRequest request) throws UtilException{
225
		SessionData sessionData = null;
226
		String sessionId = request.getSession().getId();
227

    
228
		try {
229

    
230
			if (sessionId != null && SessionService.isSessionRegistered(sessionId)) {
231
				// get the registered session data
232
				sessionData = SessionService.getRegisteredSession(sessionId);
233

    
234
				// get the timeout limit
235
				String sessionTimeout = PropertyService.getProperty("auth.timeoutMinutes");
236
				int sessionTimeoutInt = Integer.parseInt(sessionTimeout);
237

    
238
				// get the last time the session was accessed
239
				Calendar lastAccessedTime = sessionData.getLastAccessedTime();
240
				// get the current time and set back "sessionTimoutInt" minutes
241
				Calendar now = Calendar.getInstance();
242
				now.add(Calendar.MINUTE, 0 - sessionTimeoutInt);
243

    
244
				// if the last accessed time is before now minus the timeout,
245
				// the session has expired. Unregister it and return false.
246
				if (lastAccessedTime.before(now)) {
247
					SessionService.unRegisterSession(sessionId);
248
					return false;
249
				}
250

    
251
				return true;
252
			}
253
			
254
		} catch (PropertyNotFoundException pnfe) {
255
			throw new UtilException("Could not determine if user is logged in because " 
256
					+ "of property error: " + pnfe.getMessage());
257
		} catch (NumberFormatException nfe) {
258
			throw new UtilException("Could not determine if user is logged in because " 
259
					+ "of number conversion error: " + nfe.getMessage());
260
		}
261

    
262
		return false;
263
	}
264

    
265
	/**
266
	 * Checks to see if the user is logged in as admin by first checking if the
267
	 * user is logged in and then seeing if the user's account is on the
268
	 * administrators list in metacat.properties.
269
	 * 
270
	 * @param request
271
	 *            the http request that holds the login session
272
	 * @return boolean that is true if the user is logged in as admin, false
273
	 *         otherwise
274
	 */
275
	public static boolean isUserLoggedInAsAdmin(HttpServletRequest request) throws UtilException {
276
		if (!isUserLoggedIn(request)) {
277
			return false;
278
		}
279

    
280
		String userName = getUserName(request);
281
		boolean isAdmin = isAdministrator(userName, null);
282

    
283
		return isAdmin;
284
	}
285

    
286
	/**
287
	 * Gets the user name from the login session on the http request
288
	 * 
289
	 * @param request
290
	 *            the http request that holds the login session
291
	 * @return String that holds the user name
292
	 */
293
	public static String getUserName(HttpServletRequest request) {
294
		String userName = (String)request.getSession().getAttribute("username");
295

    
296
		return userName;
297
	}
298

    
299
	/**
300
	 * Gets the user group names from the login session on the http request
301
	 * 
302
	 * @param request
303
	 *            the http request that holds the login session
304
	 * @return String array that holds the user groups
305
	 */
306
	public static String[] getGroupNames(HttpServletRequest request) {
307
		String sessionId = request.getSession().getId();;
308
		SessionData sessionData = SessionService.getRegisteredSession(sessionId);
309
		String[] groupNames = { "" };
310

    
311
		if (sessionData != null) {
312
			groupNames = sessionData.getGroupNames();
313
		}
314

    
315
		return groupNames;
316
	}
317

    
318
	/**
319
	 * Creates an ldap credentail string from the username, organization
320
	 * and dn list.
321
	 * 
322
	 * @param username the user name
323
	 * @param organization the organization
324
	 * @param dnList a list of dns
325
	 * @return String holding the ldap login string
326
	 */	
327
	public static String createLDAPString(String username, String organization,
328
			Vector<String> dnList) throws UtilException {
329

    
330
		if (username == null || organization == null || dnList == null || dnList.size() == 0) {
331
			throw new UtilException("Could not generate LDAP user string.  One of the following is null: username, organization or dnlist");
332
		}
333

    
334
		String ldapString = "uid=" + username + ",o=" + organization;
335

    
336
		for (String dn : dnList) {
337
			ldapString += "," + dn;
338
		}
339

    
340
		return ldapString;
341
	}
342

    
343
	/**
344
	 * Reports whether LDAP is fully configured.
345
	 * 
346
	 * @return a boolean that is true if all sections are configured and false
347
	 *         otherwise
348
	 */
349
	public static boolean isAuthConfigured() throws UtilException {
350
		String authConfiguredString = PropertyService.UNCONFIGURED;
351
		try {
352
			authConfiguredString = PropertyService.getProperty("configutil.authConfigured");
353
		} catch (PropertyNotFoundException pnfe) {
354
			throw new UtilException("Could not determine if LDAP is configured: "
355
					+ pnfe.getMessage());
356
		}
357
		return !authConfiguredString.equals(PropertyService.UNCONFIGURED);
358
	}
359

    
360
	/**
361
	 * Check if the specified user is part of the administrators list
362
	 * 
363
	 * @param username
364
	 *            the user login credentails
365
	 * @param groups
366
	 *            a list of the user's groups
367
	 */
368
	public static boolean isAdministrator(String username, String[] groups)
369
			throws UtilException {
370
		return onAccessList(getAdministrators(), username, groups);
371
	}
372

    
373
	/**
374
	 * Check if the specified user is part of the moderators list
375
	 * 
376
	 * @param username
377
	 *            the user login credentails
378
	 * @param groups
379
	 *            a list of the user's groups
380
	 */
381
	public static boolean isModerator(String username, String[] groups) {
382
		return onAccessList(moderators, username, groups);
383
	}
384

    
385
	/**
386
	 * Check if the specified user is part of the moderators list
387
	 * 
388
	 * @param username
389
	 *            the user login credentails
390
	 * @param groups
391
	 *            a list of the user's groups
392
	 */
393
	public static boolean isAllowedSubmitter(String username, String[] groups)
394
			throws UtilException {
395
		if (getAllowedSubmitters().size() == 0) {
396
			// no allowedSubmitters list specified -
397
			// hence everyone should be allowed
398
			return true;
399
		}
400
		return (onAccessList(getAllowedSubmitters(), username, groups));
401
	}
402

    
403
	/**
404
	 * Check if the specified user is part of the moderators list
405
	 * 
406
	 * @param username
407
	 *            the user login credentails
408
	 * @param groups
409
	 *            a list of the user's groups
410
	 */
411
	public static boolean isDeniedSubmitter(String username, String[] groups)
412
			throws UtilException {
413
		return (onAccessList(getDeniedSubmitters(), username, groups));
414
	}
415

    
416
	/**
417
	 * Check if the specified user can insert the document
418
	 * 
419
	 * @param username
420
	 *            the user login credentails
421
	 * @param groups
422
	 *            a list of the user's groups
423
	 */
424
	public static boolean canInsertOrUpdate(String username, String[] groups)
425
			throws UtilException {
426
		return (isAllowedSubmitter(username, groups) && !isDeniedSubmitter(username,
427
				groups));
428
	}
429

    
430
	/**
431
	 * Check if the user is on a given access list.  This is true if either the 
432
	 * user or the user's group is on the list.
433
	 * 
434
	 * @param accessList the list we want to check against
435
	 * @param username the name of the user we want to check
436
	 * @param groups a list of the user's groups
437
	 */
438
	private static boolean onAccessList(Vector<String> accessList, String username,
439
			String[] groups) {
440

    
441
		// this should never happen.  All calls to this method should use the 
442
		// appropriate getter to retrieve the accessList.  That should guarentee
443
		// that the access is at least an empty Vector.
444
		if (accessList == null) {
445
			return false;
446
		}
447

    
448
		// Check that the user is authenticated as an administrator account
449
		for (String accessString : accessList) {
450
			// check the given admin dn is a group dn...
451
			if (groups != null && accessString.startsWith("cn=")) {
452
				// is a group dn
453
				for (int j = 0; j < groups.length; j++) {
454
					if (groups[j].equals(accessString)) {
455
						return true;
456
					}
457
				}
458
			} else {
459
				// is a user dn
460
				if (username != null && username.equals(accessString)) {
461
					return true;
462
				}
463
			}
464
		}
465
		return false;
466
	}
467

    
468
}
(1-1/11)