/*
* JBoss, the OpenSource J2EE webOS
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.security.auth.certs;

import java.security.Principal;
import java.security.cert.X509Certificate;
import org.jboss.security.CertificatePrincipal;
import org.jboss.security.SimplePrincipal;

/** A CertificatePrincipal implementation that uses the client cert
 * SubjectDN CN='...' element as the principal.
 * 
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.2.4.1 $
 */
public class SubjectCNMapping
   implements CertificatePrincipal
{
   /** Returns the client cert common name portion (cn=...) of the SubjectDN
    * as the principal.
    *
    * @param certs Array of client certificates, with the first one in
    * the array being the certificate of the client itself.
    */
   public Principal toPrinicipal(X509Certificate[] certs)
   {
      Principal cn = null;
      Principal subject = certs[0].getSubjectDN();
      // Look for a cn=... entry in the subject DN
      String dn = subject.getName().toLowerCase();
      int index = dn.indexOf("cn=");
      if( index >= 0 )
      {
         int comma = dn.indexOf(',', index);
         if( comma < 0 )
            comma = dn.length();
         String name = dn.substring(index+3, comma);
         cn = new SimplePrincipal(name);
      }
      else
      {
         // Fallback to the DN
         cn = subject;
      }
      return cn;
   }
}