/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.kernel.security;

import com.arsdigita.domain.DataObjectNotFoundException;
import com.arsdigita.kernel.UserAuthentication;
import java.math.BigDecimal;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import org.apache.log4j.Logger;

/**
 * Translates a username to a user ID using
 * <code>com.arsdigita.kernel.UserAuthentication</code>.
 *
 * @author Sameer Ajmani
 **/
public class UserIDLoginModule extends MappingLoginModule {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/kernel/security/UserIDLoginModule.java#9 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";
    private static final Logger s_log =
        Logger.getLogger(UserIDLoginModule.class.getName());

    // fields set by initialize()
    private Subject m_subject;
    private CallbackHandler m_handler;
    private Map m_shared;
    private Map m_options;

    // implements LoginModule
    public void initialize(Subject subject,
                           CallbackHandler handler,
                           Map shared,
                           Map options) {
        super.initialize(subject, handler, shared, options);
        m_subject = subject;
        m_handler = handler;
        m_shared = shared;
        m_options = options;
        // TODO: support "debug" option
    }

    /**
     * Retreieves the user ID for the given username from the database.
     *
     * @param username the username to look up
     *
     * @return the user ID for the given username.
     *
     * @throws AccountNotFoundException if the account does not exist.
     * @throws LoginException if an error occurs.
     **/
    protected BigDecimal getUserID(String username)
        throws AccountNotFoundException, LoginException {
        try {
            return UserAuthentication
                .retrieveForLoginName(username)
                .getUser().getID();
        } catch (DataObjectNotFoundException e) {
            throw new AccountNotFoundException(username, e);
        }
    }
}
