import java.util.Hashtable;
import jet.server.api.custom.security.AuthenticationProvider;
import jet.server.api.custom.security.SecurityListener;

/**
 * In this demonstration program, there are 4 users in system: "admin", "guest", "user1", and "user2".
 * Among these users "admin" is an admin user. Initialized password of each user is "1234". Realm name 
 * does not matter.
 * <p>
 * To apply this demonstration program on JReport Server, follow the below steps:<br>
 * 1. Compile it and put <code>DemoAuthenticationProvider.class</code> into 
 * CLASSPATH used for launching JReport Server. <br>
 * 2. Edit file <code>&lt;SERVER PATH&gt;/bin/server.properties</code>, add a name/value pair, name is  
 * <code>custom.security.AuthenticationProvider</code>, value is <code>DemoAuthenticationProvider</code>;
 * or specify it by -D parameter of the JVM, name is <code>com.jinfonet.AuthenticationProvider</code>,
 * value is <code>DemoAuthenticationProvider</code>. <br>
 * 4. Restart JReport Server and the customized user authentication demonstration works.<br>
 */
public class DemoAuthenticationProvider implements AuthenticationProvider {
    
    Hashtable users = null;
    
    public DemoAuthenticationProvider() {
        users = new Hashtable(4);
        users.put("admin", "1234");
        users.put("guest", "1234");
        users.put("user1", "1234");
        users.put("user2", "1234");
    }

    public boolean isValidUser(String realmName, String userName, String password) {
   		
		System.out.println("isValidUser(), userName=" + userName + ", password=" + password);
        String pwd = (String)users.get(userName);
        if (pwd != null && password != null && pwd.equals(password)) {
            return true;
        }
        return false;
    }

    public boolean isAdminUser(String realmName, String userName) {

        System.out.println("isAdminUser(), userName=" + userName);
        if (userName.equals("admin")) {
            return true;
        }
        return false;
    }

    public String changePassword(String realmName, String implUserName, String userName, String oldPwd, String newPwd) {
        if (implUserName.equals(userName) || isAdminUser(realmName, implUserName)) {
            if (isValidUser(realmName, implUserName, oldPwd)) {
                users.put(userName, newPwd);
                // if the change of password succeeds, return null.
                return null;
            } else {
				
                return "Authentication failed and the change of password is forbidden";
            }
        }

        return "Only administrator user or the user himself can change the user password.";
    }

    public void addSecurityListener(SecurityListener listener) {
    }

    public boolean isEnableEdit() {
        return true;
    }
}
