/**
 * Copyright 2005-2018 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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.kuali.rice.ksb.security.soap;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.log4j.Logger;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.Merlin;
import org.apache.wss4j.common.crypto.PasswordEncryptor;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.dom.handler.RequestData;
import org.apache.wss4j.dom.handler.WSHandlerConstants;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.exception.RiceRuntimeException;
import org.kuali.rice.core.api.util.ClassLoaderUtils;
import org.kuali.rice.ksb.config.wss4j.CryptoPasswordCallbackHandler;

import java.io.IOException;
import java.util.Properties;


/**
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */

public class CXFWSS4JOutInterceptor extends WSS4JOutInterceptor {

	private static final Logger LOG = Logger.getLogger(CXFWSS4JOutInterceptor.class);

	private final boolean busSecurity;

	public CXFWSS4JOutInterceptor(boolean busSecurity) {
		this.busSecurity = busSecurity;
        if (busSecurity) {
		    this.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
		    this.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, CryptoPasswordCallbackHandler.class.getName());
		    this.setProperty(WSHandlerConstants.SIG_KEY_ID, "IssuerSerial");
		    this.setProperty(WSHandlerConstants.USER, ConfigContext.getCurrentContextConfig().getKeystoreAlias());
        }
	}

    @Override
    public Crypto loadSignatureCrypto(RequestData reqData) throws WSSecurityException {
        try {
            PasswordEncryptor passwordEncryptor = new PlainTextPasswordEcryptor();
            return new Merlin(getMerlinProperties(), ClassLoaderUtils.getDefaultClassLoader(), passwordEncryptor);
        } catch (Exception e) {
            throw new RiceRuntimeException(e);
        }
    }

    @Override
    public Crypto loadDecryptionCrypto(RequestData reqData) throws WSSecurityException {
        return loadSignatureCrypto(reqData);
    }

    protected Properties getMerlinProperties() throws IOException {
		Properties props = new Properties();
		props.put("org.apache.ws.security.crypto.merlin.keystore.type", "jks");
		props.put("org.apache.ws.security.crypto.merlin.keystore.password", ConfigContext.getCurrentContextConfig().getKeystorePassword());
		props.put("org.apache.ws.security.crypto.merlin.alias.password", ConfigContext.getCurrentContextConfig().getKeystorePassword());
		props.put("org.apache.ws.security.crypto.merlin.keystore.alias", ConfigContext.getCurrentContextConfig().getKeystoreAlias());
		props.put("org.apache.ws.security.crypto.merlin.file", ConfigContext.getCurrentContextConfig().getKeystoreFile());

		if (LOG.isDebugEnabled()) {
			LOG.debug("Using keystore location " + ConfigContext.getCurrentContextConfig().getKeystoreFile());
		}

		return props;
	}

	/**
	 * This overridden method will not apply security headers if bus security is disabled.
	 * 
	 * @see org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor#handleMessage(org.apache.cxf.binding.soap.SoapMessage)
	 */
	@Override
	public void handleMessage(SoapMessage mc) {
		if (busSecurity) {
			super.handleMessage(mc);
		}
	}

}
