View Javadoc
1   /*
2    * Copyright 2024-2026 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.spring.security.ldaptive.authentication;
18  
19  import static org.springframework.util.ObjectUtils.isEmpty;
20  
21  import java.util.Optional;
22  import lombok.AccessLevel;
23  import lombok.Getter;
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.bremersee.ldaptive.LdaptiveException;
27  import org.bremersee.ldaptive.LdaptiveTemplate;
28  import org.bremersee.spring.security.core.EmailToUsernameResolver;
29  import org.ldaptive.FilterTemplate;
30  import org.ldaptive.LdapAttribute;
31  import org.ldaptive.SearchRequest;
32  
33  /**
34   * The email to username resolver by ldap attribute.
35   *
36   * @author Christian Bremer
37   */
38  public class EmailToUsernameResolverByLdapAttribute implements EmailToUsernameResolver {
39  
40    /**
41     * The Logger.
42     */
43    protected final Log logger = LogFactory.getLog(this.getClass());
44  
45    /**
46     * The properties.
47     */
48    @Getter(AccessLevel.PROTECTED)
49    private final LdaptiveAuthenticationProperties properties;
50  
51    /**
52     * The ldaptive template.
53     */
54    @Getter(AccessLevel.PROTECTED)
55    private final LdaptiveTemplate ldaptiveTemplate;
56  
57    /**
58     * Instantiates a new Email to username resolver by ldap attribute.
59     *
60     * @param properties the properties
61     * @param ldaptiveTemplate the ldaptive template
62     */
63    public EmailToUsernameResolverByLdapAttribute(
64        LdaptiveAuthenticationProperties properties,
65        LdaptiveTemplate ldaptiveTemplate) {
66      this.properties = properties;
67      this.ldaptiveTemplate = ldaptiveTemplate;
68    }
69  
70    @Override
71    public Optional<String> getUsernameByEmail(String email) {
72      return Optional.ofNullable(email)
73          .filter(mail -> isValidEmail(mail)
74              && areRequiredPropertiesPresent())
75          .flatMap(this::findUsernameByEmail);
76    }
77  
78    /**
79     * Determines whether required properties are present or not.
80     *
81     * @return the boolean
82     */
83    protected boolean areRequiredPropertiesPresent() {
84      return !isEmpty(getProperties().getUserBaseDn())
85          && !isEmpty(getProperties().getUserObjectClass())
86          && !isEmpty(getProperties().getUserFindOneSearchScope())
87          && !isEmpty(getProperties().getEmailAttribute())
88          && !isEmpty(getProperties().getUsernameAttribute());
89    }
90  
91    private Optional<String> findUsernameByEmail(String email) {
92      try {
93        String filter = String.format("(&(objectClass=%s)(%s={0}))",
94            getProperties().getUserObjectClass(), getProperties().getEmailAttribute());
95        SearchRequest searchRequest = SearchRequest.builder()
96            .dn(getProperties().getUserBaseDn())
97            .filter(FilterTemplate.builder()
98                .filter(filter)
99                .parameters(email)
100               .build())
101           .scope(getProperties().getUserFindOneSearchScope())
102           .sizeLimit(1)
103           .build();
104       return getLdaptiveTemplate().findOne(searchRequest)
105           .map(ldapEntry -> ldapEntry.getAttribute(getProperties().getUsernameAttribute()))
106           .map(LdapAttribute::getStringValue);
107 
108     } catch (LdaptiveException e) {
109       logger.warn("Resolve username by email '" + email + "' failed.", e);
110       return Optional.empty();
111     }
112   }
113 }