package jacorb.security.level2;

import java.io.*;
import java.net.*;
import org.omg.SecurityLevel2.*;
import org.omg.Security.*;
import jacorb.util.Environment;

/**
 * PrincipalAuthenticator
 * 
 * This simple authenticator just retrieves X.509v3 certificates
 * from a Java key store
 *
 * @author Gerald Brose
 * $id$
 */

public class PrincipalAuthenticator
    extends jacorb.orb.LocalityConstrainedObject
    implements org.omg.SecurityLevel2.PrincipalAuthenticator
{  
    private org.omg.CORBA.ORB orb;
    private String keyStoreFileName;

    PrincipalAuthenticator(org.omg.CORBA.ORB orb)
    {
	this.orb = orb;
	keyStoreFileName = jacorb.util.Environment.keyStore();
    }
  

    public int[] get_supported_authen_methods(java.lang.String mechanism)
    {
	return new int[]{0};
    }


    public org.omg.Security.AuthenticationStatus authenticate(
			       int method, 
			       java.lang.String mechanism, 
			       java.lang.String security_name, //user name
			       byte[] auth_data, 
			       org.omg.Security.SecAttribute[] privileges, 
			       org.omg.SecurityLevel2.CredentialsHolder creds, 
			       org.omg.Security.OpaqueHolder continuation_data, 
			       org.omg.Security.OpaqueHolder auth_specific_data)
    {
	jacorb.util.Debug.output(3,"starting authentication");
	try 
	{
	    String passwd = jacorb.util.Environment.getProperty("jacorb.security.keyPassword");
	    char[] password = (passwd != null? passwd.toCharArray() : null );
	    String alias = jacorb.util.Environment.getProperty("jacorb.security.keyAlias");    
	    java.security.cert.X509Certificate [] certs = 
	    		jacorb.security.util.KeyStoreUtil.getCerts( keyStoreFileName, alias, password );
	    creds.value =  new jacorb.security.level2.Credentials(this, 
				  certs,org.omg.Security.AuthenticationStatus.SecAuthSuccess );
	    jacorb.util.Debug.output(3,"authentication succeeded");
	    return org.omg.Security.AuthenticationStatus.SecAuthSuccess;
	}
	catch (Exception e) 
	{
	    jacorb.util.Debug.output(4,e);
	    jacorb.util.Debug.output(3,"authentication failed, reason: " + e.getMessage());
	    return org.omg.Security.AuthenticationStatus.SecAuthFailure;
	}
    }

    /** 
     * not implemented
     */
  
    public org.omg.Security.AuthenticationStatus continue_authentication(
							byte[] response_data, 
							org.omg.SecurityLevel2.Credentials creds, 
							org.omg.Security.OpaqueHolder continuation_data, 
							org.omg.Security.OpaqueHolder auth_specific_data)
    {
	return org.omg.Security.AuthenticationStatus.SecAuthFailure;
    }


}




