/*
 * 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.auth.login;

import com.sun.enterprise.deployment.Group;
import com.sun.enterprise.security.auth.realm.NoSuchRealmException;
import com.sun.logging.LogDomains;
import java.util.Enumeration;
import java.util.Map;
import java.util.logging.Logger;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import com.sun.enterprise.util.i18n.StringManager;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import com.sun.web.security.PrincipalGroupFactory;
import com.sun.enterprise.deployment.PrincipalImpl;
import com.sun.enterprise.deployment.Group;
import com.sun.enterprise.security.auth.digest.api.DigestAlgorithmParameter;
import com.sun.enterprise.security.auth.digest.api.Password;
import com.sun.enterprise.security.auth.realm.DigestRealm;
import com.sun.enterprise.security.auth.realm.Realm;
import java.util.Enumeration;


/**
 *
 * @author K.Venugopal@sun.com
 */
public abstract class DigestLoginModule implements LoginModule {

    private Subject subject = null;
    private CallbackHandler handler = null;
    private Map<String, ?> sharedState = null;
    private Map<String, ?> options = null;
    protected Logger _logger = LogDomains.getLogger(LogDomains.SECURITY_LOGGER);
    protected static final StringManager sm = StringManager.getManager("com.sun.enterprise.security.auth.login");
    protected boolean _succeeded = false;
    protected boolean _commitSucceeded = false;
    protected PrincipalImpl _userPrincipal;
    private DigestCredentials digestCredentials = null;
    private Realm _realm;

    public DigestLoginModule() {
    }

    public final void initialize(Subject subject, CallbackHandler handler, Map<String, ?> sharedState, Map<String, ?> options) {
        this.subject = subject;
        this.handler = handler;
        this.sharedState = sharedState;
        this.options = options;
        if (_logger.isLoggable(Level.FINE)) {
            _logger.log(Level.FINE, "Login module initialized: " + this.getClass().toString());
        }
    }

    public final boolean login() throws LoginException {
        Set<Object> creds = this.subject.getPrivateCredentials();
        Iterator<Object> itr = creds.iterator();
        while (itr.hasNext()) {
            Object obj = itr.next();
            if (obj instanceof DigestCredentials) {
                digestCredentials = (DigestCredentials) obj;
                break;
            }
        }
        DigestAlgorithmParameter [] params = digestCredentials.getParameters();
        String username = digestCredentials.getUserName();
        try {
            _realm = Realm.getInstance(digestCredentials.getRealmName());
        } catch (NoSuchRealmException ex) {
            _logger.log(Level.FINE,"",ex);
            _logger.log(Level.SEVERE,"no.realm",digestCredentials.getRealmName());
            throw new LoginException(ex.getMessage());
        }
            if (_realm instanceof DigestRealm){
                if(((DigestRealm)_realm).validate(username, params)) {
                //change to pass Password Validator
                _succeeded = true;
                }
            }else{
                _logger.log(Level.SEVERE,"digest.realm",digestCredentials.getRealmName());
                throw new LoginException("Realm" + digestCredentials.getRealmName()+ " does not support Digest validation");                
            }

        return _succeeded;
    }

    public final boolean commit() throws LoginException {
        
            if (!_succeeded) {
                _commitSucceeded = false;
                return false;
            }


            _userPrincipal = com.sun.web.security.PrincipalGroupFactory.getPrincipalInstance(digestCredentials.getUserName(), digestCredentials.getRealmName());
            java.util.Set principalSet = this.subject.getPrincipals();
            if (!principalSet.contains(_userPrincipal)) {
                principalSet.add(_userPrincipal);
            }
            java.util.Enumeration groupsList = getGroups(digestCredentials.getUserName());
            while (groupsList.hasMoreElements()) {
                java.lang.String value = (java.lang.String) groupsList.nextElement();
                com.sun.enterprise.deployment.Group g = com.sun.web.security.PrincipalGroupFactory.getGroupInstance(value, digestCredentials.getRealmName());
                if (!principalSet.contains(g)) {
                    principalSet.add(g);
                }
                // cleaning the slate
            }

            return true;
        
	
    }

    public final boolean abort() throws LoginException {
        if (_logger.isLoggable(Level.FINE)) {
            _logger.log(Level.FINE, "JAAS authentication aborted.");
        }

        if (_succeeded == false) {
            return false;
        } else if (_succeeded == true && _commitSucceeded == false) {
            // login succeeded but overall authentication failed
            _succeeded = false;


          
        } else {
            // overall authentication succeeded and commit succeeded,
            // but someone else's commit failed
            logout();
        }
        return true;
    }

    public final boolean logout() throws LoginException {
        subject.getPrincipals().clear();
        subject.getPublicCredentials().clear();
        subject.getPrivateCredentials().clear();

        _succeeded = false;
        _commitSucceeded = false;
       
        return true;
    }

    protected Realm getRealm() {
        return _realm;
    }

    protected abstract Enumeration getGroups(String username);

    
}
