Project

General

Profile

« Previous | Next » 

Revision 2058

Added by sgarg over 20 years ago

Made changes in these three files so that getPrincipal returns back more details about users and groups. Users now contain userDN, user Name and user Email. Groups now contain Group name and Group description. So some function calls which returned single string array earlier now returns multiple string arrays. AuthSession.java called one of these functions - so accordingly changes were made to fix that part of the code.

View differences:

src/edu/ucsb/nceas/metacat/AuthLdap.java
58 58
/**
59 59
 * An implementation of the AuthInterface interface that
60 60
 * allows Metacat to use the LDAP protocol for directory services.
61
 * The LDAP authentication service is used to determine if a user 
61
 * The LDAP authentication service is used to determine if a user
62 62
 * is authenticated, and whether they are a member of a particular group.
63 63
 */
64 64
public class AuthLdap implements AuthInterface, Runnable {
......
75 75
  ReferralException refExc;
76 76
  //String uid=null;
77 77

  
78
  /** 
78
  /**
79 79
   * Construct an AuthLdap
80 80
   */
81 81
  public AuthLdap() {
......
104 104
    String identifier = user;
105 105
    //get uid here.
106 106
    //uid=user.substring(0, user.indexOf(","));
107
  
107

  
108 108
    try {
109 109
        // Check the usename as passed in
110 110
        authenticated = ldapAuthenticate(identifier, password);
......
138 138
            }
139 139
            //authenticated = ldapAuthenticate(identifier, password);
140 140
        }
141
     
141

  
142 142
    } catch (NullPointerException e) {
143 143
      util.debugMessage("NullPointerException b' password is null", 30);
144
      util.debugMessage("NullPointerException while authenticating in " + 
144
      util.debugMessage("NullPointerException while authenticating in " +
145 145
                        "AuthLdap.authenticate: " + e, 30);
146 146
      throw new ConnectException(
147
      "NullPointerException while authenticating in " + 
147
      "NullPointerException while authenticating in " +
148 148
                        "AuthLdap.authenticate: " + e);
149 149
    } catch (NamingException e) {
150
      util.debugMessage("Naming exception while authenticating in " + 
150
      util.debugMessage("Naming exception while authenticating in " +
151 151
                        "AuthLdap.authenticate: " + e, 30);
152 152
      e.printStackTrace();
153 153
    } catch (Exception e) {
......
166 166
  private boolean ldapAuthenticate(String identifier, String password)
167 167
            throws ConnectException, NamingException, NullPointerException
168 168
  {
169
      return ldapAuthenticate(identifier, password, 
169
      return ldapAuthenticate(identifier, password,
170 170
                              this.ldapsUrl, this.ldapBase);
171 171
  }
172 172

  
......
184 184
    double totStartTime = System.currentTimeMillis();
185 185
    boolean authenticated = false;
186 186
    if (identifier != null && !password.equals("")) {
187
    
187

  
188 188
        //Pass the username and password to run() method
189 189
        userName=identifier;
190 190
        userPassword=password;
191 191
        // Identify service provider to use
192 192
        Hashtable env = new Hashtable(11);
193
        env.put(Context.INITIAL_CONTEXT_FACTORY, 
193
        env.put(Context.INITIAL_CONTEXT_FACTORY,
194 194
              "com.sun.jndi.ldap.LdapCtxFactory");
195 195
        env.put(Context.REFERRAL, "throw");
196 196
        env.put(Context.PROVIDER_URL, directoryUrl + searchBase);
......
233 233

  
234 234
            Thread t = new Thread(this);
235 235
            t.start();
236
            Thread.sleep(5000); //this is a manual override of ldap's 
236
            Thread.sleep(5000); //this is a manual override of ldap's
237 237
                                //hideously long time out period.
238 238
            util.debugMessage("Awake after 5 seconds.", 35);
239 239
            if (referralContext == null) {
......
246 246
            authenticated = false;
247 247
          }
248 248
        }
249
    } else { 
249
    } else {
250 250
        util.debugMessage("User not found", 30);
251 251
    }
252 252
    double totStopTime = System.currentTimeMillis();
253
    util.debugMessage("total ldap authentication time: " + 
253
    util.debugMessage("total ldap authentication time: " +
254 254
                      (totStopTime - totStartTime)/1000 + " seconds", 35);
255 255
    return authenticated;
256 256
  }
257
  
258
  
259 257

  
258

  
259

  
260 260
  /**
261 261
   * Get the identifying name for a given userid or name.  This is the name
262 262
   * that is used in conjunction withthe LDAP BaseDN to create a
263 263
   * distinguished name (dn) for the record
264 264
   *
265 265
   * @param user the user for which the identifying name is requested
266
   * @returns String the identifying name for the user, 
266
   * @returns String the identifying name for the user,
267 267
   *          or null if not found
268 268
   */
269 269
  private String getIdentifyingName(String user, String ldapUrl,
......
279 279
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
280 280
    //    non-secure LDAP context; dn are publicly readable
281 281
    try {
282
      
282

  
283 283
      // Bind to the LDAP server, in order to search for the right
284 284
      // distinguished name (dn) based on userid (uid) or common name (cn)
285 285
      DirContext ctx = new InitialDirContext(env);
286 286
      SearchControls ctls = new SearchControls();
287 287
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
288
      // Search for the user id or name using the uid, then cn and sn 
288
      // Search for the user id or name using the uid, then cn and sn
289 289
      //attributes
290 290
      // If we find a record, determine the dn for the record
291 291
      // The following blocks need to be refactored into a subroutine
......
296 296
      int position = user.indexOf(",");
297 297
      String comp1 = user.substring(0, position);
298 298
      MetaCatUtil.debugMessage("First comp is: " + comp1, 35);
299
      String comp2 = user.substring(position+1, 
299
      String comp2 = user.substring(position+1,
300 300
                                    user.indexOf(",", position+1));
301 301
      MetaCatUtil.debugMessage("Second comp is: " + comp2, 35);
302 302

  
......
331 331
        if (answer.hasMore()) {
332 332
          SearchResult sr = (SearchResult)answer.next();
333 333
          identifier = sr.getName();
334
          if ( !sr.isRelative() ) { 
334
          if ( !sr.isRelative() ) {
335 335
            this.ldapUrl = identifier.substring(0,
336 336
                                                identifier.lastIndexOf("/")+1);
337 337
            this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
......
350 350
      if (answer.hasMore()) {
351 351
        SearchResult sr = (SearchResult)answer.next();
352 352
        identifier = sr.getName();
353
        if ( !sr.isRelative() ) { 
353
        if ( !sr.isRelative() ) {
354 354
          this.ldapUrl = identifier.substring(0,identifier.lastIndexOf("/")+1);
355 355
          this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
356 356
          identifier = identifier.substring(identifier.lastIndexOf("/")+1,
......
366 366
        if (answer2.hasMore()) {
367 367
          SearchResult sr = (SearchResult)answer2.next();
368 368
          identifier = sr.getName();
369
          if ( !sr.isRelative() ) { 
369
          if ( !sr.isRelative() ) {
370 370
            this.ldapUrl = identifier.substring(0,
371 371
                                                identifier.lastIndexOf("/")+1);
372 372
            this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
......
383 383
          if (answer3.hasMore()) {
384 384
            SearchResult sr = (SearchResult)answer3.next();
385 385
            identifier = sr.getName();
386
            if ( !sr.isRelative() ) { 
386
            if ( !sr.isRelative() ) {
387 387
              this.ldapUrl = identifier.substring(0,
388 388
                                                identifier.lastIndexOf("/")+1);
389 389
              this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
......
412 412
   * @param password the password for authenticating against the service
413 413
   * @returns string array of all of the user names
414 414
   */
415
  public String[] getUsers(String user, String password) 
415
  public String[][] getUsers(String user, String password)
416 416
         throws ConnectException
417 417
  {
418
    String[] users = null;
418
    String[][] users = null;
419 419

  
420 420
    // Identify service provider to use
421 421
    Hashtable env = new Hashtable(11);
422
    env.put(Context.INITIAL_CONTEXT_FACTORY, 
422
    env.put(Context.INITIAL_CONTEXT_FACTORY,
423 423
            "com.sun.jndi.ldap.LdapCtxFactory");
424 424
    env.put(Context.REFERRAL, referral);
425 425
    env.put(Context.PROVIDER_URL, ldapUrl);
426
 
426

  
427 427
    try {
428 428

  
429 429
        // Create the initial directory context
......
432 432
        // Specify the attributes to match.
433 433
        // Users are objects that have the attribute objectclass=InetOrgPerson.
434 434
        SearchControls ctls = new SearchControls();
435
        String[] attrIDs = {"dn"};
435
        String[] attrIDs = {"dn", "cn", "mail"};
436 436
        ctls.setReturningAttributes(attrIDs);
437 437
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
438 438
        //ctls.setCountLimit(1000);
439 439
        String filter = "(objectClass=inetOrgPerson)";
440 440
        NamingEnumeration enum = ctx.search(ldapBase, filter, ctls);
441
        
441

  
442 442
        // Store the users in a vector
443 443
        Vector uvec = new Vector();
444
        Vector uname = new Vector();
445
        Vector umail = new Vector();
446
        Attributes tempAttr = null;
444 447
        try {
445 448
            while (enum.hasMore()) {
446 449
                SearchResult sr = (SearchResult)enum.next();
450
                tempAttr = sr.getAttributes();
451

  
452
                if((tempAttr.get("cn")+"").startsWith("cn: ")){
453
                  uname.add( (tempAttr.get("cn") + "").substring(4));
454
                } else {
455
                  uname.add( tempAttr.get("cn") + "");
456
                }
457

  
458
                if((tempAttr.get("mail")+"").startsWith("mail: ")){
459
                  umail.add((tempAttr.get("mail") + "").substring(6));
460
                } else {
461
                  umail.add(tempAttr.get("mail") + "");
462
                }
463

  
447 464
                uvec.add(sr.getName()+","+ldapBase);
448 465
            }
449 466
        } catch (SizeLimitExceededException slee) {
......
452 469
        }
453 470

  
454 471
        // initialize users[]; fill users[]
455
        users = new String[uvec.size()];
472
        users = new String[uvec.size()][3];
456 473
        for (int i=0; i < uvec.size(); i++) {
457
          users[i] = (String)uvec.elementAt(i); 
474
          users[i][0] = (String)uvec.elementAt(i);
475
          users[i][1] = (String)uname.elementAt(i);
476
          users[i][2] = (String)umail.elementAt(i);
458 477
        }
459 478

  
460 479
        // Close the context when we're done
......
478 497
   * @param group the group whose user list should be returned
479 498
   * @returns string array of the user names belonging to the group
480 499
   */
481
  public String[] getUsers(String user, String password, String group) 
500
  public String[] getUsers(String user, String password, String group)
482 501
         throws ConnectException
483 502
  {
484 503
    String[] users = null;
485 504

  
486 505
    // Identify service provider to use
487 506
    Hashtable env = new Hashtable(11);
488
    env.put(Context.INITIAL_CONTEXT_FACTORY, 
507
    env.put(Context.INITIAL_CONTEXT_FACTORY,
489 508
            "com.sun.jndi.ldap.LdapCtxFactory");
490 509
    env.put(Context.REFERRAL, referral);
491 510
    env.put(Context.PROVIDER_URL, ldapUrl);
......
504 523
        try {
505 524
            for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
506 525
                Attribute attr = (Attribute)ae.next();
507
                for (NamingEnumeration e = attr.getAll(); 
526
                for (NamingEnumeration e = attr.getAll();
508 527
                     e.hasMore();
509
                     uvec.add(e.next()) 
528
                     uvec.add(e.next())
510 529
                    );
511 530
            }
512 531
        } catch (SizeLimitExceededException slee) {
......
517 536
        // initialize users[]; fill users[]
518 537
        users = new String[uvec.size()];
519 538
        for (int i=0; i < uvec.size(); i++) {
520
          users[i] = (String)uvec.elementAt(i); 
539
          users[i] = (String)uvec.elementAt(i);
521 540
        }
522 541

  
523 542
        // Close the context when we're done
......
540 559
   * @param password the password for authenticating against the service
541 560
   * @returns string array of the group names
542 561
   */
543
  public String[] getGroups(String user, String password) 
562
  public String[][] getGroups(String user, String password)
544 563
         throws ConnectException
545 564
  {
546 565
      return getGroups(user, password, null);
......
554 573
   * @param foruser the user whose group list should be returned
555 574
   * @returns string array of the group names
556 575
   */
557
  public String[] getGroups(String user, String password, String foruser) 
576
  public String[][] getGroups(String user, String password, String foruser)
558 577
         throws ConnectException
559 578
  {
560 579
    Vector uvec = new Vector();
580
    Vector desc = new Vector();
581
    Attributes tempAttr = null;
582

  
561 583
    //Pass the username and password to run() method
562 584
    userName=user;
563 585
    userPassword=password;
564 586
    // Identify service provider to use
565
    env.put(Context.INITIAL_CONTEXT_FACTORY, 
587
    env.put(Context.INITIAL_CONTEXT_FACTORY,
566 588
            "com.sun.jndi.ldap.LdapCtxFactory");
567 589
    env.put(Context.REFERRAL, "throw");
568 590
    env.put(Context.PROVIDER_URL, ldapUrl);
......
570 592
        // Create the initial directory context
571 593
        DirContext ctx = new InitialDirContext(env);
572 594
        // Specify the ids of the attributes to return
573
        String[] attrIDs = {"cn"};
595
        String[] attrIDs = {"cn", "description"};
574 596
        // Specify the attributes to match.
575 597
        // Groups are objects with attribute objectclass=groupofuniquenames.
576 598
        // and have attribute uniquemember: uid=foruser,ldapbase.
577 599
        SearchControls ctls = new SearchControls();
578 600
        ctls.setReturningAttributes(attrIDs);
579 601
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
580
        
602

  
581 603
        String filter = null;
582 604
        String gfilter = "(objectClass=groupOfUniqueNames)";
583 605
        if (null == foruser) {
......
591 613
        // Print the groups
592 614
        MetaCatUtil.debugMessage("getting group results.", 50);
593 615
        while (enum.hasMore()) {
594
          SearchResult sr = (SearchResult)enum.next();          
616
          SearchResult sr = (SearchResult)enum.next();
617
          tempAttr = sr.getAttributes();
618

  
619
          if((tempAttr.get("description")+"").startsWith("description: ")){
620
            desc.add( (tempAttr.get("description") + "").substring(13));
621
          } else {
622
            desc.add( tempAttr.get("description") + "");
623
          }
624

  
595 625
          uvec.add(sr.getName()+","+ldapBase);
596
          MetaCatUtil.debugMessage("group " + sr.getName() + 
626
          MetaCatUtil.debugMessage("group " + sr.getName() +
597 627
                                  " added to Group vector", 35);
598 628
        }
599 629
        // Close the context when we're done
600 630
        ctx.close();
601 631

  
602
    } 
603
    catch (ReferralException re) 
632
    }
633
    catch (ReferralException re)
604 634
    {
605 635
      refExc = re;
606 636
      Thread t = new Thread(new GetGroup());
......
621 651
      if (referralContext == null)
622 652
      {
623 653
        util.debugMessage("thread timed out...returning groups: " + uvec.toString(), 35);
624
        String groups[] = new String[uvec.size()];
654
        String groups[][] = new String[uvec.size()][2];
625 655
        for(int i=0; i<uvec.size(); i++)
626 656
        {
627
          groups[i] = (String)uvec.elementAt(i);
657
          groups[i][0] = (String)uvec.elementAt(i);
658
          groups[i][1] = (String)desc.elementAt(i);
628 659
        }
629 660
        t.interrupt();
630 661
        return groups;
631 662
      }
632 663
      DirContext dc = (DirContext)referralContext;
633
      String[] attrIDs = {"cn"};
664
      String[] attrIDs = {"cn", "description"};
634 665
      // Specify the attributes to match.
635 666
      // Groups are objects with attribute objectclass=groupofuniquenames.
636 667
      // and have attribute uniquemember: uid=foruser,ldapbase.
637 668
      SearchControls ctls = new SearchControls();
638 669
      ctls.setReturningAttributes(attrIDs);
639 670
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
640
      
671

  
641 672
      String filter = null;
642 673
      String gfilter = "(objectClass=groupOfUniqueNames)";
643 674
      if (null == foruser) {
......
645 676
      } else {
646 677
          filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
647 678
      }
648
      
679

  
649 680
      try
650 681
      {
651 682
        NamingEnumeration enum = dc.search(ldapBase, filter, ctls);
652 683
        // Print the groups
653 684
        while (enum.hasMore()) {
654 685
          SearchResult sr = (SearchResult)enum.next();
686
          tempAttr = sr.getAttributes();
687

  
688
          if((tempAttr.get("description")+"").startsWith("description: ")){
689
            desc.add( (tempAttr.get("description") + "").substring(13));
690
          } else {
691
            desc.add( tempAttr.get("description") + "");
692
          }
693

  
655 694
          uvec.add(sr.getName()+","+ldapBase);
656 695
        }
657
        
696

  
658 697
        referralContext.close();
659 698
        dc.close();
660 699
      }
661 700
      catch(NamingException ne)
662 701
      {
663
        MetaCatUtil.debugMessage("Naming Exception in AuthLdap.getGroups", 30);
702
        MetaCatUtil.debugMessage("Naming Exception in AuthLdap.getGroups" + ne.getExplanation() + ne.getMessage(), 30);
664 703
      }
665 704
    } catch (NamingException e) {
666 705
      e.printStackTrace(System.err);
667
      String groups[] = new String[uvec.size()];
706
      String groups[][] = new String[uvec.size()][2];
668 707
      for(int i=0; i<uvec.size(); i++)
669 708
      {
670
        groups[i] = (String)uvec.elementAt(i);
709
        groups[i][0] = (String)uvec.elementAt(i);
710
        groups[i][1] = (String)desc.elementAt(i);
671 711
      }
672 712
      return groups;
673 713
       /*throw new ConnectException(
674 714
      "Problem getting groups for a user in AuthLdap.getGroups:" + e);*/
675
    } 
676
    
677
    MetaCatUtil.debugMessage("The user is in the following groups: " + 
715
    }
716

  
717
    MetaCatUtil.debugMessage("The user is in the following groups: " +
678 718
                              uvec.toString(), 35);
679
    String groups[] = new String[uvec.size()];
719
    String groups[][] = new String[uvec.size()][2];
680 720
    for(int i=0; i<uvec.size(); i++)
681 721
    {
682
      groups[i] = (String)uvec.elementAt(i);
722
      groups[i][0] = (String)uvec.elementAt(i);
723
      groups[i][1] = (String)desc.elementAt(i);
683 724
    }
684 725
    return groups;
685 726
  }
......
690 731
   * @param foruser the user for which the attribute list is requested
691 732
   * @returns HashMap a map of attribute name to a Vector of values
692 733
   */
693
  public HashMap getAttributes(String foruser) 
734
  public HashMap getAttributes(String foruser)
694 735
         throws ConnectException
695 736
  {
696 737
    return getAttributes(null, null, foruser);
......
704 745
   * @param foruser the user whose attributes should be returned
705 746
   * @returns HashMap a map of attribute name to a Vector of values
706 747
   */
707
  public HashMap getAttributes(String user, String password, String foruser) 
748
  public HashMap getAttributes(String user, String password, String foruser)
708 749
         throws ConnectException
709 750
  {
710 751
    HashMap attributes = new HashMap();
711 752
    String ldapUrl = this.ldapUrl;
712 753
    String ldapBase = this.ldapBase;
713 754
    String userident = foruser;
714
   
755

  
715 756
    // Identify service provider to use
716 757
    Hashtable env = new Hashtable(11);
717
    env.put(Context.INITIAL_CONTEXT_FACTORY, 
758
    env.put(Context.INITIAL_CONTEXT_FACTORY,
718 759
        "com.sun.jndi.ldap.LdapCtxFactory");
719 760
    env.put(Context.REFERRAL, referral);
720 761
    env.put(Context.PROVIDER_URL, ldapUrl);
721 762

  
722 763
    try {
723
      
764

  
724 765
      // Create the initial directory context
725 766
      DirContext ctx = new InitialDirContext(env);
726
        
727
      // Ask for all attributes of the user 
767

  
768
      // Ask for all attributes of the user
728 769
      //Attributes attrs = ctx.getAttributes(userident);
729 770
      Attributes attrs = ctx.getAttributes(foruser);
730
 
771

  
731 772
      // Print all of the attributes
732 773
      NamingEnumeration en = attrs.getAll();
733 774
      while (en.hasMore()) {
......
741 782
        }
742 783
        attributes.put(attName, values);
743 784
      }
744
  
785

  
745 786
      // Close the context when we're done
746 787
      ctx.close();
747 788
    } catch (NamingException e) {
748
      util.debugMessage("Problem getting attributes in " + 
789
      util.debugMessage("Problem getting attributes in " +
749 790
              "AuthLdap.getAttributes:" + e, 35);
750 791
      throw new ConnectException(
751 792
      "Problem getting attributes in AuthLdap.getAttributes:" + e);
......
756 797

  
757 798
  /**
758 799
   * Get list of all subtrees holding Metacat's groups and users
759
   * starting from the Metacat LDAP root, 
800
   * starting from the Metacat LDAP root,
760 801
   * i.e. ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
761 802
   */
762 803
  private Hashtable getSubtrees(String user, String password,
......
767 808

  
768 809
    // Identify service provider to use
769 810
    Hashtable env = new Hashtable(11);
770
    env.put(Context.INITIAL_CONTEXT_FACTORY, 
811
    env.put(Context.INITIAL_CONTEXT_FACTORY,
771 812
            "com.sun.jndi.ldap.LdapCtxFactory");
772 813
    env.put(Context.REFERRAL, referral);
773 814
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
......
782 823
        SearchControls ctls = new SearchControls();
783 824
        ctls.setReturningAttributes(attrIDs);
784 825
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
785
          
826

  
786 827
        // Specify the attributes to match.
787 828
        // Subtrees from the main server are found as objects with attribute
788 829
        // objectclass=organization or objectclass=referral to the subtree
......
801 842
            Attribute attr = (Attribute)enum1.next();
802 843
            String attrValue = (String)attr.get();
803 844
            String attrName = (String)attr.getID();
804
 
845

  
805 846
            if ( enum1.hasMore() ) {
806 847
              attr = (Attribute)enum1.next();
807 848
              String refValue = (String)attr.get();
......
813 854
                trees.put(refName + "=" + refValue + "," + ldapBase,
814 855
                         attrValue.substring(0,attrValue.lastIndexOf("/")+1) );
815 856
              }
816
 
857

  
817 858
            } else if ( ldapBase.startsWith(attrName + "=" + attrValue) ) {
818 859
                trees.put(ldapBase, ldapUrl);
819
            } else {              
820
                trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);               
860
            } else {
861
                trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
821 862
            }
822 863
          }
823 864
        }
......
826 867
        ctx.close();
827 868

  
828 869
    } catch (NamingException e) {
829
      util.debugMessage("Problem getting subtrees in AuthLdap.getSubtrees:" 
870
      util.debugMessage("Problem getting subtrees in AuthLdap.getSubtrees:"
830 871
                        + e, 30);
831 872
      throw new ConnectException(
832 873
      "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
......
846 887
  {
847 888
    StringBuffer out = new StringBuffer();
848 889
    Vector usersIn = new Vector();
849
    
850
    out.append("<?xml version=\"1.0\"?>\n");
890

  
891
    out.append("<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n");
851 892
    out.append("<principals>\n");
852
    
893

  
853 894
    /*
854
     * get all subtrees first in the current dir context 
895
     * get all subtrees first in the current dir context
855 896
     * and then the Metacat users under them
856 897
     */
857 898
    Hashtable subtrees = getSubtrees(user,password,this.ldapUrl,this.ldapBase);
858
    
899

  
859 900
    Enumeration enum = subtrees.keys();
860 901
    while ( enum.hasMoreElements() ) {
861 902
      this.ldapBase = (String)enum.nextElement();
862 903
      this.ldapUrl = (String)subtrees.get(ldapBase);
863
      
864
      out.append("  <authSystem URI=\"" + 
904

  
905
      out.append("  <authSystem URI=\"" +
865 906
                 this.ldapUrl + this.ldapBase + "\">\n");
866 907

  
867 908
      // get all groups for directory context
868
      String[] groups = getGroups(user, password);
909
      String[][] groups = getGroups(user, password);
910
      String[][] users = getUsers(user, password);
911
      int userIndex = 0;
869 912

  
870 913
      // for the groups and users that belong to them
871 914
      if ( groups!=null && groups.length > 0 ) {
872 915
        for (int i=0; i < groups.length; i++ ) {
873 916
          out.append("    <group>\n");
874
          out.append("      <groupname>" + groups[i] + "</groupname>\n");
875
          String[] usersForGroup = getUsers(user,password,groups[i]);
917
          out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
918
          out.append("      <description>" + groups[i][1] + "</description>\n");
919
          String[] usersForGroup = getUsers(user,password,groups[i][0]);
876 920
          for (int j=0; j < usersForGroup.length; j++ ) {
877 921
            usersIn.addElement(usersForGroup[j]);
922

  
923
            userIndex = searchUser(usersForGroup[j], users);
878 924
            out.append("      <user>\n");
879
            out.append("        <username>" + usersForGroup[j] + 
880
                        "</username>\n");
925

  
926
            if(userIndex < 0){
927
              out.append("        <userdn>" + usersForGroup[j] +
928
                         "</userdn>\n");
929
            } else {
930
              out.append("      <username>" + users[userIndex][0] + "</username>\n");
931
              out.append("      <name>" + users[userIndex][1] + "</name>\n");
932
              out.append("      <email>" + users[userIndex][2] + "</email>\n");
933
            }
934

  
881 935
            out.append("      </user>\n");
882 936
          }
883 937
          out.append("    </group>\n");
884 938
        }
885 939
      }
940

  
886 941
      // for the users not belonging to any group
887
      String[] users = getUsers(user, password);
888 942
      for (int j=0; j < users.length; j++ ) {
889
        if ( !usersIn.contains(users[j]) ) {
943
        if ( !usersIn.contains(users[j][0]) ) {
890 944
          out.append("    <user>\n");
891
          out.append("      <username>" + users[j] + "</username>\n");
945
          out.append("      <username>" + users[j][0] + "</username>\n");
946
          out.append("      <name>" + users[j][1] + "</name>\n");
947
          out.append("      <email>" + users[j][2] + "</email>\n");
892 948
          out.append("    </user>\n");
893 949
        }
894 950
      }
895
    
951

  
896 952
      out.append("  </authSystem>\n");
897 953
      if ( !usersIn.isEmpty() ) {
898 954
        usersIn.removeAllElements();
899 955
        usersIn.trimToSize();
900 956
      }
901
    
957

  
902 958
    }
903 959
    out.append("</principals>");
904 960
    return out.toString();
905 961
  }
906 962

  
963

  
907 964
  /**
965
   * Method for getting index of user DN in User info array
966
   */
967
  int searchUser(String user, String userGroup[][]){
968
    for (int j=0; j < userGroup.length; j++ ) {
969
      if (user.compareTo(userGroup[j][0]) == 0){
970
        return j;
971
      }
972
    }
973
    return -1;
974
  }
975

  
976
  /**
908 977
   * Test method for the class
909 978
   */
910 979
  public static void main(String[] args) {
......
916 985
    MetaCatUtil.debugMessage("Creating session...", 20);
917 986
    AuthLdap authservice = new AuthLdap();
918 987
    MetaCatUtil.debugMessage("Session exists...", 20);
919
                
988

  
920 989
    boolean isValid = false;
921 990
    try {
922 991
      MetaCatUtil.debugMessage("Authenticating...", 20);
......
947 1016
      // get the groups
948 1017
      if (isValid) {
949 1018
        MetaCatUtil.debugMessage("\nGetting all groups....", 20);
950
        String[] groups = authservice.getGroups(user, password);
1019
        String[][] groups = authservice.getGroups(user, password);
951 1020
        MetaCatUtil.debugMessage("Groups found: " + groups.length, 20);
952 1021
        for (int i=0; i < groups.length; i++) {
953
            MetaCatUtil.debugMessage("Group " + i + ": " + groups[i], 20);
1022
            MetaCatUtil.debugMessage("Group " + i + ": " + groups[i][0], 20);
954 1023
        }
955 1024
      }
956 1025

  
......
958 1027
      String savedGroup = null;
959 1028
      if (isValid) {
960 1029
        MetaCatUtil.debugMessage("\nGetting groups for user....", 20);
961
        String[] groups = authservice.getGroups(user, password, user);
1030
        String[][] groups = authservice.getGroups(user, password, user);
962 1031
        MetaCatUtil.debugMessage("Groups found: " + groups.length, 20);
963 1032
        for (int i=0; i < groups.length; i++) {
964
            MetaCatUtil.debugMessage("Group " + i + ": " + groups[i], 20);
965
            savedGroup = groups[i];
1033
            MetaCatUtil.debugMessage("Group " + i + ": " + groups[i][0], 20);
1034
            savedGroup = groups[i][0];
966 1035
        }
967 1036
      }
968 1037

  
......
980 1049
      // get all users
981 1050
      if (isValid) {
982 1051
        MetaCatUtil.debugMessage("\nGetting all users ....", 20);
983
        String[] users = authservice.getUsers(user, password);
1052
        String[][] users = authservice.getUsers(user, password);
984 1053
        MetaCatUtil.debugMessage("Users found: " + users.length, 20);
985
        
1054

  
986 1055
      }
987 1056

  
988 1057
      // get the whole list groups and users in XML format
......
1006 1075
      MetaCatUtil.debugMessage("I/O Error writing to file principals.txt", 20);
1007 1076
    }
1008 1077
  }
1009
  
1078

  
1010 1079
  /**
1011 1080
   * This method will be called by start a thread.
1012 1081
   * It can handle if a referral exception happend.
1013
   */ 
1082
   */
1014 1083
  public void run()
1015 1084
  {
1016 1085
    referralContext = null;
......
1022 1091
    while (moreReferrals)
1023 1092
    {
1024 1093
      try
1025
      {  
1094
      {
1026 1095
        //revise environment variable
1027 1096
        referralInfo=(String)refExc.getReferralInfo();
1028 1097
        util.debugMessage("Processing referral (pr0): ", 35);
......
1059 1128
      //catch a authentication exception
1060 1129
      catch (AuthenticationException ae)
1061 1130
      {
1062
        util.debugMessage("Error running referral handler thread (ae1): " + 
1131
        util.debugMessage("Error running referral handler thread (ae1): " +
1063 1132
                          ae.getMessage(), 20);
1064 1133
        //check if has another referral
1065 1134
        moreReferrals=refExc.skipReferral();
......
1069 1138
      //catch a naming exception
1070 1139
      catch (NamingException ne)
1071 1140
      {
1072
        util.debugMessage("Error running referral handler thread (ne1): " + 
1141
        util.debugMessage("Error running referral handler thread (ne1): " +
1073 1142
                          ne.getMessage(), 20);
1074 1143
        //check if has another referral
1075 1144
        moreReferrals=refExc.skipReferral();
1076 1145
        //don't get context
1077
        referralContext = null;		
1146
        referralContext = null;
1078 1147
      }
1079 1148
    }//while
1080 1149
  }//run()
1081
  
1150

  
1082 1151
  private class GetGroup implements Runnable
1083 1152
  {
1084 1153
    public void run()
......
1087 1156
      MetaCatUtil.debugMessage("getting groups context", 50);
1088 1157
      DirContext refDirContext=null;
1089 1158
      boolean moreReferrals=true;
1090
      //set a while loop is because we don't know if a referral excption 
1159
      //set a while loop is because we don't know if a referral excption
1091 1160
      //contains another referral exception
1092 1161
      while (moreReferrals)
1093 1162
      {
......
1098 1167
          refInfo = (String)refExc.getReferralInfo();
1099 1168
          if(refInfo != null)
1100 1169
          {
1101
            MetaCatUtil.debugMessage("Referral in thread to: " + 
1170
            MetaCatUtil.debugMessage("Referral in thread to: " +
1102 1171
                              refInfo.toString(), 40);
1103 1172
          }
1104 1173
          else
......
1108 1177
                                                  get(Context.PROVIDER_URL);
1109 1178
          }
1110 1179
          MetaCatUtil.debugMessage("refInfo: " + refInfo, 40);
1111
        
1112
          env.put(Context.INITIAL_CONTEXT_FACTORY, 
1180

  
1181
          env.put(Context.INITIAL_CONTEXT_FACTORY,
1113 1182
              "com.sun.jndi.ldap.LdapCtxFactory");
1114 1183
          env.put(Context.REFERRAL, "throw");
1115 1184
          env.put(Context.PROVIDER_URL, refInfo);
1116
        
1185

  
1117 1186
          MetaCatUtil.debugMessage("creating referralContext", 40);
1118 1187
          referralContext = new InitialDirContext(env);
1119 1188
          MetaCatUtil.debugMessage("referralContext created", 40);
......
1129 1198
        }
1130 1199
        catch (AuthenticationException ae)
1131 1200
        {
1132
          util.debugMessage("Error running referral handler thread (ae2): " + 
1201
          util.debugMessage("Error running referral handler thread (ae2): " +
1133 1202
                          ae.getMessage(), 50);
1134 1203
          //check if has another referral
1135 1204
          moreReferrals=refExc.skipReferral();
......
1138 1207
        }
1139 1208
        catch (NamingException ne)
1140 1209
        {
1141
          util.debugMessage("Error running referral handler thread (ne2): " + 
1210
          util.debugMessage("Error running referral handler thread (ne2): " +
1142 1211
                          ne.getMessage(), 50);
1143 1212
          //check if has another referral
1144 1213
          moreReferrals=refExc.skipReferral();
1145 1214
          //don't get context
1146
          referralContext = null;		
1215
          referralContext = null;
1147 1216
        }
1148 1217
      }//while
1149 1218
    }//run()
src/edu/ucsb/nceas/metacat/AuthSession.java
42 42
  private HttpSession session = null;
43 43
  private AuthInterface authService = null;
44 44
  private String statusMessage = null;
45
 
46
  /** 
45

  
46
  /**
47 47
   * Construct an AuthSession
48 48
   */
49 49
  public AuthSession() throws Exception {
......
53 53
    this.authClass = util.getOption("authclass");
54 54
    this.authService = (AuthInterface)createObject(authClass);
55 55
  }
56
  
56

  
57 57
  /**
58 58
   * Get the new session
59 59
   */
......
62 62
    return this.session;
63 63
  }
64 64

  
65
  /** 
66
   * determine if the credentials for this session are valid by 
65
  /**
66
   * determine if the credentials for this session are valid by
67 67
   * authenticating them using the authService configured for this session.
68 68
   *
69 69
   * @param request the request made from the client
70 70
   * @param username the username entered when login
71 71
   * @param password the password entered when login
72 72
   */
73
  public boolean authenticate(HttpServletRequest request, 
74
                              String username, String password)  { 
73
  public boolean authenticate(HttpServletRequest request,
74
                              String username, String password)  {
75 75
    String message = null;
76
    try { 
76
    try {
77 77
      if ( authService.authenticate(username, password) ) {
78
        String[] groups = authService.getGroups(username,password,username);
78

  
79
        // getGroups returns groupname along with their description.
80
        // hence groups[] is generated from groupsWithDescription[][]
81
        String[][] groupsWithDescription =
82
            authService.getGroups(username,password,username);
83
        String groups[] = new String[groupsWithDescription.length];
84

  
85
        for(int i=0; i<groupsWithDescription.length; i++){
86
          groups[i] = groupsWithDescription[i][0];
87
        }
88

  
79 89
        if(groups == null)
80 90
        {
81 91
          groups = new String[0];
......
85 95
        message = "Authentication successful for user: " + username;
86 96
        this.statusMessage = formatOutput("login", message, sessionId);
87 97
        return true;
88
      } else {  
98
      } else {
89 99
        message = "Authentication failed for user: " + username;
90 100
        this.statusMessage = formatOutput("unauth_login", message);
91 101
        return false;
92
      }    
102
      }
93 103
    } catch ( ConnectException ce ) {
94 104
      message = "Connection to the authentication service failed in " +
95 105
                "AuthSession.authenticate: " + ce.getMessage();
96 106
    } catch ( IllegalStateException ise ) {
97 107
      message = ise.getMessage();
98 108
    }
99
 
109

  
100 110
    this.statusMessage = formatOutput("error_login", message);
101 111
    return false;
102 112
  }
103 113

  
104 114
  /** Get new HttpSession and store username & password in it */
105
  private HttpSession createSession(HttpServletRequest request, 
115
  private HttpSession createSession(HttpServletRequest request,
106 116
                                 String username, String password,
107
                                 String[] groups)  
117
                                 String[] groups)
108 118
                      throws IllegalStateException {
109 119

  
110 120
    // get the current session object, create one if necessary
......
140 150
   * Get the message associated with authenticating this session. The
141 151
   * message is formatted in XML.
142 152
   */
143
  public String getMessage() 
153
  public String getMessage()
144 154
  {
145 155
    return this.statusMessage;
146 156
  }
......
157 167
    return authService.getPrincipals(user, password);
158 168
  }
159 169

  
160
  /* 
170
  /*
161 171
   * format the output in xml for processing from client applications
162 172
   *
163 173
   * @param tag the root element tag for the message (error or success)
164 174
   * @param message the message content of the root element
165 175
   */
166
  private String formatOutput(String tag, String message) 
176
  private String formatOutput(String tag, String message)
167 177
  {
168 178
      return formatOutput(tag, message, null);
169 179
  }
170 180

  
171
  /* 
181
  /*
172 182
   * format the output in xml for processing from client applications
173 183
   *
174 184
   * @param tag the root element tag for the message (error or success)
175 185
   * @param message the message content of the root element
176 186
   * @param sessionId the session identifier for a successful login
177 187
   */
178
  private String formatOutput(String tag, String message, String sessionId) 
188
  private String formatOutput(String tag, String message, String sessionId)
179 189
  {
180 190
    StringBuffer out = new StringBuffer();
181
      
191

  
182 192
    out.append("<?xml version=\"1.0\"?>\n");
183 193
    out.append("<" + tag + ">");
184 194
    out.append("\n  <message>" + message + "</message>\n");
......
186 196
        out.append("\n  <sessionId>" + sessionId + "</sessionId>\n");
187 197
    }
188 198
    out.append("</" + tag + ">");
189
    
199

  
190 200
    return out.toString();
191 201
  }
192 202

  
......
196 206
   * @param className the fully qualified name of the class to instantiate
197 207
   */
198 208
  private static Object createObject(String className) throws Exception {
199
 
209

  
200 210
    Object object = null;
201 211
    try {
202 212
      Class classDefinition = Class.forName(className);
src/edu/ucsb/nceas/metacat/AuthInterface.java
1 1
/**
2 2
 *  '$RCSfile$'
3
 *    Purpose: An interface representing the methods that should be 
3
 *    Purpose: An interface representing the methods that should be
4 4
 *             implemented by an authentication service
5 5
 *  Copyright: 2000 Regents of the University of California and the
6 6
 *             National Center for Ecological Analysis and Synthesis
......
32 32
import java.util.HashMap;
33 33

  
34 34
/**
35
 * An interface representing the methods that should be 
35
 * An interface representing the methods that should be
36 36
 * implemented by an authentication service.  The authentication service is
37
 * used to determine if a user is authenticated, and whether they are a member 
37
 * used to determine if a user is authenticated, and whether they are a member
38 38
 * of a particular group.
39 39
 */
40 40
public interface AuthInterface {
......
53 53
  /**
54 54
   * Get all users from the authentication service
55 55
   */
56
  public String[] getUsers(String user, String password) 
56
  public String[][] getUsers(String user, String password)
57 57
         throws ConnectException;
58 58

  
59 59
  /**
......
65 65
  /**
66 66
   * Get all groups from the authentication service
67 67
   */
68
  public String[] getGroups(String user, String password)
68
  public String[][] getGroups(String user, String password)
69 69
         throws ConnectException;
70 70

  
71 71
  /**
72 72
   * Get the groups for a particular user from the authentication service
73 73
   */
74
  public String[] getGroups(String user, String password, String foruser)
74
  public String[][] getGroups(String user, String password, String foruser)
75 75
         throws ConnectException;
76 76

  
77 77
  /**
......
80 80
   * @param user the user for which the attribute list is requested
81 81
   * @returns HashMap a map of attribute name to a Vector of values
82 82
   */
83
  public HashMap getAttributes(String foruser) 
83
  public HashMap getAttributes(String foruser)
84 84
         throws ConnectException;
85 85

  
86 86
  /**
......
91 91
   * @param password the password for authenticating against the service
92 92
   * @returns HashMap a map of attribute name to a Vector of values
93 93
   */
94
  public HashMap getAttributes(String user, String password, String foruser) 
94
  public HashMap getAttributes(String user, String password, String foruser)
95 95
         throws ConnectException;
96 96

  
97 97
  /**

Also available in: Unified diff