Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: An implementation of the AuthInterface interface that
4
 *             allows Metacat to use the LDAP protocol for
5
 *             directory services
6
 *  Copyright: 2000 Regents of the University of California and the
7
 *             National Center for Ecological Analysis and Synthesis
8
 *    Authors: Matt Jones
9
 *
10
 *   '$Author: berkley $'
11
 *     '$Date: 2010-10-27 10:51:00 -0700 (Wed, 27 Oct 2010) $'
12
 * '$Revision: 5629 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

    
31
import java.net.ConnectException;
32
import javax.naming.AuthenticationException;
33
import javax.naming.Context;
34
import javax.naming.NamingEnumeration;
35
import javax.naming.NamingException;
36
import javax.naming.SizeLimitExceededException;
37
import javax.naming.directory.Attribute;
38
import javax.naming.directory.Attributes;
39
import javax.naming.directory.DirContext;
40
import javax.naming.directory.InitialDirContext;
41
import javax.naming.directory.SearchResult;
42
import javax.naming.directory.SearchControls;
43
import javax.naming.ReferralException;
44
import javax.naming.ldap.InitialLdapContext;
45
import javax.naming.ldap.LdapContext;
46
import javax.naming.ldap.StartTlsRequest;
47
import javax.naming.ldap.StartTlsResponse;
48
import javax.net.ssl.SSLSession;
49

    
50
import org.apache.log4j.Logger;
51

    
52
import edu.ucsb.nceas.metacat.properties.PropertyService;
53
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
54

    
55
import java.io.IOException;
56
import java.lang.InstantiationException;
57
import java.net.URLDecoder;
58
import java.util.Iterator;
59
import java.util.HashMap;
60
import java.util.Hashtable;
61
import java.util.Enumeration;
62
import java.util.Set;
63
import java.util.Vector;
64

    
65
/**
66
 * An implementation of the AuthInterface interface that allows Metacat to use
67
 * the LDAP protocol for directory services. The LDAP authentication service is
68
 * used to determine if a user is authenticated, and whether they are a member
69
 * of a particular group.
70
 */
71
public class AuthLdap implements AuthInterface {
72
	private String ldapUrl;
73
	private String ldapsUrl;
74
	private String ldapBase;
75
	private String referral;
76
	private String ldapConnectTimeLimit;
77
	private int ldapSearchTimeLimit;
78
	private int ldapSearchCountLimit;
79
	private String currentReferralInfo;
80
	Hashtable<String, String> env = new Hashtable<String, String>(11);
81
	private Context rContext;
82
	private String userName;
83
	private String userPassword;
84
	ReferralException refExc;
85

    
86
	private static Logger logMetacat = Logger.getLogger(AuthLdap.class);
87

    
88
	/**
89
	 * Construct an AuthLdap
90
	 */
91
	public AuthLdap() throws InstantiationException {
92
		// Read LDAP URI for directory service information
93
		try {
94
			this.ldapUrl = PropertyService.getProperty("auth.url");
95
			this.ldapsUrl = PropertyService.getProperty("auth.surl");
96
			this.ldapBase = PropertyService.getProperty("auth.base");
97
			this.referral = PropertyService.getProperty("ldap.referral");
98
			this.ldapConnectTimeLimit = PropertyService
99
					.getProperty("ldap.connectTimeLimit");
100
			this.ldapSearchTimeLimit = Integer.parseInt(PropertyService
101
					.getProperty("ldap.searchTimeLimit"));
102
			this.ldapSearchCountLimit = Integer.parseInt(PropertyService
103
					.getProperty("ldap.searchCountLimit"));
104
		} catch (PropertyNotFoundException pnfe) {
105
			throw new InstantiationException(
106
					"Could not instantiate AuthLdap.  Property not found: "
107
							+ pnfe.getMessage());
108
		} catch (NumberFormatException nfe) {
109
			throw new InstantiationException(
110
					"Could not instantiate AuthLdap.  Bad number format when converting properties: "
111
							+ nfe.getMessage());
112
		}
113

    
114
		// Store referral info for use in building group DNs in getGroups()
115
		this.currentReferralInfo = "";
116
	}
117

    
118
	/**
119
	 * Determine if a user/password are valid according to the authentication
120
	 * service.
121
	 * 
122
	 * @param user
123
	 *            the name of the principal to authenticate
124
	 * @param password
125
	 *            the password to use for authentication
126
	 * @returns boolean true if authentication successful, false otherwise
127
	 */
128
	public boolean authenticate(String user, String password) throws ConnectException {
129
		String ldapUrl = this.ldapUrl;
130
		String ldapsUrl = this.ldapsUrl;
131
		String ldapBase = this.ldapBase;
132
		boolean authenticated = false;
133
		String identifier = user;
134

    
135
		// get uid here.
136
		if (user.indexOf(",") == -1) {
137
			throw new ConnectException("Invalid LDAP user credential: " + user
138
					+ ".  Missing ','");
139
		}
140
		String uid = user.substring(0, user.indexOf(","));
141
		user = user.substring(user.indexOf(","), user.length());
142

    
143
		logMetacat.debug("AuthLdap.authenticate - identifier: " + identifier + 
144
				", uid: " + uid +", user: " + user);
145

    
146
		try {
147
			// Check the usename as passed in
148
			logMetacat.info("AuthLdap.authenticate - Calling ldapAuthenticate" +
149
				" with user as identifier: " + identifier);
150

    
151
			authenticated = ldapAuthenticate(identifier, password, (new Boolean(
152
					PropertyService.getProperty("ldap.onlySecureConnection")))
153
					.booleanValue());
154
			// if not found, try looking up a valid DN then auth again
155
			if (!authenticated) {
156
				logMetacat.info("AuthLdap.authenticate - Not Authenticated");
157
				logMetacat.info("AuthLdap.authenticate - Looking up DN for: " + identifier);
158
				identifier = getIdentifyingName(identifier, ldapUrl, ldapBase);
159
				if (identifier == null) {
160
					logMetacat.info("AuthLdap.authenticate - No DN found from getIdentifyingName");
161
					return authenticated;
162
				}
163

    
164
				logMetacat.info("AuthLdap.authenticate - DN found from getIdentifyingName: " + identifier);
165
				String decoded = URLDecoder.decode(identifier);
166
				logMetacat.info("AuthLdap.authenticate - DN decoded: " + decoded);
167
				identifier = decoded;
168
				String refUrl = "";
169
				String refBase = "";
170
				if (identifier.startsWith("ldap")) {
171
					logMetacat.debug("AuthLdap.authenticate - identifier starts with \"ldap\"");
172

    
173
					refUrl = identifier.substring(0, identifier.lastIndexOf("/") + 1);
174
					int position = identifier.indexOf(",");
175
					int position2 = identifier.indexOf(",", position + 1);
176

    
177
					refBase = identifier.substring(position2 + 1);
178
					identifier = identifier.substring(identifier.lastIndexOf("/") + 1);
179

    
180
					logMetacat.info("AuthLdap.authenticate - Calling ldapAuthenticate: " +
181
						"with user as identifier: " + identifier + " and refUrl as: " + 
182
						refUrl + " and refBase as: " + refBase);
183

    
184
					authenticated = ldapAuthenticate(identifier, password, refUrl,
185
							refBase, (new Boolean(PropertyService
186
									.getProperty("ldap.onlySecureReferalsConnection")))
187
									.booleanValue());
188
				} else {
189
					logMetacat.info("AuthLdap.authenticate - identifier doesnt start with ldap");
190
					identifier = identifier + "," + ldapBase;
191

    
192
					logMetacat.info("AuthLdap.authenticate - Calling ldapAuthenticate" + 
193
							"with user as identifier: " + identifier);
194

    
195
					authenticated = ldapAuthenticate(identifier, password, (new Boolean(
196
							PropertyService.getProperty("ldap.onlySecureConnection")))
197
							.booleanValue());
198
				}
199
			}
200
		} catch (NullPointerException npe) {
201
			logMetacat.error("AuthLdap.authenticate - NullPointerException while authenticating in "
202
					+ "AuthLdap.authenticate: " + npe);
203
			npe.printStackTrace();
204

    
205
			throw new ConnectException("AuthLdap.authenticate - NullPointerException while authenticating in "
206
					+ "AuthLdap.authenticate: " + npe);
207
		} catch (NamingException ne) {
208
			logMetacat.error("AuthLdap.authenticate - Naming exception while authenticating in "
209
					+ "AuthLdap.authenticate: " + ne);
210
			ne.printStackTrace();
211
		} catch (PropertyNotFoundException pnfe) {
212
			logMetacat.error("AuthLdap.authenticate - Property exception while authenticating in "
213
					+ "AuthLdap.authenticate: " + pnfe.getMessage());
214
		}
215

    
216
		return authenticated;
217
	}
218

    
219
	/**
220
	 * Connect to the LDAP directory and do the authentication using the
221
	 * username and password as passed into the routine.
222
	 * 
223
	 * @param identifier
224
	 *            the distinguished name to check against LDAP
225
	 * @param password
226
	 *            the password for authentication
227
	 */
228
	private boolean ldapAuthenticate(String identifier, String password,
229
			boolean secureConnectionOnly) throws ConnectException, NamingException,
230
			NullPointerException {
231
		return ldapAuthenticate(identifier, password, this.ldapsUrl, this.ldapBase,
232
				secureConnectionOnly);
233
	}
234

    
235
	/**
236
	 * Connect to the LDAP directory and do the authentication using the
237
	 * username and password as passed into the routine.
238
	 * 
239
	 * @param identifier
240
	 *            the distinguished name to check against LDAP
241
	 * @param password
242
	 *            the password for authentication
243
	 */
244

    
245
	private boolean ldapAuthenticate(String dn, String password, String rootServer,
246
			String rootBase, boolean secureConnectionOnly) {
247

    
248
		boolean authenticated = false;
249

    
250
		String server = "";
251
		String userDN = "";
252
		logMetacat.info("AuthLdap.ldapAuthenticate - dn is: " + dn);
253

    
254
		int position = dn.lastIndexOf("/");
255
		logMetacat.debug("AuthLdap.ldapAuthenticate - position is: " + position);
256
		if (position == -1) {
257
			server = rootServer;
258
			if (dn.indexOf(userDN) < 0) {
259
				userDN = dn + "," + rootBase;
260
			} else {
261
				userDN = dn;
262
			}
263
			logMetacat.info("AuthLdap.ldapAuthenticate - userDN is: " + userDN);
264

    
265
		} else {
266
			server = dn.substring(0, position + 1);
267
			userDN = dn.substring(position + 1);
268
			logMetacat.info("AuthLdap.ldapAuthenticate - server is: " + server);
269
			logMetacat.info("AuthLdap.ldapAuthenticate - userDN is: " + userDN);
270
		}
271

    
272
		logMetacat.warn("AuthLdap.ldapAuthenticate - Trying to authenticate: " + 
273
				userDN + " Using server: " + server);
274

    
275
		try {
276
			Hashtable<String, String> env = new Hashtable<String, String>();
277
			env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
278
			env.put(Context.PROVIDER_URL, server);
279
			env.put(Context.REFERRAL, "throw");
280
			
281
			try {
282
				authenticated = authenticateTLS(env, userDN, password);
283
			} catch (AuthTLSException ate) {
284
				logMetacat.info("AuthLdap.ldapAuthenticate - error while negotiating TLS: "
285
						+ ate.getMessage());
286

    
287
				if (secureConnectionOnly) {
288
					return authenticated;
289

    
290
				} else {
291
					authenticated = authenticateNonTLS(env, userDN, password);
292
				}
293
			}
294
		} catch (AuthenticationException ae) {
295
			logMetacat.warn("Authentication exception: " + ae.getMessage());
296
			authenticated = false;
297
		} catch (javax.naming.InvalidNameException ine) {
298
			logMetacat.error("AuthLdap.ldapAuthenticate - An invalid DN was provided: " + ine.getMessage());
299
		} catch (NamingException ne) {
300
			logMetacat.warn("AuthLdap.ldapAuthenticate - Caught NamingException in login: " + ne.getClass().getName());
301
			logMetacat.info(ne.toString() + "  " + ne.getRootCause());
302
		}
303

    
304
		return authenticated;
305
	}
306
	
307
	private boolean authenticateTLS(Hashtable<String, String> env, String userDN, String password)
308
			throws AuthTLSException{	
309
		logMetacat.info("AuthLdap.authenticateTLS - Trying to authenticate with TLS");
310
		try {
311
			LdapContext ctx = null;
312
			double startTime;
313
			double stopTime;
314
			startTime = System.currentTimeMillis();
315
			ctx = new InitialLdapContext(env, null);
316
			// Start up TLS here so that we don't pass our jewels in
317
			// cleartext
318
			StartTlsResponse tls = 
319
				(StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
320
			// tls.setHostnameVerifier(new SampleVerifier());
321
			SSLSession sess = tls.negotiate();
322
			ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
323
			ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
324
			ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
325
			ctx.reconnect(null);
326
			stopTime = System.currentTimeMillis();
327
			logMetacat.info("AuthLdap.authenticateTLS - Connection time thru "
328
					+ ldapsUrl + " was: " + (stopTime - startTime) / 1000 + " seconds.");
329
		} catch (NamingException ne) {
330
			throw new AuthTLSException("AuthLdap.authenticateTLS - Naming error when athenticating via TLS: " + ne.getMessage());
331
		} catch (IOException ioe) {
332
			throw new AuthTLSException("AuthLdap.authenticateTLS - I/O error when athenticating via TLS: " + ioe.getMessage());
333
		}
334
		return true;
335
	}
336
	
337
	private boolean authenticateNonTLS(Hashtable<String, String> env, String userDN, String password) 
338
			throws NamingException {
339
		LdapContext ctx = null;
340
		double startTime;
341
		double stopTime;
342
		
343
		logMetacat.info("AuthLdap.authenticateNonTLS - Trying to authenticate without TLS");
344
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
345
		env.put(Context.SECURITY_PRINCIPAL, userDN);
346
		env.put(Context.SECURITY_CREDENTIALS, password);
347

    
348
		startTime = System.currentTimeMillis();
349
		ctx = new InitialLdapContext(env, null);
350
		stopTime = System.currentTimeMillis();
351
		logMetacat.info("AuthLdap.authenticateNonTLS - Connection time thru " + ldapsUrl + " was: "
352
				+ (stopTime - startTime) / 1000 + " seconds.");
353

    
354
		return true;
355
	}
356

    
357
	/**
358
	 * Get the identifying name for a given userid or name. This is the name
359
	 * that is used in conjunction withthe LDAP BaseDN to create a distinguished
360
	 * name (dn) for the record
361
	 * 
362
	 * @param user
363
	 *            the user for which the identifying name is requested
364
	 * @returns String the identifying name for the user, or null if not found
365
	 */
366
	private String getIdentifyingName(String user, String ldapUrl, String ldapBase)
367
			throws NamingException {
368

    
369
		String identifier = null;
370
		Hashtable env = new Hashtable();
371
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
372
		env.put(Context.REFERRAL, "throw");
373
		env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
374
		try {
375
			int position = user.indexOf(",");
376
			String uid = user.substring(user.indexOf("=") + 1, position);
377
			logMetacat.info("AuthLdap.getIdentifyingName - uid is: " + uid);
378
			String org = user.substring(user.indexOf("=", position + 1) + 1, user
379
					.indexOf(",", position + 1));
380
			logMetacat.info("AuthLdap.getIdentifyingName - org is: " + org);
381

    
382
			DirContext sctx = new InitialDirContext(env);
383
			SearchControls ctls = new SearchControls();
384
			ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
385
			String filter = "(&(uid=" + uid + ")(o=" + org + "))";
386
			logMetacat.warn("AuthLdap.getIdentifyingName - Searching for DNs with following filter: " + filter);
387

    
388
			for (boolean moreReferrals = true; moreReferrals;) {
389
				try {
390
					// Perform the search
391
				    
392
					NamingEnumeration answer = sctx.search("", filter, ctls);
393

    
394
					// Return the answer
395
					while (answer.hasMore()) {
396
						SearchResult sr = (SearchResult) answer.next();
397
						identifier = sr.getName();
398
						return identifier;
399
					}
400
					// The search completes with no more referrals
401
					moreReferrals = false;
402
				} catch (ReferralException e) {
403
					logMetacat.info("AuthLdap.getIdentifyingName - Got referral: " + e.getReferralInfo());
404
					// Point to the new context from the referral
405
					if (moreReferrals) {
406
						// try following referral, skip if error
407
						boolean referralError = true;
408
						while (referralError) {
409
							try {
410
								sctx = (DirContext) e.getReferralContext();
411
								referralError = false;
412
							}
413
							catch (NamingException ne) {
414
								logMetacat.error("NamingException when getting referral contex. Skipping this referral. " + ne.getMessage());
415
								e.skipReferral();
416
								referralError = true;
417
							}
418
						}
419
					}
420
				}				
421
			}
422
		} catch (NamingException e) {
423
			logMetacat.error("AuthLdap.getIdentifyingName - Naming exception while getting dn: " + e);
424
			throw new NamingException("Naming exception in AuthLdap.getIdentifyingName: "
425
					+ e);
426
		}
427
		return identifier;
428
	}
429

    
430
	/**
431
	 * Get all users from the authentication service
432
	 * 
433
	 * @param user
434
	 *            the user for authenticating against the service
435
	 * @param password
436
	 *            the password for authenticating against the service
437
	 * @returns string array of all of the user names
438
	 */
439
	public String[][] getUsers(String user, String password) throws ConnectException {
440
		String[][] users = null;
441

    
442
		// Identify service provider to use
443
		Hashtable env = new Hashtable(11);
444
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
445
		env.put(Context.REFERRAL, referral);
446
		env.put(Context.PROVIDER_URL, ldapUrl);
447
		env.put("com.sun.jndi.ldap.connect.timeout", ldapConnectTimeLimit);
448

    
449
		try {
450

    
451
			// Create the initial directory context
452
			DirContext ctx = new InitialDirContext(env);
453

    
454
			// Specify the attributes to match.
455
			// Users are objects that have the attribute
456
			// objectclass=InetOrgPerson.
457
			SearchControls ctls = new SearchControls();
458
			String[] attrIDs = { "dn", "cn", "o", "ou", "mail" };
459
			ctls.setReturningAttributes(attrIDs);
460
			ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
461
			ctls.setTimeLimit(ldapSearchTimeLimit);
462
			// ctls.setCountLimit(1000);
463
			String filter = "(objectClass=inetOrgPerson)";
464
			NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
465

    
466
			// Store the users in a vector
467
			Vector uvec = new Vector();
468
			Vector uname = new Vector();
469
			Vector uorg = new Vector();
470
			Vector uou = new Vector();
471
			Vector umail = new Vector();
472
			Attributes tempAttr = null;
473
			try {
474
				while (namingEnum.hasMore()) {
475
					SearchResult sr = (SearchResult) namingEnum.next();
476
					tempAttr = sr.getAttributes();
477

    
478
					if ((tempAttr.get("cn") + "").startsWith("cn: ")) {
479
						uname.add((tempAttr.get("cn") + "").substring(4));
480
					} else {
481
						uname.add(tempAttr.get("cn") + "");
482
					}
483

    
484
					if ((tempAttr.get("o") + "").startsWith("o: ")) {
485
						uorg.add((tempAttr.get("o") + "").substring(3));
486
					} else {
487
						uorg.add(tempAttr.get("o") + "");
488
					}
489

    
490
					if ((tempAttr.get("ou") + "").startsWith("ou: ")) {
491
						uou.add((tempAttr.get("ou") + "").substring(4));
492
					} else {
493
						uou.add(tempAttr.get("ou") + "");
494
					}
495

    
496
					if ((tempAttr.get("mail") + "").startsWith("mail: ")) {
497
						umail.add((tempAttr.get("mail") + "").substring(6));
498
					} else {
499
						umail.add(tempAttr.get("mail") + "");
500
					}
501

    
502
					uvec.add(sr.getName() + "," + ldapBase);
503
				}
504
			} catch (SizeLimitExceededException slee) {
505
				logMetacat.error("AuthLdap.getUsers - LDAP Server size limit exceeded. "
506
						+ "Returning incomplete record set.");
507
			}
508

    
509
			// initialize users[]; fill users[]
510
			users = new String[uvec.size()][5];
511
			for (int i = 0; i < uvec.size(); i++) {
512
				users[i][0] = (String) uvec.elementAt(i);
513
				users[i][1] = (String) uname.elementAt(i);
514
				users[i][2] = (String) uorg.elementAt(i);
515
				users[i][3] = (String) uorg.elementAt(i);
516
				users[i][4] = (String) umail.elementAt(i);
517
			}
518

    
519
			// Close the context when we're done
520
			ctx.close();
521

    
522
		} catch (NamingException e) {
523
			logMetacat.error("AuthLdap.getUsers - Problem getting users in AuthLdap.getUsers:" + e);
524
			// e.printStackTrace(System.err);
525
			/*
526
			 * throw new ConnectException( "Problem getting users in
527
			 * AuthLdap.getUsers:" + e);
528
			 */
529
		}
530

    
531
		return users;
532
	}
533

    
534
	/**
535
	 * Get all users from the authentication service
536
	 * 
537
	 * @param user
538
	 *            the user for authenticating against the service
539
	 * @param password
540
	 *            the password for authenticating against the service
541
	 * @returns string array of all of the user names
542
	 */
543
	public String[] getUserInfo(String user, String password) throws ConnectException {
544
		String[] userinfo = new String[3];
545

    
546
		// Identify service provider to use
547
		Hashtable env = new Hashtable(11);
548
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
549
		env.put(Context.REFERRAL, referral);
550
		env.put(Context.PROVIDER_URL, ldapUrl);
551

    
552
		try {
553

    
554
			// Create the initial directory context
555
			DirContext ctx = new InitialDirContext(env);
556
			// Specify the attributes to match.
557
			// Users are objects that have the attribute
558
			// objectclass=InetOrgPerson.
559
			SearchControls ctls = new SearchControls();
560
			String[] attrIDs = { "cn", "o", "mail" };
561
			ctls.setReturningAttributes(attrIDs);
562
			ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
563
			// ctls.setCountLimit(1000);
564
			// create the filter based on the uid
565

    
566
			String filter = null;
567

    
568
			if (user.indexOf("o=") > 0) {
569
				String tempStr = user.substring(user.indexOf("o="));
570
				filter = "(&(" + user.substring(0, user.indexOf(",")) + ")("
571
						+ tempStr.substring(0, tempStr.indexOf(",")) + "))";
572
			} else {
573
				filter = "(&(" + user.substring(0, user.indexOf(",")) + "))";
574
			}
575
			filter = "(&(" + user.substring(0, user.indexOf(",")) + "))";
576

    
577
			NamingEnumeration namingEnum = ctx.search(user, filter, ctls);
578

    
579
			Attributes tempAttr = null;
580
			try {
581
				while (namingEnum.hasMore()) {
582
					SearchResult sr = (SearchResult) namingEnum.next();
583
					tempAttr = sr.getAttributes();
584

    
585
					if ((tempAttr.get("cn") + "").startsWith("cn: ")) {
586
						userinfo[0] = (tempAttr.get("cn") + "").substring(4);
587
					} else {
588
						userinfo[0] = (tempAttr.get("cn") + "");
589
					}
590

    
591
					if ((tempAttr.get("o") + "").startsWith("o: ")) {
592
						userinfo[1] = (tempAttr.get("o") + "").substring(3);
593
					} else {
594
						userinfo[1] = (tempAttr.get("o") + "");
595
					}
596

    
597
					if ((tempAttr.get("mail") + "").startsWith("mail: ")) {
598
						userinfo[2] = (tempAttr.get("mail") + "").substring(6);
599
					} else {
600
						userinfo[2] = (tempAttr.get("mail") + "");
601
					}
602
				}
603
			} catch (SizeLimitExceededException slee) {
604
				logMetacat.error("AuthLdap.getUserInfo - LDAP Server size limit exceeded. "
605
						+ "Returning incomplete record set.");
606
			}
607

    
608
			// Close the context when we're done
609
			ctx.close();
610

    
611
		} catch (NamingException e) {
612
			logMetacat.error("AuthLdap.getUserInfo - Problem getting users:" + e);
613
			// e.printStackTrace(System.err);
614
			throw new ConnectException("Problem getting users in AuthLdap.getUsers:" + e);
615
		}
616

    
617
		return userinfo;
618
	}
619

    
620
	/**
621
	 * Get the users for a particular group from the authentication service
622
	 * 
623
	 * @param user
624
	 *            the user for authenticating against the service
625
	 * @param password
626
	 *            the password for authenticating against the service
627
	 * @param group
628
	 *            the group whose user list should be returned
629
	 * @returns string array of the user names belonging to the group
630
	 */
631
	public String[] getUsers(String user, String password, String group)
632
			throws ConnectException {
633
		String[] users = null;
634

    
635
		// Identify service provider to use
636
		Hashtable env = new Hashtable(11);
637
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
638
		env.put(Context.REFERRAL, referral);
639
		env.put(Context.PROVIDER_URL, ldapUrl);
640

    
641
		try {
642

    
643
			// Create the initial directory context
644
			DirContext ctx = new InitialDirContext(env);
645

    
646
			// Specify the ids of the attributes to return
647
			String[] attrIDs = { "uniqueMember" };
648

    
649
			Attributes answer = ctx.getAttributes(group, attrIDs);
650

    
651
			Vector uvec = new Vector();
652
			try {
653
				for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
654
					Attribute attr = (Attribute) ae.next();
655
					for (NamingEnumeration e = attr.getAll(); e.hasMore(); uvec.add(e
656
							.next())) {
657
						;
658
					}
659
				}
660
			} catch (SizeLimitExceededException slee) {
661
				logMetacat.error("AuthLdap.getUsers - LDAP Server size limit exceeded. "
662
						+ "Returning incomplete record set.");
663
			}
664

    
665
			// initialize users[]; fill users[]
666
			users = new String[uvec.size()];
667
			for (int i = 0; i < uvec.size(); i++) {
668
				users[i] = (String) uvec.elementAt(i);
669
			}
670

    
671
			// Close the context when we're done
672
			ctx.close();
673

    
674
		} catch (NamingException e) {
675
			logMetacat.error("AuthLdap.getUsers - Problem getting users for a group in "
676
					+ "AuthLdap.getUsers:" + e);
677
			/*
678
			 * throw new ConnectException( "Problem getting users for a group in
679
			 * AuthLdap.getUsers:" + e);
680
			 */
681
		}
682

    
683
		return users;
684
	}
685

    
686
	/**
687
	 * Get all groups from the authentication service
688
	 * 
689
	 * @param user
690
	 *            the user for authenticating against the service
691
	 * @param password
692
	 *            the password for authenticating against the service
693
	 * @returns string array of the group names
694
	 */
695
	public String[][] getGroups(String user, String password) throws ConnectException {
696
		return getGroups(user, password, null);
697
	}
698

    
699
	/**
700
	 * Get the groups for a particular user from the authentication service
701
	 * 
702
	 * @param user
703
	 *            the user for authenticating against the service
704
	 * @param password
705
	 *            the password for authenticating against the service
706
	 * @param foruser
707
	 *            the user whose group list should be returned
708
	 * @returns string array of the group names
709
	 */
710
	public String[][] getGroups(String user, String password, String foruser)
711
			throws ConnectException {
712

    
713
		logMetacat.debug("AuthLdap.getGroups - getGroups() called.");
714

    
715
		// create vectors to store group and dscription values returned from the
716
		// ldap servers
717
		Vector gvec = new Vector();
718
		Vector desc = new Vector();
719
		Attributes tempAttr = null;
720
		Attributes rsrAttr = null;
721

    
722
		// DURING getGroups(), DO WE NOT BIND USING userName AND userPassword??
723
		// NEED TO FIX THIS ...
724
		userName = user;
725
		userPassword = password;
726
		// Identify service provider to use
727
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
728
		env.put(Context.REFERRAL, "throw");
729
		env.put(Context.PROVIDER_URL, ldapUrl);
730
		env.put("com.sun.jndi.ldap.connect.timeout", ldapConnectTimeLimit);
731

    
732
		// Iterate through the referrals, handling NamingExceptions in the
733
		// outer catch statement, ReferralExceptions in the inner catch
734
		// statement
735
		try { // outer try
736

    
737
			// Create the initial directory context
738
			DirContext ctx = new InitialDirContext(env);
739

    
740
			// Specify the attributes to match.
741
			// Groups are objects with attribute objectclass=groupofuniquenames.
742
			// and have attribute uniquemember: uid=foruser,ldapbase.
743
			SearchControls ctls = new SearchControls();
744
			// Specify the ids of the attributes to return
745
			String[] attrIDs = { "cn", "o", "description" };
746
			ctls.setReturningAttributes(attrIDs);
747
			// set the ldap search scope
748
			ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
749
			// set a 10 second time limit on searches to limit non-responding
750
			// servers
751
			ctls.setTimeLimit(ldapSearchTimeLimit);
752
			// return at most 20000 entries
753
			ctls.setCountLimit(ldapSearchCountLimit);
754

    
755
			// build the ldap search filter that represents the "group" concept
756
			String filter = null;
757
			String gfilter = "(objectClass=groupOfUniqueNames)";
758
			if (null == foruser) {
759
				filter = gfilter;
760
			} else {
761
				filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
762
			}
763
			logMetacat.info("AuthLdap.getGroups - group filter is: " + filter);
764

    
765
			// now, search and iterate through the referrals
766
			for (boolean moreReferrals = true; moreReferrals;) {
767
				try { // inner try
768

    
769
					NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
770

    
771
					// Print the groups
772
					while (namingEnum.hasMore()) {
773
						SearchResult sr = (SearchResult) namingEnum.next();
774

    
775
						tempAttr = sr.getAttributes();
776

    
777
						if ((tempAttr.get("description") + "")
778
								.startsWith("description: ")) {
779
							desc.add((tempAttr.get("description") + "").substring(13));
780
						} else {
781
							desc.add(tempAttr.get("description") + "");
782
						}
783

    
784
						// check for an absolute URL value or an answer value
785
						// relative
786
						// to the target context
787
						if (!sr.getName().startsWith("ldap") && sr.isRelative()) {
788
							logMetacat.debug("AuthLdap.getGroups - Search result entry is relative ...");
789
							gvec.add(sr.getName() + "," + ldapBase);
790
							logMetacat.info("AuthLdap.getGroups - group " + sr.getName() + "," + ldapBase
791
									+ " added to the group vector");
792
						} else {
793
							logMetacat.debug("AuthLdap.getGroups - Search result entry is absolute ...");
794

    
795
							// search the top level directory for referral
796
							// objects and match
797
							// that of the search result's absolute URL. This
798
							// will let us
799
							// rebuild the group name from the search result,
800
							// referral point
801
							// in the top directory tree, and ldapBase.
802

    
803
							// configure a new directory search first
804
							Hashtable envHash = new Hashtable(11);
805
							// Identify service provider to use
806
							envHash.put(Context.INITIAL_CONTEXT_FACTORY,
807
									"com.sun.jndi.ldap.LdapCtxFactory");
808
							envHash.put(Context.REFERRAL, "ignore");
809
							envHash.put(Context.PROVIDER_URL, ldapUrl);
810
							envHash.put("com.sun.jndi.ldap.connect.timeout",
811
									ldapConnectTimeLimit);
812

    
813
							try {
814
								// Create the initial directory context
815
								DirContext DirCtx = new InitialDirContext(envHash);
816

    
817
								SearchControls searchCtls = new SearchControls();
818
								// Specify the ids of the attributes to return
819
								String[] attrNames = { "o" };
820
								searchCtls.setReturningAttributes(attrNames);
821
								// set the ldap search scope - only look for top
822
								// level referrals
823
								searchCtls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
824
								// set a time limit on searches to limit
825
								// non-responding servers
826
								searchCtls.setTimeLimit(ldapSearchTimeLimit);
827
								// return the configured number of entries
828
								searchCtls.setCountLimit(ldapSearchCountLimit);
829

    
830
								// Specify the attributes to match.
831
								// build the ldap search filter to match
832
								// referral entries that
833
								// match the search result
834
								String rFilter = "(&(objectClass=referral)(ref="
835
										+ currentReferralInfo.substring(0,
836
												currentReferralInfo.indexOf("?")) + "))";
837
								logMetacat.debug("AuthLdap.getGroups - rFilter is: " + rFilter);
838

    
839
								NamingEnumeration rNamingEnum = DirCtx.search(ldapBase,
840
										rFilter, searchCtls);
841

    
842
								while (rNamingEnum.hasMore()) {
843
									SearchResult rsr = (SearchResult) rNamingEnum.next();
844
									rsrAttr = rsr.getAttributes();
845
									logMetacat.debug("AuthLdap.getGroups - referral search result is: "
846
											+ rsr.toString());
847

    
848
									// add the returned groups to the group
849
									// vector. Test the
850
									// syntax of the returned attributes -
851
									// sometimes they are
852
									// preceded with the attribute id and a
853
									// colon
854
									if ((tempAttr.get("cn") + "").startsWith("cn: ")) {
855
										gvec.add("cn="
856
												+ (tempAttr.get("cn") + "").substring(4)
857
												+ "," + "o="
858
												+ (rsrAttr.get("o") + "").substring(3)
859
												+ "," + ldapBase);
860
										logMetacat.info("AuthLdap.getGroups - group "
861
												+ (tempAttr.get("cn") + "").substring(4)
862
												+ "," + "o="
863
												+ (rsrAttr.get("o") + "").substring(3)
864
												+ "," + ldapBase
865
												+ " added to the group vector");
866
									} else {
867
										gvec.add("cn=" + tempAttr.get("cn") + "," + "o="
868
												+ rsrAttr.get("o") + "," + ldapBase);
869
										logMetacat.info("AuthLdap.getGroups - group " + "cn="
870
												+ tempAttr.get("cn") + "," + "o="
871
												+ rsrAttr.get("o") + "," + ldapBase
872
												+ " added to the group vector");
873
									}
874
								}
875

    
876
							} catch (NamingException nameEx) {
877
								logMetacat.debug("AuthLdap.getGroups - Caught naming exception: ");
878
								nameEx.printStackTrace(System.err);
879
							}
880
						}
881
					}// end while
882

    
883
					moreReferrals = false;
884

    
885
				} catch (ReferralException re) {
886

    
887
					logMetacat
888
							.info("AuthLdap.getGroups -  caught referral exception: "
889
									+ re.getReferralInfo());
890
					this.currentReferralInfo = (String) re.getReferralInfo();
891

    
892
					// set moreReferrals to true and set the referral context
893
					moreReferrals = true;
894
					
895
					// try following referral, skip if error
896
					boolean referralError = true;
897
					while (referralError) {
898
						try {
899
							ctx = (DirContext) re.getReferralContext();
900
							referralError = false;
901
						}
902
						catch (NamingException ne) {
903
							logMetacat.error("NamingException when getting referral contex. Skipping this referral. " + ne.getMessage());
904
							re.skipReferral();
905
							referralError = true;
906
						}
907
					}
908

    
909
				}// end inner try
910
			}// end for
911

    
912
			// close the context now that all initial and referral
913
			// searches are processed
914
			ctx.close();
915

    
916
		} catch (NamingException e) {
917

    
918
			// naming exceptions get logged, groups are returned
919
			logMetacat.info("AuthLdap.getGroups - caught naming exception: ");
920
			e.printStackTrace(System.err);
921

    
922
		} finally {
923
			// once all referrals are followed, report and return the groups
924
			// found
925
			logMetacat.warn("AuthLdap.getGroups - The user is in the following groups: " + gvec.toString());
926
			// build and return the groups array
927
			String groups[][] = new String[gvec.size()][2];
928
			for (int i = 0; i < gvec.size(); i++) {
929
				groups[i][0] = (String) gvec.elementAt(i);
930
				groups[i][1] = (String) desc.elementAt(i);
931
			}
932
			return groups;
933
		}// end outer try
934
	}
935

    
936
	/**
937
	 * Get attributes describing a user or group
938
	 * 
939
	 * @param foruser
940
	 *            the user for which the attribute list is requested
941
	 * @returns HashMap a map of attribute name to a Vector of values
942
	 */
943
	public HashMap<String, Vector<String>> getAttributes(String foruser)
944
			throws ConnectException {
945
		return getAttributes(null, null, foruser);
946
	}
947

    
948
	/**
949
	 * Get attributes describing a user or group
950
	 * 
951
	 * @param user
952
	 *            the user for authenticating against the service
953
	 * @param password
954
	 *            the password for authenticating against the service
955
	 * @param foruser
956
	 *            the user whose attributes should be returned
957
	 * @returns HashMap a map of attribute name to a Vector of values
958
	 */
959
	public HashMap<String, Vector<String>> getAttributes(String user, String password,
960
			String foruser) throws ConnectException {
961
		HashMap<String, Vector<String>> attributes = new HashMap<String, Vector<String>>();
962
		String ldapUrl = this.ldapUrl;
963
		String ldapBase = this.ldapBase;
964
		String userident = foruser;
965

    
966
		// Identify service provider to use
967
		Hashtable env = new Hashtable(11);
968
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
969
		env.put(Context.REFERRAL, referral);
970
		env.put(Context.PROVIDER_URL, ldapUrl);
971

    
972
		try {
973

    
974
			// Create the initial directory context
975
			DirContext ctx = new InitialDirContext(env);
976

    
977
			// Ask for all attributes of the user
978
			// Attributes attrs = ctx.getAttributes(userident);
979
			Attributes attrs = ctx.getAttributes(foruser);
980

    
981
			// Print all of the attributes
982
			NamingEnumeration en = attrs.getAll();
983
			while (en.hasMore()) {
984
				Attribute att = (Attribute) en.next();
985
				Vector<String> values = new Vector();
986
				String attName = att.getID();
987
				NamingEnumeration attvalues = att.getAll();
988
				while (attvalues.hasMore()) {
989
					String value = (String) attvalues.next();
990
					values.add(value);
991
				}
992
				attributes.put(attName, values);
993
			}
994

    
995
			// Close the context when we're done
996
			ctx.close();
997
		} catch (NamingException e) {
998
			logMetacat.error("AuthLdap.getAttributes - Problem getting attributes:"
999
					+ e);
1000
			throw new ConnectException(
1001
					"Problem getting attributes in AuthLdap.getAttributes:" + e);
1002
		}
1003

    
1004
		return attributes;
1005
	}
1006

    
1007
	/**
1008
	 * Get list of all subtrees holding Metacat's groups and users starting from
1009
	 * the Metacat LDAP root, i.e.
1010
	 * ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
1011
	 */
1012
	private Hashtable getSubtrees(String user, String password, String ldapUrl,
1013
			String ldapBase) throws ConnectException {
1014
		logMetacat.debug("AuthLdap.getSubtrees - getting subtrees for user: " + user + 
1015
				", ldapUrl: " + ldapUrl + ", ldapBase: " + ldapBase);
1016
		Hashtable trees = new Hashtable();
1017

    
1018
		// Identify service provider to use
1019
		Hashtable env = new Hashtable(11);
1020
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
1021
		// env.put(Context.REFERRAL, referral);
1022
		// Using 'ignore' here instead of 'follow' as 'ignore' seems
1023
		// to do the job better. 'follow' was not bringing up the UCNRS
1024
		// and PISCO tree whereas 'ignore' brings up the tree.
1025

    
1026
		env.put(Context.REFERRAL, "ignore");
1027
		env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
1028

    
1029
		try {
1030

    
1031
			// Create the initial directory context
1032
			DirContext ctx = new InitialDirContext(env);
1033

    
1034
			// Specify the ids of the attributes to return
1035
			String[] attrIDs = { "o", "ref" };
1036
			SearchControls ctls = new SearchControls();
1037
			ctls.setReturningAttributes(attrIDs);
1038
			ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
1039

    
1040
			// Specify the attributes to match.
1041
			// Subtrees from the main server are found as objects with attribute
1042
			// objectclass=organization or objectclass=referral to the subtree
1043
			// resided on other server.
1044
			String filter = "(|(objectclass=organization)(objectclass=referral))";
1045

    
1046
			// Search for objects in the current context
1047
			NamingEnumeration namingEnum = ctx.search("", filter, ctls);
1048

    
1049
			// Print the subtrees' <ldapURL, baseDN>
1050
			while (namingEnum.hasMore()) {
1051

    
1052
				SearchResult sr = (SearchResult) namingEnum.next();
1053
				logMetacat.debug("AuthLdap.getSubtrees - search result: " + sr.toString());
1054

    
1055
				Attributes attrs = sr.getAttributes();
1056
				NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref"
1057
															// attrs
1058

    
1059
				if (enum1.hasMore()) {
1060
					Attribute attr = (Attribute) enum1.next();
1061
					String attrValue = (String) attr.get();
1062
					String attrName = (String) attr.getID();
1063

    
1064
					if (enum1.hasMore()) {
1065
						attr = (Attribute) enum1.next();
1066
						String refValue = (String) attr.get();
1067
						String refName = (String) attr.getID();
1068
						if (ldapBase.startsWith(refName + "=" + refValue)) {
1069
							trees.put(ldapBase, attrValue.substring(0, attrValue
1070
									.lastIndexOf("/") + 1));
1071
						} else {
1072
							// this is a referral - so organization name is
1073
							// appended in front of the ldapbase.... later it is 
1074
							// stripped out in getPrincipals
1075
							trees.put("[" + refName + "=" + refValue + "]" + 
1076
									attrValue.substring(attrValue.lastIndexOf("/") + 1,
1077
											attrValue.length()), attrValue.substring(0,
1078
													attrValue.lastIndexOf("/") + 1));
1079

    
1080
							// trees.put(refName + "=" + refValue + "," +
1081
							// ldapBase, attrValue.substring(0, attrValue.lastIndexOf("/")
1082
							// + 1));
1083
						}
1084

    
1085
					} else if (ldapBase.startsWith(attrName + "=" + attrValue)) {
1086
						trees.put(ldapBase, ldapUrl);
1087
					} else {
1088
						if (sr.isRelative()) {
1089
							trees.put(attrName + "=" + attrValue + "," + ldapBase,
1090
									ldapUrl);
1091
						} else {
1092
							String referenceURL = sr.getName();
1093
							referenceURL = referenceURL.substring(0, referenceURL
1094
									.lastIndexOf("/") + 1);
1095
							trees.put(attrName + "=" + attrValue + "," + ldapBase,
1096
									referenceURL);
1097
						}
1098

    
1099
					}
1100
				}
1101
			}
1102

    
1103
			// Close the context when we're done
1104
			ctx.close();
1105

    
1106
		} catch (NamingException e) {
1107
			logMetacat.error("AuthLdap.getSubtrees - Problem getting subtrees in AuthLdap.getSubtrees:" + e);
1108
			throw new ConnectException(
1109
					"Problem getting subtrees in AuthLdap.getSubtrees:" + e);
1110
		}
1111

    
1112
		return trees;
1113
	}
1114

    
1115
	/**
1116
	 * Get all groups and users from authentication scheme. The output is
1117
	 * formatted in XML.
1118
	 * 
1119
	 * @param user
1120
	 *            the user which requests the information
1121
	 * @param password
1122
	 *            the user's password
1123
	 */
1124
	public String getPrincipals(String user, String password) throws ConnectException {
1125
		StringBuffer out = new StringBuffer();
1126

    
1127
		out.append("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n");
1128
		out.append("<principals>\n");
1129

    
1130
		/*
1131
		 * get all subtrees first in the current dir context and then the
1132
		 * Metacat users under them
1133
		 */
1134
		Hashtable subtrees = getSubtrees(user, password, this.ldapUrl, this.ldapBase);
1135

    
1136
		Enumeration keyEnum = subtrees.keys();
1137
		while (keyEnum.hasMoreElements()) {
1138
			this.ldapBase = (String) keyEnum.nextElement();
1139
			this.ldapUrl = (String) subtrees.get(ldapBase);
1140
			logMetacat.info("AuthLdap.getPrincipals - ldapBase: " + ldapBase + 
1141
					", ldapUrl: " + ldapUrl);
1142
			/*
1143
			 * code to get the organization name from ldapBase
1144
			 */
1145
			String orgName = this.ldapBase;
1146
			if (orgName.startsWith("[")) {
1147
				// if orgName starts with [ then it is a referral URL...
1148
				// (see code in getSubtress) hence orgName can be retrieved by 
1149
				// getting the string between 'o=' and ']' also the string between 
1150
				// [ and ] needs to be striped out from this.ldapBase
1151
				this.ldapBase = orgName.substring(orgName.indexOf("]") + 1);
1152
				if (orgName != null && orgName.indexOf("o=") > -1) {
1153
					orgName = orgName.substring(orgName.indexOf("o=") + 2);
1154
					orgName = orgName.substring(0, orgName.indexOf("]"));
1155
				}
1156
			} else {
1157
				// else it is not referral
1158
				// hence orgName can be retrieved by getting the string between
1159
				// 'o=' and ','
1160
				if (orgName != null && orgName.indexOf("o=") > -1) {
1161
					orgName = orgName.substring(orgName.indexOf("o=") + 2);
1162
					if (orgName.indexOf(",") > -1) {
1163
						orgName = orgName.substring(0, orgName.indexOf(","));
1164
					}
1165
				}
1166
			}
1167
			logMetacat.info("AuthLdap.getPrincipals - org name is  " + orgName);
1168
			out.append("  <authSystem URI=\"" + this.ldapUrl + this.ldapBase
1169
					+ "\" organization=\"" + orgName + "\">\n");
1170

    
1171
			// get all groups for directory context
1172
			String[][] groups = getGroups(user, password);
1173
			logMetacat.debug("AuthLdap.getPrincipals - after getting groups " + groups);
1174
			String[][] users = getUsers(user, password);
1175
			logMetacat.debug("AuthLdap.getPrincipals - after getting users " + users);
1176
			int userIndex = 0;
1177

    
1178
			// for the groups and users that belong to them
1179
			if (groups != null && users != null && groups.length > 0) {
1180
				for (int i = 0; i < groups.length; i++) {
1181
					out.append("    <group>\n");
1182
					out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
1183
					out.append("      <description>" + groups[i][1] + "</description>\n");
1184
					String[] usersForGroup = getUsers(user, password, groups[i][0]);
1185
					for (int j = 0; j < usersForGroup.length; j++) {
1186
						userIndex = searchUser(usersForGroup[j], users);
1187
						out.append("      <user>\n");
1188

    
1189
						if (userIndex < 0) {
1190
							out.append("        <username>" + usersForGroup[j]
1191
									+ "</username>\n");
1192
						} else {
1193
							out.append("        <username>" + users[userIndex][0]
1194
									+ "</username>\n");
1195
							out.append("        <name>" + users[userIndex][1]
1196
									+ "</name>\n");
1197
							out.append("        <organization>" + users[userIndex][2]
1198
									+ "</organization>\n");
1199
							if (users[userIndex][3].compareTo("null") != 0) {
1200
								out.append("      <organizationUnitName>"
1201
										+ users[userIndex][3]
1202
										+ "</organizationUnitName>\n");
1203
							}
1204
							out.append("        <email>" + users[userIndex][4]
1205
									+ "</email>\n");
1206
						}
1207

    
1208
						out.append("      </user>\n");
1209
					}
1210
					out.append("    </group>\n");
1211
				}
1212
			}
1213

    
1214
			if (users != null) {
1215
				// for the users not belonging to any grou8p
1216
				for (int j = 0; j < users.length; j++) {
1217
					out.append("    <user>\n");
1218
					out.append("      <username>" + users[j][0] + "</username>\n");
1219
					out.append("      <name>" + users[j][1] + "</name>\n");
1220
					out
1221
							.append("      <organization>" + users[j][2]
1222
									+ "</organization>\n");
1223
					if (users[j][3].compareTo("null") != 0) {
1224
						out.append("      <organizationUnitName>" + users[j][3]
1225
								+ "</organizationUnitName>\n");
1226
					}
1227
					out.append("      <email>" + users[j][4] + "</email>\n");
1228
					out.append("    </user>\n");
1229
				}
1230
			}
1231

    
1232
			out.append("  </authSystem>\n");
1233
		}
1234
		out.append("</principals>");
1235
		return out.toString();
1236
	}
1237

    
1238
	/**
1239
	 * Method for getting index of user DN in User info array
1240
	 */
1241
	int searchUser(String user, String userGroup[][]) {
1242
		for (int j = 0; j < userGroup.length; j++) {
1243
			if (user.compareTo(userGroup[j][0]) == 0) {
1244
				return j;
1245
			}
1246
		}
1247
		return -1;
1248
	}
1249

    
1250
	public void testCredentials(String dn, String password, String rootServer,
1251
			String rootBase) throws NamingException {
1252

    
1253
		String server = "";
1254
		String userDN = "";
1255
		logMetacat.debug("dn is: " + dn);
1256

    
1257
		int position = dn.lastIndexOf("/");
1258
		logMetacat.debug("AuthLdap.testCredentials - position is: " + position);
1259
		if (position == -1) {
1260
			server = rootServer;
1261
			if (dn.indexOf(userDN) < 0) {
1262
				userDN = dn + "," + rootBase;
1263
			} else {
1264
				userDN = dn;
1265
			}
1266
			logMetacat.debug("AuthLdap.testCredentials - userDN is: " + userDN);
1267

    
1268
		} else {
1269
			server = dn.substring(0, position + 1);
1270
			userDN = dn.substring(position + 1);
1271
			logMetacat.debug("AuthLdap.testCredentials - server is: " + server);
1272
			logMetacat.debug("AuthLdap.testCredentials - userDN is: " + userDN);
1273
		}
1274

    
1275
		logMetacat.debug("AuthLdap.testCredentials - Trying to authenticate: " + userDN + " using server: " + server);
1276

    
1277
		// /* try {
1278
		LdapContext ctx = null;
1279

    
1280
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
1281
		env.put(Context.REFERRAL, "follow");
1282
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
1283
		env.put(Context.SECURITY_PRINCIPAL, userDN);
1284
		env.put(Context.SECURITY_CREDENTIALS, password);
1285
		env.put(Context.PROVIDER_URL, rootServer);
1286

    
1287
		ctx = new InitialLdapContext(env, null);
1288

    
1289
	}
1290

    
1291
	/**
1292
	 * Test method for the class
1293
	 */
1294
	public static void main(String[] args) {
1295

    
1296
		// Provide a user, such as: "Matt Jones", or "jones"
1297
		String user = args[0];
1298
		String password = args[1];
1299
		String org = args[2];
1300

    
1301
		logMetacat.warn("AuthLdap.main - Creating session...");
1302
		AuthLdap authservice = null;
1303
		try {
1304
			authservice = new AuthLdap();
1305
		} catch (Exception e) {
1306
			logMetacat.error("AuthLdap.main - Could not instantiate AuthLdap: " + e.getMessage());
1307
			return;
1308
		}
1309
		logMetacat.warn("AuthLdap.main - Session exists...");
1310

    
1311
		boolean isValid = false;
1312
		try {
1313
			logMetacat.warn("AuthLdap.main - Authenticating...");
1314
			isValid = authservice.authenticate(user, password);
1315
			if (isValid) {
1316
				logMetacat.warn("AuthLdap.main - Authentication successful for: " + user);
1317
			} else {
1318
				logMetacat.warn("AuthLdap.main - Authentication failed for: " + user);
1319
			}
1320

    
1321
			// Get attributes for the user
1322
			if (isValid) {
1323
				logMetacat.info("AuthLdap.main - Getting attributes for user....");
1324
				HashMap userInfo = authservice.getAttributes(user, password, user);
1325
				// Print all of the attributes
1326
				Iterator attList = (Iterator) (((Set) userInfo.keySet()).iterator());
1327
				while (attList.hasNext()) {
1328
					String att = (String) attList.next();
1329
					Vector values = (Vector) userInfo.get(att);
1330
					Iterator attvalues = values.iterator();
1331
					while (attvalues.hasNext()) {
1332
						String value = (String) attvalues.next();
1333
						logMetacat.warn("AuthLdap.main - " + att + ": " + value);
1334
					}
1335
				}
1336
			}
1337

    
1338
			// get the groups
1339
			if (isValid) {
1340
				logMetacat.warn("AuthLdap.main - Getting all groups....");
1341
				String[][] groups = authservice.getGroups(user, password);
1342
				logMetacat.info("AuthLdap.main - Groups found: " + groups.length);
1343
				for (int i = 0; i < groups.length; i++) {
1344
					logMetacat.info("AuthLdap.main - Group " + i + ": " + groups[i][0]);
1345
				}
1346
			}
1347

    
1348
			// get the groups for the user
1349
			String savedGroup = null;
1350
			if (isValid) {
1351
				logMetacat.warn("AuthLdap.main - Getting groups for user....");
1352
				String[][] groups = authservice.getGroups(user, password, user);
1353
				logMetacat.info("AuthLdap.main - Groups found: " + groups.length);
1354
				for (int i = 0; i < groups.length; i++) {
1355
					logMetacat.info("AuthLdap.main - Group " + i + ": " + groups[i][0]);
1356
					savedGroup = groups[i][0];
1357
				}
1358
			}
1359

    
1360
			// get the users for a group
1361
			if (isValid) {
1362
				logMetacat.warn("AuthLdap.main - Getting users for group....");
1363
				logMetacat.info("AuthLdap.main - Group: " + savedGroup);
1364
				String[] users = authservice.getUsers(user, password, savedGroup);
1365
				logMetacat.info("AuthLdap.main - Users found: " + users.length);
1366
				for (int i = 0; i < users.length; i++) {
1367
					logMetacat.warn("AuthLdap.main - User " + i + ": " + users[i]);
1368
				}
1369
			}
1370

    
1371
			// get all users
1372
			if (isValid) {
1373
				logMetacat.warn("AuthLdap.main - Getting all users ....");
1374
				String[][] users = authservice.getUsers(user, password);
1375
				logMetacat.info("AuthLdap.main - Users found: " + users.length);
1376

    
1377
			}
1378

    
1379
			// get the whole list groups and users in XML format
1380
			if (isValid) {
1381
				logMetacat.warn("AuthLdap.main - Trying principals....");
1382
				authservice = new AuthLdap();
1383
				String out = authservice.getPrincipals(user, password);
1384
				java.io.File f = new java.io.File("principals.xml");
1385
				java.io.FileWriter fw = new java.io.FileWriter(f);
1386
				java.io.BufferedWriter buff = new java.io.BufferedWriter(fw);
1387
				buff.write(out);
1388
				buff.flush();
1389
				buff.close();
1390
				fw.close();
1391
				logMetacat.warn("AuthLdap.main - Finished getting principals.");
1392
			}
1393

    
1394
		} catch (ConnectException ce) {
1395
			logMetacat.error("AuthLdap.main - " + ce.getMessage());
1396
		} catch (java.io.IOException ioe) {
1397
			logMetacat.error("AuthLdap.main - I/O Error writing to file principals.txt: "
1398
					+ ioe.getMessage());
1399
		} catch (InstantiationException ie) {
1400
			logMetacat.error("AuthLdap.main - Instantiation error writing to file principals.txt: "
1401
					+ ie.getMessage());
1402
		}
1403
	}
1404

    
1405
	/**
1406
	 * This method will be called by start a thread. It can handle if a referral
1407
	 * exception happend.
1408
	 */
1409
}
(6-6/65)