com.sfs.dao.LdapAuthenticationDAOImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.sfs.dao.LdapAuthenticationDAOImpl.java

Source

/*******************************************************************************
 * Copyright (c) 2009 David Harrison.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * Contributors:
 *     David Harrison - initial API and implementation
 ******************************************************************************/
package com.sfs.dao;

import com.sfs.beans.UserBean;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ldap.ContextSource;
import org.springframework.ldap.ContextMapper;
import org.springframework.ldap.LdapTemplate;
import org.springframework.ldap.support.DirContextAdapter;

/**
 * The Class LdapUserDAOImpl.
 */
public class LdapAuthenticationDAOImpl implements AuthenticationDAO {

    /** The data logger. */
    private static Logger dataLogger = Logger.getLogger(LdapAuthenticationDAOImpl.class);

    /** The group container. */
    private String groupContainer = "";

    /** The search base. */
    private String searchBase = "";

    /** The search filter. */
    private String searchFilter = "";

    /** The user name. */
    private String userName = "cn";

    /** The preferred name. */
    private String preferredName = "givenName";

    /** The last name. */
    private String lastName = "sn";

    /** The email. */
    private String email = "mail";

    /** The group membership. */
    private String groupMembership = "groupMembership";

    /** The context source. */
    @Resource
    private ContextSource contextSource;

    /**
     * Sets the group container.
     *
     * @param groupContainerVal the new group container
     */
    public final void setGroupContainer(final String groupContainerVal) {
        this.groupContainer = groupContainerVal;
    }

    /**
     * Sets the search base.
     *
     * @param searchBaseVal the new search base
     */
    public final void setSearchBase(final String searchBaseVal) {
        this.searchBase = searchBaseVal;
    }

    /**
     * Gets the search base.
     *
     * @return the search base
     */
    protected final String getSearchBase() {
        return this.searchBase;
    }

    /**
     * Sets the search filter.
     *
     * @param searchFilterVal the new search filter
     */
    public final void setSearchFilter(final String searchFilterVal) {
        this.searchFilter = searchFilterVal;
    }

    /**
     * Gets the search filter.
     *
     * @return the search filter
     */
    protected final String getSearchFilter() {
        return this.searchFilter;
    }

    /**
     * Sets the user name.
     *
     * @param userNameVal the new user name
     */
    public final void setUserName(final String userNameVal) {
        this.userName = userNameVal;
    }

    /**
     * Sets the preferred name.
     *
     * @param preferredNameVal the new preferred name
     */
    public final void setPreferredName(final String preferredNameVal) {
        this.preferredName = preferredNameVal;
    }

    /**
     * Sets the last name.
     *
     * @param lastNameVal the new last name
     */
    public final void setLastName(final String lastNameVal) {
        this.lastName = lastNameVal;
    }

    /**
     * Sets the email.
     *
     * @param emailVal the new email
     */
    public final void setEmail(final String emailVal) {
        this.email = emailVal;
    }

    /**
     * Sets the group membership.
     *
     * @param groupMembershipVal the new group membership
     */
    public final void setGroupMembership(final String groupMembershipVal) {
        this.groupMembership = groupMembershipVal;
    }

    /**
     * Load the UserBean.
     *
     * @param userNameVal the user name
     * @param request the servlet request
     *
     * @return the user bean
     *
     * @throws SFSDaoException the SFS dao exception
     */
    @SuppressWarnings("unchecked")
    public final UserBean load(final String userNameVal, final HttpServletRequest request) throws SFSDaoException {
        // Loads user details into bean using a supplied username
        if (userNameVal == null) {
            throw new SFSDaoException("Username cannot be null");
        }
        if (userNameVal.compareTo("") == 0) {
            throw new SFSDaoException("Username cannot be an empty string");
        }

        UserBean user = null;

        final String base = this.searchBase;
        final String filter = StringUtils.replace(this.searchFilter, "%u", userNameVal);

        final LdapTemplate ldapTemplate = new LdapTemplate(contextSource);

        Collection<UserBean> users = ldapTemplate.search(base, filter, new ContextMapper() {
            public Object mapFromContext(final Object ctx) {
                DirContextAdapter adapter = (DirContextAdapter) ctx;
                return loadDetails(adapter);
            }
        });

        for (UserBean loadedUser : users) {
            user = loadedUser;
        }

        if (user == null) {
            throw new SFSDaoException("A user object for this username " + "was not found");
        }
        return user;
    }

    /**
     * Load details.
     *
     * @param adapter the adapter
     *
     * @return the user bean
     */
    private UserBean loadDetails(final DirContextAdapter adapter) {

        final UserBean user = new UserBean();

        user.setDN(adapter.getDn().toString());
        user.setUserName(adapter.getStringAttribute(this.userName));
        user.setPreferredName(adapter.getStringAttribute(this.preferredName));
        user.setLastName(adapter.getStringAttribute(this.lastName));
        user.setEmail(adapter.getStringAttribute(this.email));
        String[] roleDNs = adapter.getStringAttributes(this.groupMembership);

        final Collection<String> roles = new ArrayList<String>();
        if (roleDNs != null) {
            for (String role : roleDNs) {
                // See which valid roles this user has
                final int firstAppostrophie = role.indexOf(",");
                final String groupType = role.substring(firstAppostrophie + 1);
                if (StringUtils.equalsIgnoreCase(groupType, this.groupContainer)) {
                    final int startOfGroup = role.indexOf("=");
                    final String className = role.substring(startOfGroup + 1, firstAppostrophie);
                    roles.add(className);
                }
            }
        }
        user.setMemberOf(roles);

        if (roles.size() > 0) {
            /** The user belongs to one valid role, log in **/
            dataLogger.debug("User has at least one valid role - logged in");
            user.setLoggedIn(true);
        }

        return user;
    }
}