/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.server.realm;



import java.util.Properties;
import java.util.Enumeration;

import org.apache.log4j.Logger;

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


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

	try
	{
	    Group anon_group = Group.findGroupByName("anonymous");
	    Enumeration enumeration = User.findUserPrimaryKeys( anon_group.whereMembers(), "name" );
	    if ( enumeration.hasMoreElements() )
		user_id = (PrimaryKey)enumeration.nextElement();
	    else
		throw new AuthenticationException( "Couldn't find any members of the anonymous group." );
	}
	catch ( BuildingServerException bs )
	{
	    log.error( 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();
    }
    
}

