/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.security;

import java.security.Principal;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.security.auth.Subject;

import com.sun.enterprise.security.auth.login.PasswordCredential;
import com.sun.enterprise.deployment.PrincipalImpl;
import com.sun.enterprise.ServerConfiguration;

import java.util.logging.*;
import com.sun.logging.*;


/**
 * This class represents the security context on the client side. 
 * @author Harpreet Singh
 *
 */
public final class ClientSecurityContext extends AbstractSecurityContext {
    
    private static Logger _logger =
        LogDomains.getLogger(LogDomains.SECURITY_LOGGER);

    // Bug Id: 4787940
    private static final boolean isPerThreadAuth = 
            Boolean.getBoolean("com.sun.appserv.iiopclient.perthreadauth");

    private static Object csc = isPerThreadAuth ? new ThreadLocal() : null;

    /**
     * This creates a new ClientSecurityContext object.
     * @param The name of the user.
     * @param The Credentials of the user.
     */
    public ClientSecurityContext(String userName, 
				 Subject s) {

	this.initiator = new PrincipalImpl(userName);
	this.subject = s ;
    }

    /**
     * Initialize the SecurityContext & handle the unauthenticated
     * principal case
     */
    public static ClientSecurityContext init() {
	ClientSecurityContext sc = getCurrent();
	if (sc == null) { // there is no current security context
            // create a default one if
	    sc = generateDefaultSecurityContext();
        }
	return sc;
    }
    
    private static ClientSecurityContext generateDefaultSecurityContext() {
	final String PRINCIPAL_NAME = "auth.default.principal.name";
	final String PRINCIPAL_PASS = "auth.default.principal.password";
	
	ServerConfiguration config = ServerConfiguration.getConfiguration();
	String username = config.getProperty(PRINCIPAL_NAME, "guest");
	String password = config.getProperty(PRINCIPAL_PASS, "guest123");
	
	synchronized (ClientSecurityContext.class) {
	    // login & all that stuff..
	    try {
		final Subject subject = new Subject();
		final PasswordCredential pc = new PasswordCredential(username,
		        password, "default");
		AccessController.doPrivileged(new PrivilegedAction() {
		    public java.lang.Object run() {
			subject.getPrivateCredentials().add(pc);
			return null;
		    }
		});
		// we do not need to generate any credential as authorization
		// decisions are not being done on the appclient side.
                ClientSecurityContext defaultCSC =
                    new ClientSecurityContext(username, subject);
		setCurrent(defaultCSC);
                return defaultCSC;
	    } catch(Exception e) {
		_logger.log(Level.SEVERE,
                            "java_security.gen_security_context", e);
                return null;
	    }
	}
    }

    public static void reset(ClientSecurityContext sc) {
        if (isPerThreadAuth) {
            ((ThreadLocal)csc).set(sc);
        } else {
	    csc = sc;
        }
    }
    
    /**
     * This method gets the SecurityContext stored here.  If using a
     * per-thread authentication model, it gets the context from
     * Thread Local Store (TLS) of the current thread. If not using a
     * per-thread authentication model, it gets the singleton context.
     *
     * @return The current Security Context stored here. It returns
     *      null if SecurityContext could not be found.
     */
    public static ClientSecurityContext getCurrent() {
        if (isPerThreadAuth) {
            return (ClientSecurityContext)((ThreadLocal)csc).get();
        } else {
	    return (ClientSecurityContext)csc;
        }
    }

    /**
     * This method sets the SecurityContext to be stored here.
     * 
     * @param The Security Context that should be stored.
     */
    public static void setCurrent(ClientSecurityContext sc) {
        if (isPerThreadAuth) {
            ((ThreadLocal)csc).set(sc);
        } else {
	    csc = sc;
        }
    } 

    /**
     * This method returns the caller principal. 
     * This information may be redundant since the same information 
     * can be inferred by inspecting the Credentials of the caller.
     * 
     * @return The caller Principal. 
     */
    public Principal getCallerPrincipal() {
	return initiator;
    }

    
    public Subject getSubject() {
	return subject;
    }

    public String toString() {
	return "ClientSecurityContext[ " + "Initiator: " + initiator +
	    "Subject " + subject + " ]";
    }

}







