Project

General

Profile

1 503 bojilova
/**
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$'
11
 *     '$Date$'
12
 * '$Revision$'
13 669 jones
 *
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 503 bojilova
 */
28
29
package edu.ucsb.nceas.metacat;
30
31
import java.net.ConnectException;
32
import javax.naming.AuthenticationException;
33
import javax.naming.Context;
34 787 bojilova
import javax.naming.NamingEnumeration;
35
import javax.naming.NamingException;
36 873 jones
import javax.naming.SizeLimitExceededException;
37 802 bojilova
import javax.naming.directory.InvalidSearchFilterException;
38 503 bojilova
import javax.naming.directory.Attribute;
39
import javax.naming.directory.Attributes;
40 504 jones
import javax.naming.directory.DirContext;
41
import javax.naming.directory.InitialDirContext;
42
import javax.naming.directory.SearchResult;
43 723 bojilova
import javax.naming.directory.SearchControls;
44 868 berkley
import javax.naming.ReferralException;
45 3022 sgarg
import javax.naming.ldap.InitialLdapContext;
46
import javax.naming.ldap.LdapContext;
47
import javax.naming.ldap.StartTlsRequest;
48
import javax.naming.ldap.StartTlsResponse;
49
import javax.net.ssl.SSLSession;
50 2666 sgarg
51
import org.apache.log4j.Logger;
52
53 1988 jones
import java.net.URLDecoder;
54 503 bojilova
import java.util.Iterator;
55
import java.util.HashMap;
56
import java.util.Hashtable;
57 730 bojilova
import java.util.Enumeration;
58 503 bojilova
import java.util.Set;
59
import java.util.Vector;
60
61
/**
62
 * An implementation of the AuthInterface interface that
63
 * allows Metacat to use the LDAP protocol for directory services.
64 2058 sgarg
 * The LDAP authentication service is used to determine if a user
65 503 bojilova
 * is authenticated, and whether they are a member of a particular group.
66
 */
67 3155 cjones
public class AuthLdap implements AuthInterface {
68 787 bojilova
  private MetaCatUtil util = new MetaCatUtil();
69 728 bojilova
  private String ldapUrl;
70 787 bojilova
  private String ldapsUrl;
71 728 bojilova
  private String ldapBase;
72 865 jones
  private String referral;
73 3155 cjones
  private String ldapConnectTimeLimit;
74
  private int ldapSearchTimeLimit;
75
  private int ldapSearchCountLimit;
76 991 tao
  private Context referralContext;
77 3155 cjones
  private String currentReferralInfo;
78 893 berkley
  Hashtable env = new Hashtable(11);
79
  private Context rContext;
80 934 tao
  private String userName;
81
  private String userPassword;
82 893 berkley
  ReferralException refExc;
83 503 bojilova
84 2666 sgarg
  private static Logger logMetacat = Logger.getLogger(AuthLdap.class);
85
86 2058 sgarg
  /**
87 728 bojilova
   * Construct an AuthLdap
88
   */
89
  public AuthLdap() {
90
    // Read LDAP URI for directory service information
91 787 bojilova
    this.ldapUrl = MetaCatUtil.getOption("ldapurl");
92
    this.ldapsUrl = MetaCatUtil.getOption("ldapsurl");
93
    this.ldapBase = MetaCatUtil.getOption("ldapbase");
94 865 jones
    this.referral = MetaCatUtil.getOption("referral");
95 3155 cjones
    this.ldapConnectTimeLimit =
96
      MetaCatUtil.getOption("ldapconnecttimelimit");
97
    this.ldapSearchTimeLimit = Integer.parseInt(
98
      MetaCatUtil.getOption("ldapsearchtimelimit"));
99
    this.ldapSearchCountLimit = Integer.parseInt(
100
      MetaCatUtil.getOption("ldapsearchcountlimit"));
101
102
    // Store referral info for use in building group DNs in getGroups()
103
    this.currentReferralInfo = "";
104 728 bojilova
  }
105
106 503 bojilova
  /**
107
   * Determine if a user/password are valid according to the authentication
108
   * service.
109
   *
110
   * @param user the name of the principal to authenticate
111
   * @param password the password to use for authentication
112
   * @returns boolean true if authentication successful, false otherwise
113
   */
114 3022 sgarg
115 3157 cjones
  public boolean authenticate(String user, String password) throws
116
    ConnectException {
117 730 bojilova
    String ldapUrl = this.ldapUrl;
118 787 bojilova
    String ldapsUrl = this.ldapsUrl;
119 730 bojilova
    String ldapBase = this.ldapBase;
120 503 bojilova
    boolean authenticated = false;
121 802 bojilova
    String identifier = user;
122 3022 sgarg
123 1004 tao
    //get uid here.
124 3022 sgarg
    String uid=user.substring(0, user.indexOf(","));
125
    user = user.substring(user.indexOf(","), user.length());
126 2058 sgarg
127 3022 sgarg
    logMetacat.debug("identifier: " + identifier);
128
    logMetacat.debug("uid: " + uid);
129
    logMetacat.debug("user: " + user);
130
131 503 bojilova
    try {
132 3022 sgarg
    	// Check the usename as passed in
133
        logMetacat.info("Calling ldapAuthenticate");
134
        logMetacat.info("with user as identifier: " + identifier);
135
136
        authenticated = ldapAuthenticate(identifier, password,
137
        		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPConnection"))).booleanValue());
138
        // if not found, try looking up a valid DN then auth again
139
        if (!authenticated) {
140
        	logMetacat.info("Not Authenticated");
141
        	logMetacat.info("Looking up DN for: " + identifier);
142
        	identifier = getIdentifyingName(identifier, ldapUrl, ldapBase);
143
        	if(identifier == null){
144 3023 sgarg
        		logMetacat.info("No DN found from getIdentifyingName");
145 3022 sgarg
        		return authenticated;
146
        	}
147
148
           	logMetacat.info("DN found from getIdentifyingName: " + identifier);
149
        	String decoded = URLDecoder.decode(identifier);
150
        	logMetacat.info("DN decoded: " + decoded);
151
        	identifier = decoded;
152
        	String refUrl = "";
153
        	String refBase = "";
154
        	if (identifier.startsWith("ldap")) {
155 3157 cjones
        		logMetacat.debug("identifier starts with \"ldap\"");
156 3022 sgarg
157
        		refUrl = identifier.substring(0, identifier.lastIndexOf("/") + 1);
158
        		int position = identifier.indexOf(",");
159
        		int position2 = identifier.indexOf(",", position + 1);
160 3023 sgarg
161 3022 sgarg
        		refBase = identifier.substring(position2 + 1);
162
        		identifier = identifier.substring(identifier.lastIndexOf("/") + 1);
163 3023 sgarg
164 3157 cjones
        		logMetacat.info("Calling ldapAuthenticate:");
165 3022 sgarg
        		logMetacat.info("with user as identifier: " + identifier);
166
        		logMetacat.info("and refUrl as: " + refUrl);
167
        		logMetacat.info("and refBase as: " + refBase);
168
169
        		authenticated = ldapAuthenticate(identifier, password, refUrl, refBase,
170
                		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPReferalsConnection")))
171
                			.booleanValue());
172
        	} else {
173
        		logMetacat.info("identifier doesnt start with ldap");
174 3023 sgarg
        		identifier = identifier + "," + ldapBase;
175
176 3022 sgarg
        		logMetacat.info("Calling ldapAuthenticate");
177
        		logMetacat.info("with user as identifier: " + identifier);
178 3023 sgarg
179 3022 sgarg
        		authenticated = ldapAuthenticate(identifier, password,
180
            		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPConnection"))).booleanValue());
181
        	}
182 1004 tao
        }
183 3157 cjones
    } catch (NullPointerException e) {
184 3022 sgarg
    	logMetacat.error("NullPointerException while authenticating in " +
185 2589 sgarg
                        "AuthLdap.authenticate: " + e);
186 3022 sgarg
    	e.printStackTrace();
187
188
    	throw new ConnectException(
189 2121 sgarg
          "NullPointerException while authenticating in " +
190
          "AuthLdap.authenticate: " + e);
191 3022 sgarg
    } catch (NamingException e) {
192
    	logMetacat.error("Naming exception while authenticating in " +
193 2589 sgarg
                        "AuthLdap.authenticate: " + e);
194 3022 sgarg
    	e.printStackTrace();
195
    } catch (Exception e) {
196
    	logMetacat.error(e.getMessage());
197 2121 sgarg
    }
198 3022 sgarg
199 503 bojilova
    return authenticated;
200
  }
201
202
  /**
203 852 jones
   * Connect to the LDAP directory and do the authentication using the
204
   * username and password as passed into the routine.
205
   *
206
   * @param identifier the distinguished name to check against LDAP
207
   * @param password the password for authentication
208
   */
209 3157 cjones
  private boolean ldapAuthenticate(String identifier, String password, boolean
210
    secureConnectionOnly) throws ConnectException, NamingException,
211
    NullPointerException {
212 2121 sgarg
    return ldapAuthenticate(identifier, password,
213 3022 sgarg
                            this.ldapsUrl, this.ldapBase, secureConnectionOnly);
214 1005 jones
  }
215
216
  /**
217
   * Connect to the LDAP directory and do the authentication using the
218
   * username and password as passed into the routine.
219
   *
220
   * @param identifier the distinguished name to check against LDAP
221
   * @param password the password for authentication
222
   */
223 3022 sgarg
224 3157 cjones
  private boolean ldapAuthenticate(String dn, String password,
225
    String rootServer, String rootBase, boolean secureConnectionOnly){
226 3022 sgarg
227
	  boolean authenticated = false;
228
229
	  String server = "";
230
	  String userDN = "";
231
	  logMetacat.info("dn is: " + dn);
232 2058 sgarg
233 3022 sgarg
	  int position = dn.lastIndexOf("/");
234
      logMetacat.debug("position is: " + position);
235
	  if (position == -1) {
236
		  server = rootServer;
237
		  if(dn.indexOf(userDN) < 0){
238
			  userDN = dn + "," + rootBase;
239
		  } else {
240
			  userDN = dn;
241
		  }
242
		  logMetacat.info("userDN is: " + userDN);
243
244
       } else {
245
		  server = dn.substring(0, position+1);
246
		  userDN = dn.substring(position+1);
247
		  logMetacat.info("server is: " + server);
248
		  logMetacat.info("userDN is: " + userDN);
249
	   }
250
251
	   logMetacat.warn("Trying to authenticate: " + userDN);
252
	   logMetacat.warn("          Using server: " + server);
253
254
	   LdapContext ctx = null;
255
	   double startTime;
256
	   double stopTime;
257
	   try {
258
		   Hashtable env = new Hashtable();
259
		   env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
260
		   env.put(Context.PROVIDER_URL, server);
261
		   env.put(Context.REFERRAL, "throw");
262
263
		   try {
264
265
			   startTime = System.currentTimeMillis();
266
			   ctx = new InitialLdapContext(env, null);
267
268
			   // Start up TLS here so that we don't pass our jewels in cleartext
269
		       StartTlsResponse tls =
270
		              (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
271
		       //tls.setHostnameVerifier(new SampleVerifier());
272
		       SSLSession sess = tls.negotiate();
273
274
		       ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
275
			   ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
276
			   ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
277
			   ctx.reconnect(null);
278
279
			   stopTime = System.currentTimeMillis();
280
			   logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
281
                       	(stopTime - startTime) / 1000 + " seconds.");
282
283
			   authenticated = true;
284
		   } catch (java.io.IOException ioe) {
285
			   logMetacat.warn("Caught IOException in login while negotiating TLS: "
286
	                                 + ioe.getMessage());
287
288
			   if(secureConnectionOnly){
289 3023 sgarg
290
				   return authenticated;
291
292 3022 sgarg
			   } else {
293 3023 sgarg
294
				   logMetacat.info("Trying to authenticate without TLS");
295 3022 sgarg
				   env.put(Context.SECURITY_AUTHENTICATION, "simple");
296
				   env.put(Context.SECURITY_PRINCIPAL, userDN);
297
				   env.put(Context.SECURITY_CREDENTIALS, password);
298
299
				   startTime = System.currentTimeMillis();
300
				   ctx = new InitialLdapContext(env, null);
301
				   stopTime = System.currentTimeMillis();
302
				   logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
303
	                       	(stopTime - startTime) / 1000 + " seconds.");
304
305
				   authenticated = true;
306
			   }
307
		   }
308
	   } catch (AuthenticationException ae) {
309
		   authenticated = false;
310
	   } catch (javax.naming.InvalidNameException ine) {
311
	        logMetacat.error("An invalid DN was provided!");
312
	   } catch (NamingException e) {
313
		   logMetacat.warn("Caught NamingException in login: " + e.getClass().getName());
314
		   logMetacat.info(e.toString() + "  " + e.getRootCause());
315 2666 sgarg
       }
316 934 tao
317 3022 sgarg
       return authenticated;
318 852 jones
  }
319
320 3022 sgarg
321 852 jones
  /**
322 730 bojilova
   * Get the identifying name for a given userid or name.  This is the name
323
   * that is used in conjunction withthe LDAP BaseDN to create a
324
   * distinguished name (dn) for the record
325
   *
326
   * @param user the user for which the identifying name is requested
327 2058 sgarg
   * @returns String the identifying name for the user,
328 730 bojilova
   *          or null if not found
329
   */
330 3157 cjones
  private String getIdentifyingName(String user, String ldapUrl,
331
    String ldapBase) throws NamingException {
332 3022 sgarg
333
      String identifier = null;
334
      Hashtable env = new Hashtable();
335
      env.put(Context.INITIAL_CONTEXT_FACTORY,
336
              "com.sun.jndi.ldap.LdapCtxFactory");
337
      env.put(Context.REFERRAL, "throw");
338
      env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
339 802 bojilova
      try {
340 3022 sgarg
    	  int position = user.indexOf(",");
341
          String uid = user.substring(user.indexOf("=") + 1, position);
342 3023 sgarg
          logMetacat.info("uid is: " + uid);
343 3022 sgarg
          String org = user.substring(user.indexOf("=", position + 1) + 1,
344
                                        user.indexOf(",", position + 1));
345 3023 sgarg
          logMetacat.info("org is: " + org);
346 3022 sgarg
347
          DirContext sctx = new InitialDirContext(env);
348
          SearchControls ctls = new SearchControls();
349
          ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
350
          String filter = "(&(uid=" + uid + ")(o=" + org + "))";
351 3023 sgarg
          logMetacat.warn("Searching for DNs with following filter: " + filter);
352 3022 sgarg
353
          for (boolean moreReferrals = true; moreReferrals;) {
354
              try {
355
                  // Perform the search
356
                  NamingEnumeration answer =
357
                      sctx.search("", filter, ctls);
358 1005 jones
359 3022 sgarg
                  // Return the answer
360
                  while (answer.hasMore()) {
361
                      SearchResult sr = (SearchResult)answer.next();
362
                      identifier = sr.getName();
363
                      return identifier;
364
                  }
365
                  // The search completes with no more referrals
366
                  moreReferrals = false;
367
              } catch (ReferralException e) {
368
            	  logMetacat.info("Got referral: " + e.getReferralInfo());
369 3023 sgarg
            	  // Point to the new context from the referral
370 3022 sgarg
                  if (moreReferrals) {
371
                      sctx = (DirContext) e.getReferralContext();
372
                  }
373
              }
374 730 bojilova
          }
375 3022 sgarg
      } catch (NamingException e) {
376
    	     logMetacat.error("Naming exception while getting dn: " + e);
377
    	      throw new NamingException(
378
    	          "Naming exception in AuthLdap.getIdentifyingName: " + e);
379
    	      }
380
      return identifier;
381 730 bojilova
  }
382 3022 sgarg
383 730 bojilova
  /**
384 503 bojilova
   * Get all users from the authentication service
385 871 jones
   *
386
   * @param user the user for authenticating against the service
387
   * @param password the password for authenticating against the service
388
   * @returns string array of all of the user names
389 503 bojilova
   */
390 3157 cjones
  public String[][] getUsers(String user, String password) throws
391
    ConnectException {
392 2058 sgarg
    String[][] users = null;
393 723 bojilova
394
    // Identify service provider to use
395
    Hashtable env = new Hashtable(11);
396 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
397 723 bojilova
            "com.sun.jndi.ldap.LdapCtxFactory");
398 865 jones
    env.put(Context.REFERRAL, referral);
399 871 jones
    env.put(Context.PROVIDER_URL, ldapUrl);
400 2058 sgarg
401 723 bojilova
    try {
402
403 2121 sgarg
      // Create the initial directory context
404
      DirContext ctx = new InitialDirContext(env);
405 723 bojilova
406 2121 sgarg
      // Specify the attributes to match.
407
      // Users are objects that have the attribute objectclass=InetOrgPerson.
408
      SearchControls ctls = new SearchControls();
409
      String[] attrIDs = {
410 2130 sgarg
          "dn", "cn", "o", "ou", "mail"};
411 2121 sgarg
      ctls.setReturningAttributes(attrIDs);
412
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
413
      //ctls.setCountLimit(1000);
414
      String filter = "(objectClass=inetOrgPerson)";
415 2447 sgarg
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
416 2058 sgarg
417 2121 sgarg
      // Store the users in a vector
418
      Vector uvec = new Vector();
419
      Vector uname = new Vector();
420
      Vector uorg = new Vector();
421 2130 sgarg
      Vector uou = new Vector();
422 2121 sgarg
      Vector umail = new Vector();
423
      Attributes tempAttr = null;
424
      try {
425 2447 sgarg
        while (namingEnum.hasMore()) {
426
          SearchResult sr = (SearchResult) namingEnum.next();
427 2121 sgarg
          tempAttr = sr.getAttributes();
428 2058 sgarg
429 2121 sgarg
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
430
            uname.add( (tempAttr.get("cn") + "").substring(4));
431
          }
432
          else {
433
            uname.add(tempAttr.get("cn") + "");
434
          }
435 2058 sgarg
436 2121 sgarg
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
437
            uorg.add( (tempAttr.get("o") + "").substring(3));
438
          }
439
          else {
440
            uorg.add(tempAttr.get("o") + "");
441
          }
442 2116 sgarg
443 2130 sgarg
          if ( (tempAttr.get("ou") + "").startsWith("ou: ")) {
444
            uou.add( (tempAttr.get("ou") + "").substring(4));
445
          }
446
          else {
447
            uou.add(tempAttr.get("ou") + "");
448
          }
449
450 2121 sgarg
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
451
            umail.add( (tempAttr.get("mail") + "").substring(6));
452
          }
453
          else {
454
            umail.add(tempAttr.get("mail") + "");
455
          }
456 2058 sgarg
457 2121 sgarg
          uvec.add(sr.getName() + "," + ldapBase);
458 723 bojilova
        }
459 2121 sgarg
      }
460
      catch (SizeLimitExceededException slee) {
461 2666 sgarg
        logMetacat.error("LDAP Server size limit exceeded. " +
462 2589 sgarg
                          "Returning incomplete record set.");
463 2121 sgarg
      }
464 723 bojilova
465 2121 sgarg
      // initialize users[]; fill users[]
466 2130 sgarg
      users = new String[uvec.size()][5];
467 2121 sgarg
      for (int i = 0; i < uvec.size(); i++) {
468
        users[i][0] = (String) uvec.elementAt(i);
469
        users[i][1] = (String) uname.elementAt(i);
470
        users[i][2] = (String) uorg.elementAt(i);
471 2130 sgarg
        users[i][3] = (String) uorg.elementAt(i);
472
        users[i][4] = (String) umail.elementAt(i);
473 2121 sgarg
      }
474 723 bojilova
475 2121 sgarg
      // Close the context when we're done
476
      ctx.close();
477 723 bojilova
478 2121 sgarg
    }
479
    catch (NamingException e) {
480 2666 sgarg
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
481 1477 tao
      //e.printStackTrace(System.err);
482 723 bojilova
      throw new ConnectException(
483 2121 sgarg
          "Problem getting users in AuthLdap.getUsers:" + e);
484 723 bojilova
    }
485
486
    return users;
487 503 bojilova
  }
488
489 2679 sgarg
490 503 bojilova
  /**
491 2679 sgarg
   * Get all users from the authentication service
492
   *
493
   * @param user the user for authenticating against the service
494
   * @param password the password for authenticating against the service
495
   * @returns string array of all of the user names
496
   */
497 3157 cjones
  public String[] getUserInfo(String user, String password) throws
498
    ConnectException {
499 2679 sgarg
    String[] userinfo = new String[3];
500
501
    // Identify service provider to use
502
    Hashtable env = new Hashtable(11);
503
    env.put(Context.INITIAL_CONTEXT_FACTORY,
504
            "com.sun.jndi.ldap.LdapCtxFactory");
505
    env.put(Context.REFERRAL, referral);
506
    env.put(Context.PROVIDER_URL, ldapUrl);
507
508
    try {
509 2697 sgarg
510 2679 sgarg
      // Create the initial directory context
511
      DirContext ctx = new InitialDirContext(env);
512
      // Specify the attributes to match.
513
      // Users are objects that have the attribute objectclass=InetOrgPerson.
514
      SearchControls ctls = new SearchControls();
515
      String[] attrIDs = {
516
          "cn", "o", "mail"};
517
      ctls.setReturningAttributes(attrIDs);
518
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
519
      //ctls.setCountLimit(1000);
520 2697 sgarg
      // create the filter based on the uid
521
522
      String filter = null;
523
524
      if(user.indexOf("o=")>0){
525
    	  String tempStr = user.substring(user.indexOf("o="));
526
    	  filter = "(&(" + user.substring(0, user.indexOf(","))
527
			+ ")(" + tempStr.substring(0, tempStr.indexOf(","))
528
			+ "))";
529
      } else{
530
    	  filter = "(&(" + user.substring(0, user.indexOf(","))
531
			+ "))";
532
      }
533
   	  filter = "(&(" + user.substring(0, user.indexOf(","))
534
		+ "))";
535
536 2679 sgarg
      NamingEnumeration namingEnum = ctx.search(user, filter, ctls);
537 2697 sgarg
538 2679 sgarg
      Attributes tempAttr = null;
539
      try {
540
        while (namingEnum.hasMore()) {
541
          SearchResult sr = (SearchResult) namingEnum.next();
542
          tempAttr = sr.getAttributes();
543
544
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
545
        	  userinfo[0] = (tempAttr.get("cn") + "").substring(4);
546
          }
547
          else {
548
        	  userinfo[0] = (tempAttr.get("cn") + "");
549
          }
550
551
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
552
        	  userinfo[1] = (tempAttr.get("o") + "").substring(3);
553
          }
554
          else {
555
        	  userinfo[1] = (tempAttr.get("o") + "");
556
          }
557
558
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
559
        	  userinfo[2] =  (tempAttr.get("mail") + "").substring(6);
560
          }
561
          else {
562
        	  userinfo[2] = (tempAttr.get("mail") + "");
563
          }
564
        }
565
      }
566
      catch (SizeLimitExceededException slee) {
567
        logMetacat.error("LDAP Server size limit exceeded. " +
568
                          "Returning incomplete record set.");
569
      }
570
571
      // Close the context when we're done
572
      ctx.close();
573
574
    }
575
    catch (NamingException e) {
576
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
577
      //e.printStackTrace(System.err);
578
      throw new ConnectException(
579
          "Problem getting users in AuthLdap.getUsers:" + e);
580
    }
581
582
    return userinfo;
583
  }
584
585
  /**
586 503 bojilova
   * Get the users for a particular group from the authentication service
587 871 jones
   *
588
   * @param user the user for authenticating against the service
589
   * @param password the password for authenticating against the service
590
   * @param group the group whose user list should be returned
591
   * @returns string array of the user names belonging to the group
592 503 bojilova
   */
593 3157 cjones
  public String[] getUsers(String user, String password, String group) throws
594
    ConnectException {
595 723 bojilova
    String[] users = null;
596
597
    // Identify service provider to use
598
    Hashtable env = new Hashtable(11);
599 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
600 723 bojilova
            "com.sun.jndi.ldap.LdapCtxFactory");
601 865 jones
    env.put(Context.REFERRAL, referral);
602 871 jones
    env.put(Context.PROVIDER_URL, ldapUrl);
603 723 bojilova
604
    try {
605
606 2121 sgarg
      // Create the initial directory context
607
      DirContext ctx = new InitialDirContext(env);
608 723 bojilova
609 2121 sgarg
      // Specify the ids of the attributes to return
610
      String[] attrIDs = {
611
          "uniqueMember"};
612 723 bojilova
613 2121 sgarg
      Attributes answer = ctx.getAttributes(group, attrIDs);
614 723 bojilova
615 2121 sgarg
      Vector uvec = new Vector();
616
      try {
617
        for (NamingEnumeration ae = answer.getAll(); ae.hasMore(); ) {
618
          Attribute attr = (Attribute) ae.next();
619
          for (NamingEnumeration e = attr.getAll();
620
               e.hasMore();
621
               uvec.add(e.next())
622
               ) {
623
            ;
624
          }
625 723 bojilova
        }
626 2121 sgarg
      }
627
      catch (SizeLimitExceededException slee) {
628 2666 sgarg
        logMetacat.error("LDAP Server size limit exceeded. " +
629 2589 sgarg
                          "Returning incomplete record set.");
630 2121 sgarg
      }
631 723 bojilova
632 2121 sgarg
      // initialize users[]; fill users[]
633
      users = new String[uvec.size()];
634
      for (int i = 0; i < uvec.size(); i++) {
635
        users[i] = (String) uvec.elementAt(i);
636
      }
637 723 bojilova
638 2121 sgarg
      // Close the context when we're done
639
      ctx.close();
640 723 bojilova
641 2121 sgarg
    }
642
    catch (NamingException e) {
643 2666 sgarg
      logMetacat.error("Problem getting users for a group in " +
644 2589 sgarg
                        "AuthLdap.getUsers:" + e);
645 723 bojilova
      throw new ConnectException(
646 2121 sgarg
          "Problem getting users for a group in AuthLdap.getUsers:" + e);
647 723 bojilova
    }
648
649
    return users;
650 503 bojilova
  }
651
652
  /**
653
   * Get all groups from the authentication service
654 871 jones
   *
655
   * @param user the user for authenticating against the service
656
   * @param password the password for authenticating against the service
657
   * @returns string array of the group names
658 503 bojilova
   */
659 3157 cjones
  public String[][] getGroups(String user, String password) throws
660
    ConnectException {
661 2121 sgarg
    return getGroups(user, password, null);
662 503 bojilova
  }
663
664
  /**
665
   * Get the groups for a particular user from the authentication service
666 871 jones
   *
667
   * @param user the user for authenticating against the service
668
   * @param password the password for authenticating against the service
669
   * @param foruser the user whose group list should be returned
670
   * @returns string array of the group names
671 503 bojilova
   */
672 3156 cjones
  public String[][] getGroups(String user, String password,
673
    String foruser) throws ConnectException {
674
675
    logMetacat.debug("getGroups() called.");
676
677
    // create vectors to store group and dscription values returned from the
678
    // ldap servers
679 2116 sgarg
    Vector gvec = new Vector();
680 2058 sgarg
    Vector desc = new Vector();
681
    Attributes tempAttr = null;
682 3156 cjones
    Attributes rsrAttr = null;
683
684
    // DURING getGroups(), DO WE NOT BIND USING userName AND userPassword??
685
    // NEED TO FIX THIS ...
686 2121 sgarg
    userName = user;
687
    userPassword = password;
688 723 bojilova
    // Identify service provider to use
689 3156 cjones
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
690 888 berkley
    env.put(Context.REFERRAL, "throw");
691 871 jones
    env.put(Context.PROVIDER_URL, ldapUrl);
692 3156 cjones
    env.put("com.sun.jndi.ldap.connect.timeout", ldapConnectTimeLimit);
693
694
695
    // Iterate through the referrals, handling NamingExceptions in the
696
    // outer catch statement, ReferralExceptions in the inner catch statement
697
    try { // outer try
698
699 2121 sgarg
      // Create the initial directory context
700
      DirContext ctx = new InitialDirContext(env);
701 3156 cjones
702 2121 sgarg
      // Specify the attributes to match.
703
      // Groups are objects with attribute objectclass=groupofuniquenames.
704
      // and have attribute uniquemember: uid=foruser,ldapbase.
705
      SearchControls ctls = new SearchControls();
706 3156 cjones
      // Specify the ids of the attributes to return
707
      String[] attrIDs = {"cn", "o", "description"};
708 2121 sgarg
      ctls.setReturningAttributes(attrIDs);
709 3156 cjones
      // set the ldap search scope
710 2121 sgarg
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
711 3156 cjones
      // set a 10 second time limit on searches to limit non-responding servers
712
      ctls.setTimeLimit(ldapSearchTimeLimit);
713
      // return at most 20000 entries
714
      ctls.setCountLimit(ldapSearchCountLimit);
715 2058 sgarg
716 3156 cjones
      // build the ldap search filter that represents the "group" concept
717 2121 sgarg
      String filter = null;
718
      String gfilter = "(objectClass=groupOfUniqueNames)";
719
      if (null == foruser) {
720
        filter = gfilter;
721 3156 cjones
      } else {
722 2121 sgarg
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
723
      }
724 3156 cjones
      logMetacat.info("group filter is: " + filter);
725
726
      // now, search and iterate through the referrals
727
      for (boolean moreReferrals = true; moreReferrals;) {
728
        try { // inner try
729
730
          NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
731 991 tao
732 3156 cjones
          // Print the groups
733
          while (namingEnum.hasMore()) {
734
            SearchResult sr = (SearchResult) namingEnum.next();
735
736
            tempAttr = sr.getAttributes();
737 2058 sgarg
738 3156 cjones
            if ( (tempAttr.get("description") + "").startsWith("description: ")) {
739
              desc.add( (tempAttr.get("description") + "").substring(13));
740
            }
741
            else {
742
              desc.add(tempAttr.get("description") + "");
743
            }
744
745
            // check for an absolute URL value or an answer value relative
746
            // to the target context
747
            if ( !sr.getName().startsWith("ldap") &&
748
                  sr.isRelative()) {
749
              logMetacat.debug("Search result entry is relative ...");
750
              gvec.add(sr.getName() + "," + ldapBase);
751
              logMetacat.info("group " + sr.getName() + "," +ldapBase +
752
              " added to the group vector");
753
            } else {
754
              logMetacat.debug("Search result entry is absolute ...");
755
756
              // search the top level directory for referral objects and match
757
              // that of the search result's absolute URL.  This will let us
758
              // rebuild the group name from the search result, referral point
759
              // in the top directory tree, and ldapBase.
760
761
              // configure a new directory search first
762
              Hashtable envHash = new Hashtable(11);
763
              // Identify service provider to use
764
              envHash.put(Context.INITIAL_CONTEXT_FACTORY,
765
                "com.sun.jndi.ldap.LdapCtxFactory");
766
              envHash.put(Context.REFERRAL, "ignore");
767
              envHash.put(Context.PROVIDER_URL, ldapUrl);
768
              envHash.put("com.sun.jndi.ldap.connect.timeout",
769
                ldapConnectTimeLimit);
770
771
              try {
772
                // Create the initial directory context
773
                DirContext DirCtx = new InitialDirContext(envHash);
774 991 tao
775 3156 cjones
                SearchControls searchCtls = new SearchControls();
776
                // Specify the ids of the attributes to return
777
                String[] attrNames = {"o"};
778
                searchCtls.setReturningAttributes(attrNames);
779
                // set the ldap search scope - only look for top level referrals
780
                searchCtls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
781
                // set a time limit on searches to limit non-responding servers
782
                searchCtls.setTimeLimit(ldapSearchTimeLimit);
783
                // return the configured number of entries
784
                searchCtls.setCountLimit(ldapSearchCountLimit);
785
786
                // Specify the attributes to match.
787
                // build the ldap search filter to match referral entries that
788
                // match the search result
789
                String rFilter = "(&(objectClass=referral)(ref=" +
790
                currentReferralInfo.substring(0,
791
                currentReferralInfo.indexOf("?")) + "))";
792
                logMetacat.debug("rFilter is: " + rFilter);
793
794
                NamingEnumeration rNamingEnum =
795
                  DirCtx.search(ldapBase, rFilter, searchCtls);
796
797
                while (rNamingEnum.hasMore()) {
798
                  SearchResult rsr = (SearchResult) rNamingEnum.next();
799
                  rsrAttr = rsr.getAttributes();
800
                  logMetacat.debug("referral search result is: " +
801
                    rsr.toString());
802
803
                  // add the returned groups to the group vector.  Test the
804
                  // syntax of the returned attributes - sometimes they are
805
                  // preceded with the attribute id and a colon
806
                  if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
807
                    gvec.add( "cn=" + (tempAttr.get("cn") + "").substring(4) +
808
                    "," + "o=" + (rsrAttr.get("o") + "").substring(3 ) + "," +
809
                    ldapBase);
810
                    logMetacat.info("group " +
811
                    (tempAttr.get("cn") + "").substring(4) + "," +
812
                    "o=" + (rsrAttr.get("o") + "").substring(3) + "," +
813
                    ldapBase + " added to the group vector");
814
                  } else {
815
                    gvec.add( "cn=" + tempAttr.get("cn") + "," +
816
                    "o=" + rsrAttr.get("o") +
817
                    "," + ldapBase);
818
                    logMetacat.info("group " +
819
                    "cn=" + tempAttr.get("cn") + "," +
820
                    "o=" + rsrAttr.get("o") + "," +
821
                    ldapBase + " added to the group vector");
822
                  }
823
                }
824
825
              } catch (NamingException nameEx){
826
                logMetacat.debug("Caught naming exception: ");
827
                nameEx.printStackTrace(System.err);
828
              }
829
            }
830
          }// end while
831
832
          moreReferrals = false;
833
834
        } catch (ReferralException re) {
835
836
          logMetacat.info(
837
            "In AuthLdap.getGroups(), caught referral exception: " +
838
            re.getReferralInfo()
839
          );
840
          this.currentReferralInfo = (String) re.getReferralInfo();
841
842
          // set moreReferrals to true and set the referral context
843
          moreReferrals = true;
844
          ctx = (DirContext) re.getReferralContext();
845
846
        }// end inner try
847
      }// end for
848
849
      // close the context now that all initial and referral
850
      // searches are processed
851 2121 sgarg
      ctx.close();
852 3156 cjones
853
    } catch (NamingException e) {
854
855
      // naming exceptions get logged, groups are returned
856
      logMetacat.info("In AuthLdap.getGroups(), caught naming exception: ");
857 868 berkley
      e.printStackTrace(System.err);
858 3156 cjones
859
    } finally {
860
      // once all referrals are followed, report and return the groups found
861
      logMetacat.warn("The user is in the following groups: " +
862
                               gvec.toString());
863
      //build and return the groups array
864 2116 sgarg
      String groups[][] = new String[gvec.size()][2];
865 2121 sgarg
      for (int i = 0; i < gvec.size(); i++) {
866
        groups[i][0] = (String) gvec.elementAt(i);
867
        groups[i][1] = (String) desc.elementAt(i);
868 1006 tao
      }
869
      return groups;
870 3156 cjones
    }// end outer try
871 503 bojilova
  }
872
873
  /**
874
   * Get attributes describing a user or group
875
   *
876 871 jones
   * @param foruser the user for which the attribute list is requested
877 503 bojilova
   * @returns HashMap a map of attribute name to a Vector of values
878
   */
879 2121 sgarg
  public HashMap getAttributes(String foruser) throws ConnectException {
880 514 jones
    return getAttributes(null, null, foruser);
881 503 bojilova
  }
882
883
  /**
884
   * Get attributes describing a user or group
885
   *
886 871 jones
   * @param user the user for authenticating against the service
887 503 bojilova
   * @param password the password for authenticating against the service
888 871 jones
   * @param foruser the user whose attributes should be returned
889 503 bojilova
   * @returns HashMap a map of attribute name to a Vector of values
890
   */
891 3156 cjones
  public HashMap getAttributes(String user, String password,
892
    String foruser) throws ConnectException {
893 503 bojilova
    HashMap attributes = new HashMap();
894 802 bojilova
    String ldapUrl = this.ldapUrl;
895
    String ldapBase = this.ldapBase;
896
    String userident = foruser;
897 2058 sgarg
898 503 bojilova
    // Identify service provider to use
899
    Hashtable env = new Hashtable(11);
900 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
901 2121 sgarg
            "com.sun.jndi.ldap.LdapCtxFactory");
902 865 jones
    env.put(Context.REFERRAL, referral);
903 871 jones
    env.put(Context.PROVIDER_URL, ldapUrl);
904 503 bojilova
905
    try {
906 2058 sgarg
907 503 bojilova
      // Create the initial directory context
908
      DirContext ctx = new InitialDirContext(env);
909 2058 sgarg
910
      // Ask for all attributes of the user
911 871 jones
      //Attributes attrs = ctx.getAttributes(userident);
912
      Attributes attrs = ctx.getAttributes(foruser);
913 2058 sgarg
914 503 bojilova
      // Print all of the attributes
915
      NamingEnumeration en = attrs.getAll();
916
      while (en.hasMore()) {
917 2121 sgarg
        Attribute att = (Attribute) en.next();
918 503 bojilova
        Vector values = new Vector();
919
        String attName = att.getID();
920
        NamingEnumeration attvalues = att.getAll();
921
        while (attvalues.hasMore()) {
922 2121 sgarg
          String value = (String) attvalues.next();
923 503 bojilova
          values.add(value);
924
        }
925
        attributes.put(attName, values);
926
      }
927 2058 sgarg
928 503 bojilova
      // Close the context when we're done
929
      ctx.close();
930 2121 sgarg
    }
931
    catch (NamingException e) {
932 2666 sgarg
      logMetacat.error("Problem getting attributes in " +
933 2589 sgarg
                        "AuthLdap.getAttributes:" + e);
934 723 bojilova
      throw new ConnectException(
935 2121 sgarg
          "Problem getting attributes in AuthLdap.getAttributes:" + e);
936 503 bojilova
    }
937
938
    return attributes;
939
  }
940
941
  /**
942 730 bojilova
   * Get list of all subtrees holding Metacat's groups and users
943 2058 sgarg
   * starting from the Metacat LDAP root,
944 730 bojilova
   * i.e. ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
945 504 jones
   */
946 3156 cjones
  private Hashtable getSubtrees(String user, String password,
947
    String ldapUrl, String ldapBase) throws ConnectException {
948 730 bojilova
    Hashtable trees = new Hashtable();
949 504 jones
950
    // Identify service provider to use
951
    Hashtable env = new Hashtable(11);
952 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
953 504 jones
            "com.sun.jndi.ldap.LdapCtxFactory");
954 2129 sgarg
    // env.put(Context.REFERRAL, referral);
955
    // Using 'ignore' here instead of 'follow' as 'ignore' seems
956
    // to do the job better. 'follow' was not bringing up the UCNRS
957
    // and PISCO tree whereas 'ignore' brings up the tree.
958
959
    env.put(Context.REFERRAL, "ignore");
960 504 jones
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
961
962
    try {
963
964 2121 sgarg
      // Create the initial directory context
965
      DirContext ctx = new InitialDirContext(env);
966 730 bojilova
967 2121 sgarg
      // Specify the ids of the attributes to return
968
      String[] attrIDs = {
969
          "o", "ref"};
970
      SearchControls ctls = new SearchControls();
971
      ctls.setReturningAttributes(attrIDs);
972
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
973 2058 sgarg
974 2121 sgarg
      // Specify the attributes to match.
975
      // Subtrees from the main server are found as objects with attribute
976
      // objectclass=organization or objectclass=referral to the subtree
977
      // resided on other server.
978
      String filter = "(|(objectclass=organization)(objectclass=referral))";
979 730 bojilova
980 2121 sgarg
      // Search for objects in the current context
981 2447 sgarg
      NamingEnumeration namingEnum = ctx.search("", filter, ctls);
982 730 bojilova
983 2121 sgarg
      // Print the subtrees' <ldapURL, baseDN>
984 2447 sgarg
      while (namingEnum.hasMore()) {
985 2121 sgarg
986 2447 sgarg
        SearchResult sr = (SearchResult) namingEnum.next();
987 2121 sgarg
988
        Attributes attrs = sr.getAttributes();
989
        NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref" attrs
990
991
        if (enum1.hasMore()) {
992
          Attribute attr = (Attribute) enum1.next();
993
          String attrValue = (String) attr.get();
994
          String attrName = (String) attr.getID();
995
996 730 bojilova
          if (enum1.hasMore()) {
997 2121 sgarg
            attr = (Attribute) enum1.next();
998
            String refValue = (String) attr.get();
999
            String refName = (String) attr.getID();
1000
            if (ldapBase.startsWith(refName + "=" + refValue)) {
1001
              trees.put(ldapBase,
1002
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
1003
            }
1004
            else {
1005 2129 sgarg
              // this is a referral - so organization name is appended in
1006
              // front of the ldapbase.... later it is stripped out
1007
              // in getPrincipals
1008
              trees.put("[" + refName + "=" + refValue + "]" +
1009
                        attrValue.substring(attrValue.lastIndexOf("/") + 1,
1010
                                            attrValue.length()),
1011 2121 sgarg
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
1012 2129 sgarg
1013
              // trees.put(refName + "=" + refValue + "," + ldapBase,
1014
              //           attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
1015 2121 sgarg
            }
1016 2058 sgarg
1017 2121 sgarg
          }
1018
          else if (ldapBase.startsWith(attrName + "=" + attrValue)) {
1019
            trees.put(ldapBase, ldapUrl);
1020
          }
1021
          else {
1022 2129 sgarg
            if (sr.isRelative()) {
1023 2121 sgarg
              trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
1024 2130 sgarg
            }
1025
            else {
1026 2121 sgarg
              String referenceURL = sr.getName();
1027 2129 sgarg
              referenceURL = referenceURL.substring(0,
1028
                  referenceURL.lastIndexOf("/") + 1);
1029
              trees.put(attrName + "=" + attrValue + "," + ldapBase,
1030
                        referenceURL);
1031 730 bojilova
            }
1032 2121 sgarg
1033 504 jones
          }
1034
        }
1035 2121 sgarg
      }
1036 730 bojilova
1037 2121 sgarg
      // Close the context when we're done
1038
      ctx.close();
1039 730 bojilova
1040 2121 sgarg
    }
1041
    catch (NamingException e) {
1042 2666 sgarg
      logMetacat.error("Problem getting subtrees in AuthLdap.getSubtrees:"
1043 2589 sgarg
                        + e);
1044 730 bojilova
      throw new ConnectException(
1045 2121 sgarg
          "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
1046 504 jones
    }
1047
1048 730 bojilova
    return trees;
1049 504 jones
  }
1050
1051
  /**
1052 730 bojilova
   * Get all groups and users from authentication scheme.
1053 725 bojilova
   * The output is formatted in XML.
1054 730 bojilova
   * @param user the user which requests the information
1055
   * @param password the user's password
1056 725 bojilova
   */
1057 3156 cjones
  public String getPrincipals(String user, String password) throws
1058
    ConnectException {
1059 725 bojilova
    StringBuffer out = new StringBuffer();
1060 2559 sgarg
1061 2058 sgarg
    out.append("<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n");
1062 730 bojilova
    out.append("<principals>\n");
1063 2058 sgarg
1064 730 bojilova
    /*
1065 2058 sgarg
     * get all subtrees first in the current dir context
1066 730 bojilova
     * and then the Metacat users under them
1067
     */
1068 2121 sgarg
    Hashtable subtrees = getSubtrees(user, password, this.ldapUrl,
1069
                                     this.ldapBase);
1070 2058 sgarg
1071 2447 sgarg
    Enumeration keyEnum = subtrees.keys();
1072
    while (keyEnum.hasMoreElements()) {
1073
      this.ldapBase = (String) keyEnum.nextElement();
1074 2121 sgarg
      this.ldapUrl = (String) subtrees.get(ldapBase);
1075 2058 sgarg
1076 2129 sgarg
      /*
1077
       * code to get the organization name from ldapBase
1078
       */
1079 2116 sgarg
      String orgName = this.ldapBase;
1080 2130 sgarg
      if (orgName.startsWith("[")) {
1081 2129 sgarg
        // if orgName starts with [ then it is a referral URL...
1082
        // (see code in getSubtress)
1083
        // hence orgName can be retrieved  by getting the string between
1084
        // 'o=' and ']'
1085
        // also the string between [ and ] needs to be striped out from
1086
        // this.ldapBase
1087
        this.ldapBase = orgName.substring(orgName.indexOf("]") + 1);
1088
        if (orgName != null && orgName.indexOf("o=") > -1) {
1089
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
1090
          orgName = orgName.substring(0, orgName.indexOf("]"));
1091
        }
1092 2130 sgarg
      }
1093
      else {
1094 2129 sgarg
        // else it is not referral
1095
        // hence orgName can be retrieved  by getting the string between
1096
        // 'o=' and ','
1097
        if (orgName != null && orgName.indexOf("o=") > -1) {
1098
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
1099
          if (orgName.indexOf(",") > -1) {
1100
            orgName = orgName.substring(0, orgName.indexOf(","));
1101
          }
1102
        }
1103 2121 sgarg
      }
1104
1105 2058 sgarg
      out.append("  <authSystem URI=\"" +
1106 2121 sgarg
                 this.ldapUrl + this.ldapBase + "\" organization=\"" + orgName +
1107
                 "\">\n");
1108 730 bojilova
1109
      // get all groups for directory context
1110 2058 sgarg
      String[][] groups = getGroups(user, password);
1111
      String[][] users = getUsers(user, password);
1112
      int userIndex = 0;
1113 730 bojilova
1114
      // for the groups and users that belong to them
1115 2121 sgarg
      if (groups != null && groups.length > 0) {
1116
        for (int i = 0; i < groups.length; i++) {
1117 730 bojilova
          out.append("    <group>\n");
1118 2058 sgarg
          out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
1119
          out.append("      <description>" + groups[i][1] + "</description>\n");
1120 2121 sgarg
          String[] usersForGroup = getUsers(user, password, groups[i][0]);
1121
          for (int j = 0; j < usersForGroup.length; j++) {
1122 2559 sgarg
1123 2058 sgarg
            userIndex = searchUser(usersForGroup[j], users);
1124 730 bojilova
            out.append("      <user>\n");
1125 2058 sgarg
1126 2121 sgarg
            if (userIndex < 0) {
1127 2095 sgarg
              out.append("        <username>" + usersForGroup[j] +
1128
                         "</username>\n");
1129 2121 sgarg
            }
1130
            else {
1131 2130 sgarg
              out.append("        <username>" + users[userIndex][0] +
1132 2121 sgarg
                         "</username>\n");
1133 2130 sgarg
              out.append("        <name>" + users[userIndex][1] + "</name>\n");
1134
              out.append("        <organization>" + users[userIndex][2] +
1135 2121 sgarg
                         "</organization>\n");
1136 2130 sgarg
              if (users[userIndex][3].compareTo("null") != 0) {
1137
                out.append("      <organizationUnitName>" + users[userIndex][3] +
1138
                           "</organizationUnitName>\n");
1139
              }
1140
              out.append("        <email>" + users[userIndex][4] + "</email>\n");
1141 2058 sgarg
            }
1142
1143 730 bojilova
            out.append("      </user>\n");
1144
          }
1145
          out.append("    </group>\n");
1146
        }
1147
      }
1148 2058 sgarg
1149 2130 sgarg
      // for the users not belonging to any grou8p
1150 2121 sgarg
      for (int j = 0; j < users.length; j++) {
1151 725 bojilova
          out.append("    <user>\n");
1152 2058 sgarg
          out.append("      <username>" + users[j][0] + "</username>\n");
1153
          out.append("      <name>" + users[j][1] + "</name>\n");
1154 2130 sgarg
          out.append("      <organization>" + users[j][2] +
1155
                     "</organization>\n");
1156
          if (users[j][3].compareTo("null") != 0) {
1157
            out.append("      <organizationUnitName>" + users[j][3] +
1158
                       "</organizationUnitName>\n");
1159
          }
1160
          out.append("      <email>" + users[j][4] + "</email>\n");
1161 725 bojilova
          out.append("    </user>\n");
1162
      }
1163 2058 sgarg
1164 730 bojilova
      out.append("  </authSystem>\n");
1165 725 bojilova
    }
1166
    out.append("</principals>");
1167
    return out.toString();
1168
  }
1169
1170
  /**
1171 2058 sgarg
   * Method for getting index of user DN in User info array
1172
   */
1173 2121 sgarg
  int searchUser(String user, String userGroup[][]) {
1174
    for (int j = 0; j < userGroup.length; j++) {
1175
      if (user.compareTo(userGroup[j][0]) == 0) {
1176 2058 sgarg
        return j;
1177
      }
1178
    }
1179
    return -1;
1180
  }
1181
1182
  /**
1183 503 bojilova
   * Test method for the class
1184
   */
1185
  public static void main(String[] args) {
1186
1187 504 jones
    // Provide a user, such as: "Matt Jones", or "jones"
1188 503 bojilova
    String user = args[0];
1189
    String password = args[1];
1190
1191 2666 sgarg
    logMetacat.warn("Creating session...");
1192 503 bojilova
    AuthLdap authservice = new AuthLdap();
1193 2666 sgarg
    logMetacat.warn("Session exists...");
1194 2058 sgarg
1195 503 bojilova
    boolean isValid = false;
1196
    try {
1197 2666 sgarg
      logMetacat.warn("Authenticating...");
1198 503 bojilova
      isValid = authservice.authenticate(user, password);
1199
      if (isValid) {
1200 2666 sgarg
    	  logMetacat.warn("Authentication successful for: " + user);
1201 2121 sgarg
      }
1202
      else {
1203 2666 sgarg
        logMetacat.warn("Authentication failed for: " + user);
1204 503 bojilova
      }
1205 725 bojilova
1206 871 jones
      // Get attributes for the user
1207 503 bojilova
      if (isValid) {
1208 2666 sgarg
        logMetacat.info("\nGetting attributes for user....");
1209 991 tao
        HashMap userInfo = authservice.getAttributes(user, password, user);
1210 503 bojilova
        // Print all of the attributes
1211 2121 sgarg
        Iterator attList = (Iterator) ( ( (Set) userInfo.keySet()).iterator());
1212 503 bojilova
        while (attList.hasNext()) {
1213 2121 sgarg
          String att = (String) attList.next();
1214
          Vector values = (Vector) userInfo.get(att);
1215 503 bojilova
          Iterator attvalues = values.iterator();
1216
          while (attvalues.hasNext()) {
1217 2121 sgarg
            String value = (String) attvalues.next();
1218 2666 sgarg
            logMetacat.warn(att + ": " + value);
1219 503 bojilova
          }
1220
        }
1221 871 jones
      }
1222 723 bojilova
1223 871 jones
      // get the groups
1224
      if (isValid) {
1225 2666 sgarg
        logMetacat.warn("\nGetting all groups....");
1226 2058 sgarg
        String[][] groups = authservice.getGroups(user, password);
1227 2666 sgarg
        logMetacat.info("Groups found: " + groups.length);
1228 2121 sgarg
        for (int i = 0; i < groups.length; i++) {
1229 2666 sgarg
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1230 871 jones
        }
1231 503 bojilova
      }
1232 725 bojilova
1233 871 jones
      // get the groups for the user
1234
      String savedGroup = null;
1235
      if (isValid) {
1236 2666 sgarg
        logMetacat.warn("\nGetting groups for user....");
1237 2058 sgarg
        String[][] groups = authservice.getGroups(user, password, user);
1238 2666 sgarg
        logMetacat.info("Groups found: " + groups.length);
1239 2121 sgarg
        for (int i = 0; i < groups.length; i++) {
1240 2666 sgarg
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1241 2121 sgarg
          savedGroup = groups[i][0];
1242 871 jones
        }
1243
      }
1244
1245
      // get the users for a group
1246
      if (isValid) {
1247 2666 sgarg
        logMetacat.warn("\nGetting users for group....");
1248
        logMetacat.info("Group: " + savedGroup);
1249 871 jones
        String[] users = authservice.getUsers(user, password, savedGroup);
1250 2666 sgarg
        logMetacat.info("Users found: " + users.length);
1251 2121 sgarg
        for (int i = 0; i < users.length; i++) {
1252 2666 sgarg
          logMetacat.warn("User " + i + ": " + users[i]);
1253 871 jones
        }
1254
      }
1255
1256
      // get all users
1257
      if (isValid) {
1258 2666 sgarg
        logMetacat.warn("\nGetting all users ....");
1259 2058 sgarg
        String[][] users = authservice.getUsers(user, password);
1260 2666 sgarg
        logMetacat.info("Users found: " + users.length);
1261 2058 sgarg
1262 871 jones
      }
1263 873 jones
1264 726 bojilova
      // get the whole list groups and users in XML format
1265 725 bojilova
      if (isValid) {
1266 2666 sgarg
        logMetacat.warn("\nTrying principals....");
1267 730 bojilova
        authservice = new AuthLdap();
1268 725 bojilova
        String out = authservice.getPrincipals(user, password);
1269 802 bojilova
        java.io.File f = new java.io.File("principals.xml");
1270 725 bojilova
        java.io.FileWriter fw = new java.io.FileWriter(f);
1271
        java.io.BufferedWriter buff = new java.io.BufferedWriter(fw);
1272
        buff.write(out);
1273
        buff.flush();
1274
        buff.close();
1275
        fw.close();
1276 2666 sgarg
        logMetacat.warn("\nFinished getting principals.");
1277 725 bojilova
      }
1278 873 jones
1279 2121 sgarg
    }
1280
    catch (ConnectException ce) {
1281 2666 sgarg
      logMetacat.error(ce.getMessage());
1282 2121 sgarg
    }
1283
    catch (java.io.IOException ioe) {
1284 2666 sgarg
      logMetacat.error("I/O Error writing to file principals.txt");
1285 503 bojilova
    }
1286
  }
1287 2058 sgarg
1288 934 tao
  /**
1289
   * This method will be called by start a thread.
1290
   * It can handle if a referral exception happend.
1291 2058 sgarg
   */
1292 503 bojilova
}