/*
 * 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 (c) Ericsson AB, 2004-2007. All rights reserved.
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 */
package org.jvnet.glassfish.comms.security.auth.impl;

import com.sun.enterprise.admin.server.core.AdminService;
import com.sun.enterprise.config.ConfigContext;
import com.sun.enterprise.config.ConfigException;
import com.sun.enterprise.config.serverbeans.Config;
import com.sun.enterprise.config.serverbeans.Configs;
import com.sun.enterprise.config.serverbeans.Domain;
import com.sun.enterprise.config.serverbeans.SecurityService;
import com.sun.enterprise.security.SecurityContext;
import com.sun.enterprise.security.auth.LoginContextDriver;
import com.sun.enterprise.security.auth.TrustHandler;
import com.sun.enterprise.security.auth.login.AssertedCredentials;

import com.sun.web.security.PrincipalGroupFactory;
import com.sun.web.security.WebPrincipal;

import java.security.Principal;

import java.util.ArrayList;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.sip.SipServletRequest;


/**
 *
 * @author K.Venugopal@sun.com
 */
public class PAssertedAuthenticator extends Authenticator {
    private String realmName = null;
    private TrustHandler handler = null;
    private String handlerClass = null;

    public PAssertedAuthenticator(String realmName) {
        this.realmName = realmName;
        initialize();
    }

    public Principal authenticate(SipServletRequest request) {
        ListIterator passertedHeader = request.getHeaders("P-Asserted-Identity");
        String id = request.getHeader("Privacy");

        ArrayList<String> arrayList = new ArrayList<String>();

        while (passertedHeader.hasNext()) {
            arrayList.add((String) passertedHeader.next());
        }

        if (arrayList.size() == 0) {
            return null;
        }

        String[] pAssrtValues = arrayList.toArray(new String[0]);
        String host = request.getRemoteAddr();

        Principal[] principals = new Principal[arrayList.size()];

        for (int i = 0; i < arrayList.size(); i++) {
            principals[i] = PrincipalGroupFactory.getPrincipalInstance(pAssrtValues[i],
                    realmName);
        }

        Principal[] mappedPrincipals = this.mapUsers(principals);

        if (this.isTrusted(principals, host)) {
            try {
                AssertedCredentials creds = new AssertedCredentials(realmName,
                        principals[0].getName());
                LoginContextDriver.login(creds);

                SecurityContext secCtx = SecurityContext.getCurrent();

                return new WebPrincipal(creds.getUserName(), null, secCtx);
            } catch (Exception le) {
                Logger.getLogger("global")
                      .log(Level.SEVERE, "Digest Authentication failed", le);

                //TODO: Log
            }
        }

        return null;
    }

    public boolean isTrusted(Principal[] pv, String host) {
        if (handler == null) {
            return false;
        }

        return handler.isTrusted(host, "Incoming", null, pv);
    }

    private Principal[] mapUsers(Principal[] principals) {
        if (handler == null) {
            return null;
        }

        return handler.mapIdentity(principals);
    }

    private void initialize() {
        try {
            ConfigContext ctx = AdminService.getAdminService().getAdminContext()
                                            .getAdminConfigContext();
            Configs configs = ((Domain) ctx.getRootConfigBean()).getConfigs();
            Config[] configArray = configs.getConfig();

            for (int i = 0; i < configArray.length; i++) {
                SecurityService ss = configArray[i].getSecurityService();
                com.sun.enterprise.config.serverbeans.TrustHandler th = ss.getIdentityAssertionTrust()
                                                                          .getTrustHandler();
                handlerClass = th.getClassName();
            }

            if (handlerClass != null) {
                Class trustClass = Class.forName(handlerClass);
                handler = (TrustHandler) trustClass.newInstance();
                ;
            }
        } catch (InstantiationException ex) {
            Logger.getLogger(PAssertedAuthenticator.class.getName())
                  .log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(PAssertedAuthenticator.class.getName())
                  .log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PAssertedAuthenticator.class.getName())
                  .log(Level.SEVERE, null, ex);
        } catch (ConfigException ex) {
            Logger.getLogger(PAssertedAuthenticator.class.getName())
                  .log(Level.SEVERE, null, ex);
        }
    }
}
