Hi,

I have modified the LdapAuthentication.java as below. While compiling, mvn
package it throws an error
"unreported exception java.sql.SQLException; must be caught or declared to
be thrown" in the below lines which are highlighted in yellow color. Can
anybody help me to update this?.

Thanks in advance.
Rgds
Priya

/*
 * MbankAuthentication.java
 *
 * Version: $Revision: 3735 $
 *
 * Date: $Date: 2009-04-24 04:05:53 +0000 (Fri, 24 Apr 2009) $
 *
 * Copyright (c) 2002-2009, The DSpace Foundation.  All rights reserved.
 * Modified from LDAPAuthentication.java by University of Konstanz. blabla
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of the DSpace Foundation nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */
package org.dspace.authenticate;

import java.security.MessageDigest;
import java.sql.*;
import java.util.Hashtable;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;

/**
 * Authentication module to authenticate against a flat LDAP tree where
 * all users are in the same unit.
 *
 * @author Larry Stone, Stuart Lewis
 * @version $Revision: 3735 $
 */
public class MbankAuthentication
    implements AuthenticationMethod {

    /** log4j category */
    private static Logger log = Logger.getLogger(LDAPAuthentication.class);

    /**
     * Let a real auth method return true if it wants.
     */
    public boolean canSelfRegister(Context context,
                                   HttpServletRequest request,
                                   String username)
        throws SQLException
    {
        // Registration happens in main Mbank DB, not here
        return true;
    }

    /**
     *  Nothing here, initialization is done when auto-registering.
     */
    public void initEPerson(Context context, HttpServletRequest request,
            EPerson eperson)
        throws SQLException
    {
    }

    /**
     * Cannot change Mbank password through dspace, right?
     */
    public boolean allowSetPassword(Context context,
                                    HttpServletRequest request,
                                    String username)
        throws SQLException
    {
        return false;
    }

    /*
     * This is an explicit method.
     */
    public boolean isImplicit()
    {
        return false;
    }

    /*
     * Add authenticated users to the group defined in dspace.cfg by
     * the ldap.login.specialgroup key.
     */
    public int[] getSpecialGroups(Context context, HttpServletRequest
request)
    {
        // Prevents anonymous users from being added to this group, and the
second check
        // ensures they are LDAP users
        try
        {
            if (!context.getCurrentUser().getNetid().equals(""))
            {
                String groupName =
ConfigurationManager.getProperty("Mbank.login.specialgroup");
                if ((groupName != null) && (!groupName.trim().equals("")))
                {
                Group ldapGroup = Group.findByName(context, groupName);
                    if (ldapGroup == null)
                    {
                        // Oops - the group isn't there.
                        log.warn(LogManager.getHeader(context,
                                "Mbank_specialgroup",
                                "Group defined in Mbank.login.specialgroup
does not exist"));
                        return new int[0];
                    } else
                    {
                        return new int[] { ldapGroup.getID() };
                    }
                }
            }
        }
        catch (Exception npe) {
            // The user is not a Mbank user, so we don't need to worry
about them
        }
        return new int[0];
    }

    /*
     *
     *
     * @return One of:
     *   SUCCESS, BAD_CREDENTIALS, CERT_REQUIRED, NO_SUCH_USER, BAD_ARGS
     */
    public int authenticate(Context context,
                            String netid,
                            String password,
                            String realm,
                            HttpServletRequest request)
        throws SQLException
    {
        log.info(LogManager.getHeader(context, "auth", "attempting trivial
auth of user="+netid));

        // Skip out when no netid or password is given.
        if (netid == null || password == null)
            return BAD_ARGS;

        // Locate the eperson
        EPerson eperson = null;
        try
        {
                eperson = EPerson.findByNetid(context, netid.toLowerCase());
        }
        catch (SQLException e)
        {
        }
        boolean loggedIn = false;

        Mbank Mbank = new Mbank();
        // if they entered a netid that matches an eperson
        if (eperson != null)
        {
            // e-mail address corresponds to active account
            if (eperson.getRequireCertificate())
                return CERT_REQUIRED;
            else if (!eperson.canLogIn())
                return BAD_ARGS;
            {
                if (Mbank.authenticate(netid, password, context))
                {
                    context.setCurrentUser(eperson =
EPerson.findByNetid(context, netid.toLowerCase()));
                    log.info(LogManager
                        .getHeader(context, "authenticate", "type=Mbank"));
                    return SUCCESS;
                }
                else
                   return BAD_CREDENTIALS;
            }
        }

        // the user does not already exist so try and authenticate them
        // with ldap and create an eperson for them
        else
        {
            if (Mbank.authenticate(netid, password, context))
            {
                // Register the new user automatically
                log.info(LogManager.getHeader(context,
                                "autoregister", "netid=" + netid));

                if ((Mbank.email!=null)&&(!Mbank.email.equals("")))
                {
                    try
                    {
                        eperson = EPerson.findByNetid(context, Mbank.login);
                        if (eperson!=null)
                        {
                            log.info(LogManager.getHeader(context,
                                    "type=Mbank-login",
"type=Mbank_but_already_email"));
                            context.setIgnoreAuthorization(true);
                            // Update fields in case they have changed
                                eperson.setEmail(Mbank.email);
                                eperson.setFirstName(Mbank.givenName);
                                eperson.setLastName(Mbank.surName);
                            eperson.update();
                            context.commit();
                            context.setIgnoreAuthorization(false);
                            context.setCurrentUser(eperson);
                            return SUCCESS;
                        }
                        else
                        {
                            if (canSelfRegister(context, request, netid))
                            {
                                // TEMPORARILY turn off authorisation
                                try
                                {
                                    context.setIgnoreAuthorization(true);
                                    eperson = EPerson.create(context);
                                    // Copy entries
                                    eperson.setEmail(Mbank.email);
                                    eperson.setFirstName(Mbank.givenName);
                                    eperson.setLastName(Mbank.surName);
                                    eperson.setNetid(netid.toLowerCase());
                                    eperson.setCanLogIn(true);

AuthenticationManager.initEPerson(context, request, eperson);
                                    eperson.update();
                                    context.commit();
                                    context.setCurrentUser(eperson);
                                }
                                catch (AuthorizeException e)
                                {
                                    return NO_SUCH_USER;
                                }
                                finally
                                {
                                    context.setIgnoreAuthorization(false);
                                }

                                log.info(LogManager.getHeader(context,
"authenticate",
                                            "type=ldap-login, created
ePerson"));
                                return SUCCESS;
                            }
                            else
                            {
                                // No auto-registration for valid certs
                                log.info(LogManager.getHeader(context,
                                                "failed_login",
"type=ldap_but_no_record"));
                                return NO_SUCH_USER;
                            }
                        }
                    }
                    catch (AuthorizeException e)
                    {
                        eperson = null;
                    }
                    finally
                    {
                        context.setIgnoreAuthorization(false);
                    }
                }
            }
        }
        return BAD_ARGS;
      }

    protected class Mbank {
        protected String login, password_encrypted, email, name;
        protected String givenName, surName;
        protected boolean authenticate(String netid, String password,
Context context)
        {
                boolean retval;
            Connection conn =
DriverManager.getConnection("jdbc:postgresql://dbserver./mydb?user=scott&password=secret&ssl=true");
            PreparedStatement st =  conn.prepareStatement("SELECT login,
password_encrypted, email, name FROM mb.t_subject WHERE (email = ? OR login
= ?) AND subject_type IN ('person', 'institution') AND active;");
            st.setString(1, netid);
            st.setString(2, netid);
            ResultSet rs = st.executeQuery();
                if (rs.next()) {
                        login = rs.getString(1);
                        password_encrypted = rs.getString(2);
                        email = rs.getString(3);
                        name = rs.getString(4);
                        int pos = name.lastIndexOf(' ');
                        if (pos < 0) {
                                givenName = surName = name;
                        } else {
                                givenName = name.substring(0, pos);
                                surName = name.substring(pos+1);
                        }
                        if (md5sum(password).equals(password_encrypted)) {
                                retval = true;
                        } else {
                                retval = false;
                        }
                } else {
                        retval = false;
                }
                rs.close();
                st.close();
                return retval;
        }

        String md5sum(String plain)
        {
                // Calculation
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.reset();
                md5.update(plain.getBytes());
                byte[] result = md5.digest();

                // Hex conversion
                StringBuffer hexString = new StringBuffer();
                for (int i = 0; i < result.length; i++) {
                        if (result[i] <= 15 && result[i] >= 0) {
                        hexString.append("0");
                    }
                    hexString.append(Integer.toHexString(0xFF & result[i]));
                }
                return hexString.toString();
        }
    }


    /*
     * Returns URL to which to redirect to obtain credentials (either
password
     * prompt or e.g. HTTPS port for client cert.); null means no redirect.
     *
     * @param context
     *  DSpace context, will be modified (ePerson set) upon success.
     *
     * @param request
     *  The HTTP request that started this operation, or null if not
applicable.
     *
     * @param response
     *  The HTTP response from the servlet method.
     *
     * @return fully-qualified URL
     */
    public String loginPageURL(Context context,
                            HttpServletRequest request,
                            HttpServletResponse response)
    {
        return response.encodeRedirectURL(request.getContextPath() +
                                          "/Mbank-login");
    }

    /**
     * Returns message key for title of the "login" page, to use
     * in a menu showing the choice of multiple login methods.
     *
     * @param context
     *  DSpace context, will be modified (ePerson set) upon success.
     *
     * @return Message key to look up in i18n message catalog.
     */
    public String loginPageTitle(Context context)
    {
        return "org.dspace.eperson.LDAPAuthentication.title";
    }
}



On Tue, Apr 24, 2012 at 3:19 PM, helix84 <[email protected]> wrote:

    On Sat, Apr 21, 2012 at 22:45, Priya S <[email protected]>
wrote:
    > Now I have an instance of my existing dspace (customized) in my laptop
    > instead of fresh installation of dspace.  I would like to know in
which
    > directory I should have the program PasswordAuthentication.java
(which I got
    > it from the URL which u mentioned earlier) to test it. Could you pls
let me
    > know?.

    1) rename it to MyAuthentication.java
    2) change all references of PasswordAuthentication to MyAuthentication
    within the file
    3) put it to
[dspace-src]/dspace-api/src/main/java/org/dspace/authenticate/
    4) run mvn package and ant update
    5) in dspace configuration, change
    plugin.sequence.org.dspace.authenticate.AuthenticationMethod to
    include MyAuthentication
    6) restart tomcat

    Regards,
    ~~helix84
------------------------------------------------------------------------------
Live Security Virtual Conference
Exclusive live event will cover all the ways today's security and 
threat landscape has changed and how IT managers can respond. Discussions 
will include endpoint security, mobile security and the latest in malware 
threats. http://www.accelacomm.com/jaw/sfrnl04242012/114/50122263/
_______________________________________________
DSpace-tech mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/dspace-tech

Reply via email to