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: 2009-08-04 14:32:58 -0700 (Tue, 04 Aug 2009) $'
10
 * '$Revision: 5015 $'
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
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
39
import edu.ucsb.nceas.metacat.shared.ServiceException;
40
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
41
import edu.ucsb.nceas.utilities.StringUtil;
42

    
43
public class AuthUtil {
44

    
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
	private AuthUtil() {}
55

    
56
	/**
57
	 * Get the administrators from metacat.properties
58
	 * 
59
	 * @return a Vector of Strings holding the administrators
60
	 */
61
	public static Vector<String> getAdministrators() throws MetacatUtilException {
62
		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
	public static Vector<String> getAllowedSubmitters() throws MetacatUtilException {
74
		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
	public static Vector<String> getDeniedSubmitters() throws MetacatUtilException {
86
		if (deniedSubmitters == null) {
87
			populateDeniedSubmitters();
88
		}
89
		return deniedSubmitters;
90
	}
91
	
92
	/**
93
	 * Get the moderators from metacat.properties
94
	 * 
95
	 * @return a Vector of Strings holding the moderators
96
	 */
97
	public static Vector<String> getModerators() throws MetacatUtilException {
98
		if (moderators == null) {
99
			populateModerators();
100
		}
101
		return moderators;
102
	}
103
	
104
	/**
105
	 * Get the vector of administrator credentials from metacat.properties
106
	 * and put into global administrators list
107
	 */
108
	private static void populateAdministrators() throws MetacatUtilException {
109
		String administratorString = null;
110
		try {
111
			administratorString = 
112
				PropertyService.getProperty("auth.administrators");
113
		} catch (PropertyNotFoundException pnfe) {
114
			throw new MetacatUtilException("Could not get metacat property: auth.administrators. "
115
							+ "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
	private static void populateAllowedSubmitters() throws MetacatUtilException {
126
		String allowedSubmitterString = null;
127
		try {
128
			allowedSubmitterString = PropertyService.getProperty("auth.allowedSubmitters");
129
		} catch (PropertyNotFoundException pnfe) {
130
			throw new MetacatUtilException("Could not get metacat property: auth.allowedSubmitters. "
131
					+ "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
	private static void populateDeniedSubmitters() throws MetacatUtilException {
142
		String deniedSubmitterString = null;
143
		try {
144
			deniedSubmitterString = PropertyService.getProperty("auth.deniedSubmitters");
145
		} catch (PropertyNotFoundException pnfe) {
146
			throw new MetacatUtilException("Could not get metacat property: auth.deniedSubmitters: "
147
					+ pnfe.getMessage());
148
		}		
149
		deniedSubmitters = StringUtil.toVector(deniedSubmitterString, ':');		
150
	}
151
	
152
	/**
153
	 * Get the vector of moderator credentials from metacat.properties
154
	 * and put into global administrators list
155
	 */
156
	private static void populateModerators() throws MetacatUtilException {
157
		String moderatorString = null;
158
		try {
159
			moderatorString = 
160
				PropertyService.getProperty("auth.moderators");
161
		} catch (PropertyNotFoundException pnfe) {
162
			throw new MetacatUtilException("Could not get metacat property: auth.moderators. "
163
							+ "There will be no registered metacat moderators: "
164
							+ pnfe.getMessage());
165
		}
166
		moderators = StringUtil.toVector(moderatorString, ':');
167
	}
168

    
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
	public static boolean logUserIn(HttpServletRequest request, String userName, String password) throws MetacatUtilException {
176
		AuthSession authSession = null;
177

    
178
		// make sure we have username and password.
179
		if (userName == null || password == null) {
180
			throw new MetacatUtilException("null username or password when logging user in");
181
		}
182

    
183
		// Create auth session
184
		try {
185
			authSession = new AuthSession();
186
		} catch (Exception e) {
187
			throw new MetacatUtilException("Could not instantiate AuthSession: "
188
					+ e.getMessage());
189
		}
190
		// authenticate user against ldap
191
		if(!authSession.authenticate(request, userName,password)) {
192
			throw new MetacatUtilException(authSession.getMessage());
193
		}
194
		
195
		// if login was successful, add the session information to the
196
		// global session list.
197
		HttpSession session = authSession.getSessions();
198
		String sessionId = session.getId();
199
		
200
		try {
201
		SessionService.registerSession(sessionId, 
202
				(String) session.getAttribute("username"), 
203
				(String[]) session.getAttribute("groupnames"),
204
				(String) session.getAttribute("password"));
205
		} catch (ServiceException se) {
206
			throw new MetacatUtilException("Problem registering session: " + se.getMessage());
207
		}
208
		
209
		return true;
210
	}
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
	public static boolean isUserLoggedIn(HttpServletRequest request) throws MetacatUtilException{
220
		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
			throw new MetacatUtilException("Could not determine if user is logged in because " 
251
					+ "of property error: " + pnfe.getMessage());
252
		} catch (NumberFormatException nfe) {
253
			throw new MetacatUtilException("Could not determine if user is logged in because " 
254
					+ "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
	public static boolean isUserLoggedInAsAdmin(HttpServletRequest request) throws MetacatUtilException {
271
		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
			Vector<String> dnList) throws MetacatUtilException {
324

    
325
		if (username == null || organization == null || dnList == null || dnList.size() == 0) {
326
			throw new MetacatUtilException("Could not generate LDAP user string.  One of the following is null: username, organization or dnlist");
327
		}
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
	public static boolean isAuthConfigured() throws MetacatUtilException {
345
		String authConfiguredString = PropertyService.UNCONFIGURED;
346
		try {
347
			authConfiguredString = PropertyService.getProperty("configutil.authConfigured");
348
		} catch (PropertyNotFoundException pnfe) {
349
			throw new MetacatUtilException("Could not determine if LDAP is configured: "
350
					+ pnfe.getMessage());
351
		}
352
		return !authConfiguredString.equals(PropertyService.UNCONFIGURED);
353
	}
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
			throws MetacatUtilException {
365
		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
	public static boolean isModerator(String username, String[] groups) throws MetacatUtilException{
377
		return onAccessList(getModerators(), username, groups);
378
	}
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
			throws MetacatUtilException {
390
		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
			throws MetacatUtilException {
408
		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
			throws MetacatUtilException {
421
		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
					if (groups[j] != null && groups[j].equals(accessString)) {
450
						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
}
(1-1/12)