/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004-2007 Bull S.A.S.
 * Contact: jonas-team@ow2.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: SecurityContextHelper.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.security.iiop;

import java.io.UnsupportedEncodingException;

import org.omg.GSSUP.InitialContextToken;
import org.ow2.jonas.lib.util.Log;
import org.ow2.jonas.lib.security.context.SecurityContext;
import org.ow2.jonas.lib.security.context.SecurityCurrent;
import org.ow2.jonas.security.internal.AbsSecurityContextHelper;

import org.ow2.carol.util.csiv2.gss.GSSHelper;



import org.objectweb.util.monolog.api.Logger;


/**
 * This class is used by Csiv2 server interceptor.
 * It allows to authenticate users.
 * @author Florent Benoit : Initial developper
 * @author Helene Joanin : Refactoring
 */
public class SecurityContextHelper extends AbsSecurityContextHelper {

    /**
     * The singleton instance
     */
    private static SecurityContextHelper instance = null;

    /**
     * Csiv2 Realm key
     */
    private static final String CSIV2_REALM_KEY = "jonas.service.security.csiv2.realm";

    /**
     * Default Interop resource name
     */
    private static final String DEFAULT_CSIV2_REALM = "memrlm_1";


    /**
     * Domain separator
     */
    private static final String DOMAIN_SEPARATOR = "@";

    /**
     * Default domain name
     */
    private static final String DEFAULT_DOMAIN_NAME = "default";

    /**
     * Encoding
     */
    private static final String ENCODING = "UTF-8";

    /**
     * Logger
     */
    private static Logger logger = Log.getLogger(Log.JONAS_CSIV2_SECURITY_PREFIX);

    /**
     *  Private constructor because of singleton
     */
    private SecurityContextHelper() {
    }

    /**
     * @return return the singleton instance
     */
    public static SecurityContextHelper getInstance() {
        if (instance == null) {
            instance = new SecurityContextHelper();
        }
        return instance;
    }

    /**
     * @return the associated logger
     */
    protected Logger getLogger() {
        return logger;
    }

    /**
     * @return return the CSIV2 Realm key
     */
    protected String getRealmKey() {
        return CSIV2_REALM_KEY;
    }

    /**
     * @return return the CSIV2 default Realm
     */
    protected String getRealmDefault() {
        return DEFAULT_CSIV2_REALM;
    }

    /**
     * Authenticate with csiv2 authentication token
     * @param userName user for login
     * @param password of the user
     */
    protected void loginAuthenticationToken(String userName, String password) {
        // need to remove domain of userName which is GSS NT_USERNAME
        String principalName = userName.split(DOMAIN_SEPARATOR)[0];
        String credential = password;
        login(principalName, credential);
    }

    /**
     * Authenticate with csiv2 identity token (no password)
     * @param principalName the username
     */
    protected void loginIdentiyToken(String principalName) {
        String credential = principalName;
        login(principalName, credential);
    }

    /**
     * @return the identity of the authenticated user.
     * In run-as, it returns run-as identity.
     */
    public String getIdentityToken() {
        SecurityCurrent current = SecurityCurrent.getCurrent();
        SecurityContext securityContext = current.getSecurityContext();

        if (securityContext.peekRunAsPrincipal() != null) {
            return securityContext.peekRunAsPrincipal();
        } else {
            return securityContext.getCallerPrincipal(false).getName();
        }
   }

    /**
     * @return the identity of the authenticated user.
     * In run-as, it returns run-as identity.
     * @throws UnsupportedEncodingException if UTF-8 encoding is not supported
     */
    public InitialContextToken getInitialContextToken() throws UnsupportedEncodingException {
        SecurityCurrent current = SecurityCurrent.getCurrent();
        SecurityContext securityContext = current.getSecurityContext();
        String principalName = securityContext.getPrincipalName();
        String userName = principalName + DOMAIN_SEPARATOR + DEFAULT_DOMAIN_NAME;
        String password = principalName;
        byte[] user = userName.getBytes(ENCODING);
        byte[] pass = password.getBytes(ENCODING);
        byte[] domain = GSSHelper.encodeExported(DEFAULT_DOMAIN_NAME);
        return new InitialContextToken(user, pass, domain);

   }


}
