/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Axis" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package net.vitale.filippo.axis.handlers;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.soap.SOAPException;
import javax.xml.namespace.QName;

import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.Base64;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.PrefixedQName;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.utils.Messages;

/**
 * @author Filippo Vitale (filippo [at] vitale dot net)
 *
 */
public class WsseClientHandler extends BasicHandler {

    private static final String WSSE_URI = "http://schemas.xmlsoap.org/ws/2002/07/secext";
	private static final String WSU_URI = "http://schemas.xmlsoap.org/ws/2002/07/utility";

	public static final String PASSWORD_WITHOUT = "without password";
	public static final String PASSWORD_CLEARTEXT = "cleartext password";
	public static final String PASSWORD_DIGEST = "simple password digest";
	public static final String PASSWORD_DIGEST_WITH_NONCE = "password+nonce+timestamp digest";
	public static final String PASSWORD_OPTION = "wsse password option";
	/* 
	 * @see org.apache.axis.Handler#invoke(org.apache.axis.MessageContext)
	 */
	public void invoke(MessageContext msgContext) throws AxisFault {
		System.out.println("Enter: WsseClientHandler::invoke");
		try {
			Message msg = msgContext.getCurrentMessage(); //msgContext.getRequestMessage();
			SOAPEnvelope se = msg.getSOAPEnvelope();

			SOAPHeaderElement wsseSecurity = new SOAPHeaderElement(new PrefixedQName(WSSE_URI, "Security", "wsse"));
			//wsseSecurity.setMustUnderstand(true);
			wsseSecurity.addChild(createUsernameToken(
				msgContext.getUsername(), msgContext.getPassword(),
				(String)msgContext.getProperty(PASSWORD_OPTION)));
			se.addHeader(wsseSecurity);
		}
		catch( Exception e ) {
			System.out.println( Messages.getMessage("exception00"));
			throw AxisFault.makeFault(e);
		}
		System.out.println("Exit: WsseClientHandler::invoke");
	}

	public void onFault(MessageContext msgContext) {
		System.out.println("Enter: WsseClientHandler::onFault");
		System.out.println("Exit: WsseClientHandler::onFault");
	}

	private MessageElement createUsernameToken(String usernameS, String passwordS, String passwordOption) throws SOAPException {
		System.out.println("Enter: WsseClientHandler::createUsernameToken");
		MessageElement usernameToken = new MessageElement(new PrefixedQName(WSSE_URI, "UsernameToken", "wsse"));
/*
		if (usernameS == null || passwordS == null || passwordOption == null) {
			
		}
		else
*/		
		if (passwordOption.equals(PASSWORD_WITHOUT)) {
			MessageElement username = new MessageElement("wsse", "Username");
			username.setObjectValue(usernameS);
            //username.removeNamespaceDeclaration("xmlns");
            usernameToken.addChild(username);
		}		
		else if (passwordOption.equals(PASSWORD_CLEARTEXT)) {
			MessageElement username = new MessageElement(new PrefixedQName(WSSE_URI, "Username", "wsse"));
			username.setObjectValue(usernameS);
            usernameToken.addChild(username);
			
			MessageElement password = new MessageElement(new PrefixedQName(WSSE_URI, "Password", "wsse"));
			password.setObjectValue(passwordS);
            usernameToken.addChild(password);
		}		
		else if (passwordOption.equals(PASSWORD_DIGEST)) {
			MessageElement username = new MessageElement("", "wsse:Username");
			username.setObjectValue(usernameS);
			usernameToken.addChild(username);
			
			MessageElement password = new MessageElement("", "wsse:Password");
			password.addAttribute("", "Type", "wsse:PasswordDigest");
			password.setObjectValue(getBase64Digest(utf8decode(passwordS)));
			usernameToken.addChild(password);
		}		
		else if (passwordOption.equals(PASSWORD_DIGEST_WITH_NONCE)) {
			
			String nonceS = generateNonce();
			byte[] nonceB = Base64.decode(nonceS);
			
			String createdS = generateTimestamp();
			byte[] createdB = utf8decode(createdS);
			
			byte[] passwordB = utf8decode(passwordS);

			
			MessageElement username = new MessageElement("", "wsse:Username");
			username.setObjectValue(usernameS);
			usernameToken.addChild(username);

			MessageElement password = new MessageElement("", "wsse:Password");
			password.addAttribute("", "Type", "wsse:PasswordDigest");
			password.setObjectValue(getBase64Digest(nonceB, createdB, passwordB));
			usernameToken.addChild(password);

			MessageElement nonce = new MessageElement("", "wsse:Nonce");
			nonce.setObjectValue(nonceS);
			usernameToken.addChild(nonce);

			MessageElement created = new MessageElement(new PrefixedQName(WSU_URI, "Created", "wsu"));
			created.setObjectValue(createdS);
			usernameToken.addChild(created);
		}
		else {
			System.out.println("Exit: WsseClientHandler::createUsernameToken (No UsernameToken created)");
			return null;
		}

		System.out.println("Exit: WsseClientHandler::createUsernameToken");
		return usernameToken;

	}

	private String generateNonce() {
		// TODO working Nonce generator "private byte[] generateNonce()"
		return "msJPTHku44rHAqPIRvbNQA==";
	}

	private String generateTimestamp() {
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		return dateFormatter.format(new Date());
	}
	
	private static byte[] utf8decode(String input) {
		// UTF-8 enc
		byte[] ret = null;
		try {
			ret = input.getBytes("UTF-8");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ret;
	}

	private static synchronized String getBase64Digest(byte[] nonce, byte[] created, byte[] password) {
		try {
			MessageDigest messageDigester = MessageDigest.getInstance("SHA-1");

			// SHA-1 ( nonce + created + password )
			messageDigester.reset();
			messageDigester.update(nonce);
			messageDigester.update(created);
			messageDigester.update(password);

			return Base64.encode(messageDigester.digest());
		} catch (java.security.NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static synchronized String getBase64Digest(byte[] password) {
		try {
			MessageDigest messageDigester = MessageDigest.getInstance("SHA-1");

			// SHA-1 ( nonce + created + password )
			messageDigester.reset();
			messageDigester.update(password);

			return Base64.encode(messageDigester.digest());
		} catch (java.security.NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}

