/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2005 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.objectweb.wssample.security;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.objectweb.jonas.security.SecurityService;
import org.objectweb.jonas.security.realm.factory.JResource;
import org.objectweb.jonas.security.realm.principals.User;
import org.objectweb.jonas.service.ServiceManager;

import org.apache.ws.security.WSPasswordCallback;

/**
 * WSS4J Sample CallbackHandler. It is intended to be used from a JOnAS server (servlet/ejb client & JAX-RPC/SSB endpoint).
 * It will get the 'memrlm_1' instance and try to get the needed password from that JResource.
 *
 * @author Guillaume Sauthier
 */
public class ServerSideCallbackHandler implements CallbackHandler {

    /**
     * encryptionUser value (used to access keystore - look in crypto.properties)
     */
    private static final String ENCRYPTION_USER = "jonas-ws";

    /**
     * encryptionUser password : password used to access keystore
     */
    private static final String ENCRYPTION_PASSWORD = "security";

    /**
     * @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[])
     */
    public void handle(Callback[] callbacks) throws IOException,
            UnsupportedCallbackException {
        for (int i = 0; i < callbacks.length; i++) {
            if (callbacks[i] instanceof WSPasswordCallback) {
                WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
                // set the password given a username

                if (!ENCRYPTION_USER.equals(pc.getIdentifer())) {
                    // Get the Security Service
                    SecurityService securityService = null;
                    try {
                        securityService = (SecurityService) ServiceManager.getInstance().getSecurityService();
                    } catch (Exception e) {
                        // Can't retrieve Security service
                        throw new IOException("can't retrieve Security service");
                    }

                    // Get the resource from the security service
                    JResource jResource = securityService.getJResource("memrlm_1");
                    if (jResource == null) {
                        throw new IOException("Can't retrieve resource 'memrlm_1' from the security service");
                    }

                    User user = jResource.findUser(pc.getIdentifer());

                    if (user == null) {
                        throw new IOException("Cannot find user '" + pc.getIdentifer() + "' in Realm.");
                    }
                    // if we're here, we found the user, so we can continue ...
                    pc.setPassword(user.getHashPassword().getPassword());
                } else {
                    // this is the ecryption username
                    // we must return the correct password (stored in crypto.properties)
                    pc.setPassword(ENCRYPTION_PASSWORD);
                }

            } else {
                throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
            }
        }
    }

}
