package org.bodington.server.realm;



import java.util.Properties;
import java.util.Enumeration;
import java.util.logging.*;

import org.bodington.database.PrimaryKey;
import org.bodington.server.BuildingServerException;


public class AnonymousAuthenticator implements Authenticator
{
 
    static PrimaryKey user_id=null;
    
    private void authenticate() throws AuthenticationException
    {
	if ( user_id != null ) return;

	try
	{
	    Group anon_group = Group.findGroup( "name = 'anonymous'" );
	    Enumeration enum = User.findUserPrimaryKeys( anon_group.whereMembers(), "name" );
	    if ( enum.hasMoreElements() )
		user_id = (PrimaryKey)enum.nextElement();
	    else
		throw new AuthenticationException( "Couldn't find any members of the anonymous group." );
	}
	catch ( BuildingServerException bs )
	{
	    Logger.getLogger( "org.bodington" ).logp(
		Level.SEVERE,
		"PassPhraseAuthenticator",
		"authenticate",
		bs.getMessage(),
		bs );
	    throw new AuthenticationException( "Technical problem authenticating user." );
	}
    }
    
    
    public PrimaryKey getAuthenticatedUserId() throws AuthenticationException
    {
	authenticate();
	return user_id;
    }
    
    public String getAuthenticationError() throws AuthenticationException
    {
	return null;
    }
    
    public void setAuthenticationCredentials(Properties credentials) throws AuthenticationException
    {
	// ignore
    }

    public void changeCredentials( Properties credentials ) throws AuthenticationException
    {
	// ignore
    }
    
    public boolean isAuthenticated() throws AuthenticationException
    {
	authenticate();
	return user_id != null;
    }
    
    public boolean isAnonymous() throws AuthenticationException
    {
	return isAuthenticated();
    }
    
}

