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-10-02 12:59:59 -0700 (Fri, 02 Oct 2009) $'
10
 * '$Revision: 5070 $'
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.properties.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
				(String) session.getAttribute("name"));
206
		} catch (ServiceException se) {
207
			throw new MetacatUtilException("Problem registering session: " + se.getMessage());
208
		}
209
		
210
		return true;
211
	}
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
	public static boolean isUserLoggedIn(HttpServletRequest request) throws MetacatUtilException{
221
		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
			throw new MetacatUtilException("Could not determine if user is logged in because " 
252
					+ "of property error: " + pnfe.getMessage());
253
		} catch (NumberFormatException nfe) {
254
			throw new MetacatUtilException("Could not determine if user is logged in because " 
255
					+ "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
	public static boolean isUserLoggedInAsAdmin(HttpServletRequest request) throws MetacatUtilException {
272
		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
			Vector<String> dnList) throws MetacatUtilException {
325

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