<commit_before>/*
 * Copyright (C) 2005 <NAME>
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the
 *
 * Free Software Foundation, Inc.
 * 59 Temple Place, Suite 330
 * Boston, MA 02111-1307
 * USA
 *
 * Or, you may view it online at
 * http://www.opensource.org/licenses/lgpl-license.php
 */
package org.jsecurity.ri.realm.ldap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsecurity.authc.AuthenticationException;
import org.jsecurity.authc.AuthenticationToken;
import org.jsecurity.authc.IncorrectCredentialException;
import org.jsecurity.authc.UsernamePasswordToken;
import org.jsecurity.authc.module.AuthenticationInfo;
import org.jsecurity.authc.module.AuthenticationModule;
import org.jsecurity.ri.authc.module.SimpleAuthenticationInfo;
import org.jsecurity.ri.realm.AbstractCachingRealm;
import org.jsecurity.ri.realm.AuthorizationInfo;
import org.jsecurity.ri.util.UsernamePrincipal;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.security.Principal;
import java.util.*;

/**
 * <p>An {@link AuthenticationModule} that authenticates with an LDAP
 * server to build the authorization context for a user.  This implementation only returns roles for a
 * particular user, and not permissions - but it can be subclassed to build a permission
 * list as well.</p>
 *
 * <p>Implementations would need to implement the
 * {@link #queryForLdapDirectoryInfo(String, javax.naming.ldap.LdapContext)} abstract method,
 * and may wish to override
 * {@link #buildAuthenticationInfo(String, char[], LdapDirectoryInfo)}.</p>
 *
 * @see LdapDirectoryInfo
 * @see #queryForLdapDirectoryInfo(String, javax.naming.ldap.LdapContext)
 * @see #buildAuthenticationInfo(String, char[], LdapDirectoryInfo)
 *
 * @since 0.1
 * @author <NAME>
 */
public abstract class LdapRealm extends AbstractCachingRealm {

    /*--------------------------------------------
    |             C O N S T A N T S             |
    ============================================*/

    /*--------------------------------------------
    |    I N S T A N C E   V A R I A B L E S    |
    ============================================*/
    /**
     * Commons-logger.
     */
    protected transient final Log log = LogFactory.getLog( getClass() );

    /**
     * The type of LDAP authentication to perform.
     */
    protected String authentication = "simple";

    /**
     * A suffix appended to the username. This is typically for
     * domain names.  (e.g. "@MyDomain.local")
     */
    protected String principalSuffix = null;

    /**
     * The search base for the search to perform in the LDAP server.
     * (e.g. OU=OrganizationName,DC=MyDomain,DC=local )
     */
    protected String searchBase = null;

    /**
     * The context factory to use. This defaults to the SUN LDAP JNDI implementation
     * but can be overridden to use custom LDAP factories.
     */
    protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

    /**
     * The LDAP url to connect to. (e.g. ldap://<ldapDirectoryHostname>:<port>)
     */
    protected String url = null;

    /**
     * The LDAP referral property.  Defaults to "follow"
     */
    protected String refferal = "follow";


    /*--------------------------------------------
    |         C O N S T R U C T O R S           |
    ============================================*/

    /*--------------------------------------------
    |  A C C E S S O R S / M O D I F I E R S    |
    ============================================*/

    /*--------------------------------------------
    |               M E T H O D S               |
    ============================================*/
    public void setAuthentication(String authentication) {
        this.authentication = authentication;
    }

    public void setPrincipalSuffix(String principalSuffix) {
        this.principalSuffix = principalSuffix;
    }

    public void setSearchBase(String searchBase) {
        this.searchBase = searchBase;
    }

    public void setContextFactory(String contextFactory) {
        this.contextFactory = contextFactory;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setRefferal(String refferal) {
        this.refferal = refferal;
    }

    /*--------------------------------------------
    |  A C C E S S O R S / M O D I F I E R S    |
    ============================================*/

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;

        LdapDirectoryInfo ldapDirectoryInfo = null;
        try {

            ldapDirectoryInfo = performAuthentication(upToken.getUsername(), upToken.getPassword());

        } catch (NamingException e) {
            final String message = "LDAP naming error while attempting to authenticate user.";
            if( log.isErrorEnabled() ) {
                log.error( message );
            }
        }

        if( ldapDirectoryInfo != null ) {
            return buildAuthenticationInfo( upToken.getUsername(), upToken.getPassword(), ldapDirectoryInfo );
        } else {
            return null;
        }
    }

    /**
     * Builds an {@link org.jsecurity.authc.module.AuthenticationInfo} object to return based on an {@link org.jsecurity.ri.realm.ldap.LdapDirectoryInfo} object
     * returned from {@link #performAuthentication(String, char[])}
     *
     * @param username the username of the user being authenticated.
     * @param password the password of the user being authenticated.<commit_msg>Added exception to log output.<commit_after>/*
 * Copyright (C) 2005 <NAME>
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the
 *
 * Free Software Foundation, Inc.
 * 59 Temple Place, Suite 330
 * Boston, MA 02111-1307
 * USA
 *
 * Or, you may view it online at
 * http://www.opensource.org/licenses/lgpl-license.php
 */
package org.jsecurity.ri.realm.ldap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsecurity.authc.AuthenticationException;
import org.jsecurity.authc.AuthenticationToken;
import org.jsecurity.authc.IncorrectCredentialException;
import org.jsecurity.authc.UsernamePasswordToken;
import org.jsecurity.authc.module.AuthenticationInfo;
import org.jsecurity.authc.module.AuthenticationModule;
import org.jsecurity.ri.authc.module.SimpleAuthenticationInfo;
import org.jsecurity.ri.realm.AbstractCachingRealm;
import org.jsecurity.ri.realm.AuthorizationInfo;
import org.jsecurity.ri.util.UsernamePrincipal;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.security.Principal;
import java.util.*;

/**
 * <p>An {@link AuthenticationModule} that authenticates with an LDAP
 * server to build the authorization context for a user.  This implementation only returns roles for a
 * particular user, and not permissions - but it can be subclassed to build a permission
 * list as well.</p>
 *
 * <p>Implementations would need to implement the
 * {@link #queryForLdapDirectoryInfo(String, javax.naming.ldap.LdapContext)} abstract method,
 * and may wish to override
 * {@link #buildAuthenticationInfo(String, char[], LdapDirectoryInfo)}.</p>
 *
 * @see LdapDirectoryInfo
 * @see #queryForLdapDirectoryInfo(String, javax.naming.ldap.LdapContext)
 * @see #buildAuthenticationInfo(String, char[], LdapDirectoryInfo)
 *
 * @since 0.1
 * @author <NAME>
 */
public abstract class LdapRealm extends AbstractCachingRealm {

    /*--------------------------------------------
    |             C O N S T A N T S             |
    ============================================*/

    /*--------------------------------------------
    |    I N S T A N C E   V A R I A B L E S    |
    ============================================*/
    /**
     * Commons-logger.
     */
    protected transient final Log log = LogFactory.getLog( getClass() );

    /**
     * The type of LDAP authentication to perform.
     */
    protected String authentication = "simple";

    /**
     * A suffix appended to the username. This is typically for
     * domain names.  (e.g. "@MyDomain.local")
     */
    protected String principalSuffix = null;

    /**
     * The search base for the search to perform in the LDAP server.
     * (e.g. OU=OrganizationName,DC=MyDomain,DC=local )
     */
    protected String searchBase = null;

    /**
     * The context factory to use. This defaults to the SUN LDAP JNDI implementation
     * but can be overridden to use custom LDAP factories.
     */
    protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

    /**
     * The LDAP url to connect to. (e.g. ldap://<ldapDirectoryHostname>:<port>)
     */
    protected String url = null;

    /**
     * The LDAP referral property.  Defaults to "follow"
     */
    protected String refferal = "follow";


    /*--------------------------------------------
    |         C O N S T R U C T O R S           |
    ============================================*/

    /*--------------------------------------------
    |  A C C E S S O R S / M O D I F I E R S    |
    ============================================*/

    /*--------------------------------------------
    |               M E T H O D S               |
    ============================================*/
    public void setAuthentication(String authentication) {
        this.authentication = authentication;
    }

    public void setPrincipalSuffix(String principalSuffix) {
        this.principalSuffix = principalSuffix;
    }

    public void setSearchBase(String searchBase) {
        this.searchBase = searchBase;
    }

    public void setContextFactory(String contextFactory) {
        this.contextFactory = contextFactory;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setRefferal(String refferal) {
        this.refferal = refferal;
    }

    /*--------------------------------------------
    |  A C C E S S O R S / M O D I F I E R S    |
    ============================================*/

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;

        LdapDirectoryInfo ldapDirectoryInfo = null;
        try {

            ldapDirectoryInfo = performAuthentication(upToken.getUsername(), upToken.getPassword());

        } catch (NamingException e) {
            final String message = "LDAP naming error while attempting to authenticate user.";
            if( log.isErrorEnabled() ) {
                log.error( message, e );
            }
        }

        if( ldapDirectoryInfo != null ) {
            return buildAuthenticationInfo( upToken.getUsername(), upToken.getPassword(), ldapDirectoryInfo );
        } else {
            return null;
        }
    }

    /**
     * Builds an {@link org.jsecurity.authc.module.AuthenticationInfo} object to return based on an {@link org.jsecurity.ri.realm.ldap.LdapDirectoryInfo} object
     * returned from {@link #performAuthentication(String, char[])}
     *
     * @param username the username of the user being authenticated.
     * @param password the password of the user being authenticated.
{'fraction_non_alphanumeric': 0.1648231811808693, 'fraction_numerical': 0.0034273251285246924, 'mean_word_length': 2.569363358354184, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6644777', 'n_tokens_mistral': 3460, 'n_tokens_neox': 3339, 'n_words': 1112}