LdapUserProvider.java 12.4 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 3055 $
 * $Date: 2005-11-10 21:57:51 -0300 (Thu, 10 Nov 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * 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.
19 20
 */

21
package org.jivesoftware.openfire.ldap;
22

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;

import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;

Gaston Dombiak's avatar
Gaston Dombiak committed
39
import org.jivesoftware.openfire.XMPPServer;
40 41 42 43 44
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.openfire.user.UserCollection;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.openfire.user.UserProvider;
45 46
import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.util.JiveGlobals;
47 48
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
49 50 51 52 53 54 55 56 57 58
import org.xmpp.packet.JID;

/**
 * LDAP implementation of the UserProvider interface. All data in the directory is
 * treated as read-only so any set operations will result in an exception.
 *
 * @author Matt Tucker
 */
public class LdapUserProvider implements UserProvider {

59 60
	private static final Logger Log = LoggerFactory.getLogger(LdapUserProvider.class);

61 62 63
    // LDAP date format parser.
    private static SimpleDateFormat ldapDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

64 65 66 67 68 69
    private LdapManager manager;
    private Map<String, String> searchFields;
    private int userCount = -1;
    private long expiresStamp = System.currentTimeMillis();

    public LdapUserProvider() {
70 71 72
        // Convert XML based provider setup to Database based
        JiveGlobals.migrateProperty("ldap.searchFields");

73 74
        manager = LdapManager.getInstance();
        searchFields = new LinkedHashMap<String,String>();
75
        String fieldList = JiveGlobals.getProperty("ldap.searchFields");
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        // If the value isn't present, default to to username, name, and email.
        if (fieldList == null) {
            searchFields.put("Username", manager.getUsernameField());
            searchFields.put("Name", manager.getNameField());
            searchFields.put("Email", manager.getEmailField());
        }
        else {
            try {
                for (StringTokenizer i=new StringTokenizer(fieldList, ","); i.hasMoreTokens(); ) {
                    String[] field = i.nextToken().split("/");
                    searchFields.put(field[0], field[1]);
                }
            }
            catch (Exception e) {
                Log.error("Error parsing LDAP search fields: " + fieldList, e);
            }
        }
    }

    public User loadUser(String username) throws UserNotFoundException {
96
        if(username.contains("@")) {
Gaston Dombiak's avatar
Gaston Dombiak committed
97 98 99
            if (!XMPPServer.getInstance().isLocal(new JID(username))) {
                throw new UserNotFoundException("Cannot load user of remote server: " + username);
            }
100 101
            username = username.substring(0,username.lastIndexOf("@"));
        }
102 103 104 105 106 107 108 109
        // Un-escape username.
        username = JID.unescapeNode(username);
        DirContext ctx = null;
        try {
            String userDN = manager.findUserDN(username);
            // Load record.
            String[] attributes = new String[]{
                manager.getUsernameField(), manager.getNameField(),
110
                manager.getEmailField(), "createTimestamp", "modifyTimestamp"
111
            };
112
            ctx = manager.getContext(manager.getUsersBaseDN(username));
113 114 115 116 117 118
            Attributes attrs = ctx.getAttributes(userDN, attributes);
            String name = null;
            Attribute nameField = attrs.get(manager.getNameField());
            if (nameField != null) {
                name = (String)nameField.get();
            }
119
            String email = null;
120 121 122 123
            Attribute emailField = attrs.get(manager.getEmailField());
            if (emailField != null) {
                email = (String)emailField.get();
            }
124 125
            Date creationDate = new Date();
            Attribute creationDateField = attrs.get("createTimestamp");
Gaston Dombiak's avatar
Gaston Dombiak committed
126 127
            if (creationDateField != null && "".equals(((String) creationDateField.get()).trim())) {
                creationDate = parseLDAPDate((String) creationDateField.get());
128 129 130
            }
            Date modificationDate = new Date();
            Attribute modificationDateField = attrs.get("modifyTimestamp");
Gaston Dombiak's avatar
Gaston Dombiak committed
131
            if (modificationDateField != null && "".equals(((String) modificationDateField.get()).trim())) {
132 133
                modificationDate = parseLDAPDate((String)modificationDateField.get());
            }
134 135
            // Escape the username so that it can be used as a JID.
            username = JID.escapeNode(username);
136
            return new User(username, name, email, creationDate, modificationDate);
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
        }
        catch (Exception e) {
            throw new UserNotFoundException(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
    }

    public User createUser(String username, String password, String name, String email)
            throws UserAlreadyExistsException
    {
        throw new UnsupportedOperationException();
    }

    public void deleteUser(String username) {
        throw new UnsupportedOperationException();
    }

    public int getUserCount() {
        // Cache user count for 5 minutes.
        if (userCount != -1 && System.currentTimeMillis() < expiresStamp) {
            return userCount;
        }
168
        this.userCount = manager.retrieveListCount(
169
                manager.getUsernameField(),
170
                MessageFormat.format(manager.getSearchFilter(), "*")
171
        );
172
        this.expiresStamp = System.currentTimeMillis() + JiveConstants.MINUTE *5;
173
        return this.userCount;
174 175
    }

176
    public Collection<String> getUsernames() {
177 178 179 180 181 182 183
        return manager.retrieveList(
                manager.getUsernameField(),
                MessageFormat.format(manager.getSearchFilter(), "*"),
                -1,
                -1,
                null
        );
184
    }
185 186 187 188
    
    public Collection<User> getUsers() {
        return getUsers(-1, -1);
    }
189 190

    public Collection<User> getUsers(int startIndex, int numResults) {
191 192 193 194 195 196 197 198
        List<String> userlist = manager.retrieveList(
                manager.getUsernameField(),
                MessageFormat.format(manager.getSearchFilter(), "*"),
                startIndex,
                numResults,
                manager.getUsernameSuffix()
        );
        return new UserCollection(userlist.toArray(new String[userlist.size()]));
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    }

    public void setName(String username, String name) throws UserNotFoundException {
        throw new UnsupportedOperationException();
    }

    public void setEmail(String username, String email) throws UserNotFoundException {
        throw new UnsupportedOperationException();
    }

    public void setCreationDate(String username, Date creationDate) throws UserNotFoundException {
        throw new UnsupportedOperationException();
    }

    public void setModificationDate(String username, Date modificationDate) throws UserNotFoundException {
        throw new UnsupportedOperationException();
    }

    public Set<String> getSearchFields() throws UnsupportedOperationException {
        return Collections.unmodifiableSet(searchFields.keySet());
    }

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    public void setSearchFields(String fieldList) {
        this.searchFields = new LinkedHashMap<String,String>();
        // If the value isn't present, default to to username, name, and email.
        if (fieldList == null) {
            searchFields.put("Username", manager.getUsernameField());
            searchFields.put("Name", manager.getNameField());
            searchFields.put("Email", manager.getEmailField());
        }
        else {
            try {
                for (StringTokenizer i=new StringTokenizer(fieldList, ","); i.hasMoreTokens(); ) {
                    String[] field = i.nextToken().split("/");
                    searchFields.put(field[0], field[1]);
                }
            }
            catch (Exception e) {
                Log.error("Error parsing LDAP search fields: " + fieldList, e);
            }
        }
240
        JiveGlobals.setProperty("ldap.searchFields", fieldList);
241 242
    }

243 244
    public Collection<User> findUsers(Set<String> fields, String query)
            throws UnsupportedOperationException
245 246 247 248 249 250
    {
        return findUsers(fields, query, -1, -1);
    }

    public Collection<User> findUsers(Set<String> fields, String query, int startIndex,
            int numResults) throws UnsupportedOperationException
251 252 253 254 255 256 257 258 259 260 261 262
    {
        if (fields.isEmpty() || query == null || "".equals(query)) {
            return Collections.emptyList();
        }
        if (!searchFields.keySet().containsAll(fields)) {
            throw new IllegalArgumentException("Search fields " + fields + " are not valid.");
        }
        // Make the query be a wildcard search by default. So, if the user searches for
        // "John", make the search be "John*" instead.
        if (!query.endsWith("*")) {
            query = query + "*";
        }
263 264 265 266 267 268 269 270
        StringBuilder filter = new StringBuilder();
        //Add the global search filter so only those users the directory administrator wants to include
        //are returned from the directory
        filter.append("(&(");
        filter.append(MessageFormat.format(manager.getSearchFilter(),"*"));
        filter.append(")");
        if (fields.size() > 1) {
            filter.append("(|");
271
        }
272 273 274
        for (String field:fields) {
            String attribute = searchFields.get(field);
            filter.append("(").append(attribute).append("=").append(query).append(")");
275
        }
276 277
        if (fields.size() > 1) {
            filter.append(")");
278
        }
279 280 281 282 283 284 285 286 287
        filter.append(")");
        List<String> userlist = manager.retrieveList(
                manager.getUsernameField(),
                filter.toString(),
                startIndex,
                numResults,
                manager.getUsernameSuffix()
        );
        return new UserCollection(userlist.toArray(new String[userlist.size()]));
288 289 290 291 292
    }

    public boolean isReadOnly() {
        return true;
    }
293

294 295 296 297 298 299 300 301
    public boolean isNameRequired() {
        return false;
    }

    public boolean isEmailRequired() {
        return false;
    }

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    /**
     * Parses dates/time stamps stored in LDAP. Some possible values:
     *
     * <ul>
     *      <li>20020228150820</li>
     *      <li>20030228150820Z</li>
     *      <li>20050228150820.12</li>
     *      <li>20060711011740.0Z</li>
     * </ul>
     *
     * @param dateText the date string.
     * @return the Date.
     */
    private static Date parseLDAPDate(String dateText) {
        // If the date ends with a "Z", that means that it's in the UTC time zone. Otherwise,
        // Use the default time zone.
        boolean useUTC = false;
        if (dateText.endsWith("Z")) {
            useUTC = true;
        }
        Date date = new Date();
        try {
            if (useUTC) {
                ldapDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            }
            else {
                ldapDateFormat.setTimeZone(TimeZone.getDefault());
            }
            date = ldapDateFormat.parse(dateText);
        }
        catch (Exception e) {
333
            Log.error(e.getMessage(), e);
334 335 336
        }
        return date;
    }
337
}