<commit_before>/**
 * Copyright 2014 (c) <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ru.efo.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * {@link org.springframework.security.core.userdetails.UserDetailsService} implementation for Spring Security
 * to provide authentication with Microsoft Active Directory
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class ADUserDetailsService implements UserDetailsService, AuthenticationProvider {

    private static final Logger logger = Logger.getLogger(ADUserDetailsService.class.getName());

    private String ldapUrl;
    private String ldapAccount;
    private String ldapPassword;
    private String userSearchBase;
    private String groupSearchBase;
    private String userSuffix;
    private boolean recursiveRoleSearch = true;
    private Map<String, String> rolesMapping = null;
    private String rolePrefix = "ROLE_";
    private String displayNameAttribute = "displayName";
    private String emailAttribute = "mail";
    private String phoneAttribute = "telephoneNumber";

    /**
     * @return the connection url to the Domain Controller
     */
    public String getLdapUrl() {
        return ldapUrl;
    }

    /**
     * Set the connection url to the Active Directory Domain Controller.
     * For example: <code>ldap://dc1.example.com:389</code>
     *
     * @param ldapUrl the connection url
     */
    public void setLdapUrl(String ldapUrl) {
        this.ldapUrl = ldapUrl;
    }

    /**
     * @return the Active Directory account to discovering user information and groups
     */
    public String getLdapAccount() {
        return ldapAccount;
    }

    /**
     * Set the Active Directory account to discovering user information and groups
     *
     * @param ldapAccount the account
     */
    public void setLdapAccount(String ldapAccount) {
        this.ldapAccount = ldapAccount;
    }

    /**
     * @return password for {@link #getLdapAccount()}
     */
    public String getLdapPassword() {
        return ldapPassword;
    }

    /**
     * Set the password for  {@link #getLdapAccount()}
     *
     * @param ldapPassword the password
     */
    public void setLdapPassword(String ldapPassword) {
        this.ldapPassword = ldapPassword;
    }

    /**
     * @return the base DN to search user accounts
     */
    public String getUserSearchBase() {
        return userSearchBase;
    }

    /**
     * Set the base DN to search users accounts.
     * For example: <code>dc=example,dc=com</code>
     *
     * @param userSearchBase the DN
     */
    public void setUserSearchBase(String userSearchBase) {
        this.userSearchBase = userSearchBase;
        if (userSuffix == null && userSearchBase != null) {
            // If userSuffix is not set then determine it from searchBase
            final Pattern pattern = Pattern.compile("dc\\s*=\\s*(.+)", Pattern.CASE_INSENSITIVE);
            userSuffix = "";
            for (String part : userSearchBase.split(",")) {
                final Matcher matcher = pattern.matcher(part);
                if (matcher.matches()) {
                    userSuffix += (userSuffix.isEmpty() ? "@" : ".") + matcher.group(1);
                }
            }
        }
    }

    /**
     * @return the base DN to search groups<commit_msg>userSuffix matching fixed<commit_after>/**
 * Copyright 2014 (c) <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ru.efo.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * {@link org.springframework.security.core.userdetails.UserDetailsService} implementation for Spring Security
 * to provide authentication with Microsoft Active Directory
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class ADUserDetailsService implements UserDetailsService, AuthenticationProvider {

    private static final Logger logger = Logger.getLogger(ADUserDetailsService.class.getName());

    private String ldapUrl;
    private String ldapAccount;
    private String ldapPassword;
    private String userSearchBase;
    private String groupSearchBase;
    private String userSuffix;
    private boolean recursiveRoleSearch = true;
    private Map<String, String> rolesMapping = null;
    private String rolePrefix = "ROLE_";
    private String displayNameAttribute = "displayName";
    private String emailAttribute = "mail";
    private String phoneAttribute = "telephoneNumber";

    /**
     * @return the connection url to the Domain Controller
     */
    public String getLdapUrl() {
        return ldapUrl;
    }

    /**
     * Set the connection url to the Active Directory Domain Controller.
     * For example: <code>ldap://dc1.example.com:389</code>
     *
     * @param ldapUrl the connection url
     */
    public void setLdapUrl(String ldapUrl) {
        this.ldapUrl = ldapUrl;
    }

    /**
     * @return the Active Directory account to discovering user information and groups
     */
    public String getLdapAccount() {
        return ldapAccount;
    }

    /**
     * Set the Active Directory account to discovering user information and groups
     *
     * @param ldapAccount the account
     */
    public void setLdapAccount(String ldapAccount) {
        this.ldapAccount = ldapAccount;
    }

    /**
     * @return password for {@link #getLdapAccount()}
     */
    public String getLdapPassword() {
        return ldapPassword;
    }

    /**
     * Set the password for  {@link #getLdapAccount()}
     *
     * @param ldapPassword the password
     */
    public void setLdapPassword(String ldapPassword) {
        this.ldapPassword = ldapPassword;
    }

    /**
     * @return the base DN to search user accounts
     */
    public String getUserSearchBase() {
        return userSearchBase;
    }

    /**
     * Set the base DN to search users accounts.
     * For example: <code>dc=example,dc=com</code>
     *
     * @param userSearchBase the DN
     */
    public void setUserSearchBase(String userSearchBase) {
        this.userSearchBase = userSearchBase;
        if (userSuffix == null && userSearchBase != null) {
            // If userSuffix is not set then determine it from searchBase
            final Pattern pattern = Pattern.compile("dc\\s*=\\s*([^,]+)", Pattern.CASE_INSENSITIVE);
            userSuffix = "";
            final Matcher matcher = pattern.matcher(userSearchBase);
            while (matcher.find()) {
                userSuffix += (userSuffix.isEmpty() ? "@" : ".") + matcher.group(1);
            }
        }
    }

    /**
     * @return the base DN to search groups
{'fraction_non_alphanumeric': 0.09293878859096251, 'fraction_numerical': 0.0027774810383506036, 'mean_word_length': 3.2019748653500897, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4888990', 'n_tokens_mistral': 2496, 'n_tokens_neox': 2453, 'n_words': 739}