UserManager.java 18.7 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 1217 $
 * $Date: 2005-04-11 18:11:06 -0300 (Mon, 11 Apr 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7 8
 *
 * This software is published under the terms of the GNU Public License (GPL),
9 10
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
11 12
 */

13
package org.jivesoftware.openfire.user;
14

15
import org.dom4j.Element;
16 17 18
import org.jivesoftware.openfire.IQResultListener;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.event.UserEventDispatcher;
19 20 21 22
import org.jivesoftware.openfire.event.UserEventListener;
import org.jivesoftware.stringprep.Stringprep;
import org.jivesoftware.stringprep.StringprepException;
import org.jivesoftware.util.*;
23
import org.jivesoftware.util.cache.Cache;
24
import org.jivesoftware.util.cache.CacheFactory;
25 26
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
27

28
import java.util.*;
29 30 31 32 33 34 35

/**
 * Manages users, including loading, creating and deleting.
 *
 * @author Matt Tucker
 * @see User
 */
36
public class UserManager implements IQResultListener {
37

38 39 40 41 42
    // Wrap this guy up so we can mock out the UserManager class.
    private static class UserManagerContainer {
        private static UserManager instance = new UserManager();
    }

43
    /**
44 45 46 47 48 49
     * Returns the currently-installed UserProvider. <b>Warning:</b> in virtually all
     * cases the user provider should not be used directly. Instead, the appropriate
     * methods in UserManager should be called. Direct access to the user provider is
     * only provided for special-case logic.
     *
     * @return the current UserProvider.
50
     */
51 52 53 54
    public static UserProvider getUserProvider() {
        return UserManagerContainer.instance.provider;
    }

55
    /**
56 57 58
     * Returns a singleton UserManager instance.
     *
     * @return a UserManager instance.
59
     */
60 61 62 63 64 65 66 67 68
    public static UserManager getInstance() {
        return UserManagerContainer.instance;
    }

    /** Cache of local users. */
    private Cache<String, User> userCache;
    /** Cache if a local or remote user exists. */
    private Cache<String, Boolean> remoteUsersCache;
    private UserProvider provider;
69

70
    private UserManager() {
71
        // Initialize caches.
72
        userCache = CacheFactory.createCache("User");
Gaston Dombiak's avatar
Gaston Dombiak committed
73
        remoteUsersCache = CacheFactory.createCache("Remote Users Existence");
74

75
        // Load a user provider.
76 77 78 79 80
        initProvider();

        // Detect when a new auth provider class is set
        PropertyEventListener propListener = new PropertyEventListener() {
            public void propertySet(String property, Map params) {
81 82 83
                if ("provider.user.className".equals(property)) {
                    initProvider();
                }
84 85 86 87 88 89 90
            }

            public void propertyDeleted(String property, Map params) {
                //Ignore
            }

            public void xmlPropertySet(String property, Map params) {
91
                //Ignore
92 93 94 95 96 97 98
            }

            public void xmlPropertyDeleted(String property, Map params) {
                //Ignore
            }
        };
        PropertyEventDispatcher.addListener(propListener);
99 100 101

        UserEventListener userListener = new UserEventListener() {
            public void userCreated(User user, Map<String, Object> params) {
102 103
                // Since the user could be created by the provider, add it possible again
                userCache.put(user.getUsername(), user);
104 105 106
            }

            public void userDeleting(User user, Map<String, Object> params) {
107 108
                // Since the user could be deleted by the provider, remove it possible again
                userCache.remove(user.getUsername());
109 110 111 112 113 114 115 116 117
            }

            public void userModified(User user, Map<String, Object> params) {
                // Set object again in cache. This is done so that other cluster nodes
                // get refreshed with latest version of the user
                userCache.put(user.getUsername(), user);
            }
        };
        UserEventDispatcher.addListener(userListener);
118 119 120 121
    }

    /**
     * Creates a new User. Required values are username and password. The email address
122 123
     * and name can optionally be <tt>null</tt>, unless the UserProvider deems that
     * either of them are required.
124 125 126
     *
     * @param username the new and unique username for the account.
     * @param password the password for the account (plain text).
127 128
     * @param name the name of the user, which can be <tt>null</tt> unless the UserProvider
     *      deems that it's required.
129
     * @param email the email address to associate with the new account, which can
130
     *      be <tt>null</tt>, unless the UserProvider deems that it's required.
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
     * @return a new User.
     * @throws UserAlreadyExistsException if the username already exists in the system.
     * @throws UnsupportedOperationException if the provider does not support the
     *      operation.
     */
    public User createUser(String username, String password, String name, String email)
            throws UserAlreadyExistsException
    {
        if (provider.isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }
        // Make sure that the username is valid.
        try {
            username = Stringprep.nodeprep(username);
        }
        catch (StringprepException se) {
            throw new IllegalArgumentException("Invalid username: " + username,  se);
        }
149
        if (provider.isNameRequired() && (name == null || name.matches("\\s*"))) {
150 151
            throw new IllegalArgumentException("Invalid or empty name specified with provider that requires name. User: "
                                                + username + " Name: " + name);
152 153
        }
        if (provider.isEmailRequired() && !StringUtils.isValidEmailAddress(email)) {
154 155
            throw new IllegalArgumentException("Invalid or empty email address specified with provider that requires email address. User: "
                                                + username + " Email: " + email);
156
        }
157 158 159 160
        User user = provider.createUser(username, password, name, email);
        userCache.put(username, user);

        // Fire event.
161 162
        Map<String,Object> params = Collections.emptyMap();
        UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_created, params);
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

        return user;
    }

    /**
     * Deletes a user (optional operation).
     *
     * @param user the user to delete.
     */
    public void deleteUser(User user) {
        if (provider.isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }

        String username = user.getUsername();
        // Make sure that the username is valid.
        try {
            username = Stringprep.nodeprep(username);
        }
        catch (StringprepException se) {
            throw new IllegalArgumentException("Invalid username: " + username,  se);
        }

        // Fire event.
187 188
        Map<String,Object> params = Collections.emptyMap();
        UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_deleting, params);
189 190 191 192 193 194 195 196 197 198 199 200 201 202

        provider.deleteUser(user.getUsername());
        // Remove the user from cache.
        userCache.remove(user.getUsername());
    }

    /**
     * Returns the User specified by username.
     *
     * @param username the username of the user.
     * @return the User that matches <tt>username</tt>.
     * @throws UserNotFoundException if the user does not exist.
     */
    public User getUser(String username) throws UserNotFoundException {
203 204 205
        if (username == null) {
            throw new UserNotFoundException("Username cannot be null");
        }
206 207
        // Make sure that the username is valid.
        username = username.trim().toLowerCase();
208
        User user = userCache.get(username);
209
        if (user == null) {
210 211
            synchronized (username.intern()) {
                user = userCache.get(username);
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
                if (user == null) {
                    user = provider.loadUser(username);
                    userCache.put(username, user);
                }
            }
        }
        return user;
    }

    /**
     * Returns the total number of users in the system.
     *
     * @return the total number of users.
     */
    public int getUserCount() {
        return provider.getUserCount();
    }

    /**
     * Returns an unmodifiable Collection of all users in the system.
     *
     * @return an unmodifiable Collection of all users.
     */
    public Collection<User> getUsers() {
        return provider.getUsers();
    }

239 240 241 242 243 244 245 246 247
    /**
     * Returns an unmodifiable Collection of usernames of all users in the system.
     *
     * @return an unmodifiable Collection of all usernames in the system.
     */
    public Collection<String> getUsernames() {
        return provider.getUsernames();
    }

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    /**
     * Returns an unmodifiable Collection of all users starting at <tt>startIndex</tt>
     * with the given number of results. This is useful to support pagination in a GUI
     * where you may only want to display a certain number of results per page. It is
     * possible that the number of results returned will be less than that specified
     * by <tt>numResults</tt> if <tt>numResults</tt> is greater than the number of
     * records left to display.
     *
     * @param startIndex the beginning index to start the results at.
     * @param numResults the total number of results to return.
     * @return a Collection of users in the specified range.
     */
    public Collection<User> getUsers(int startIndex, int numResults) {
        return provider.getUsers(startIndex, numResults);
    }

    /**
     * Returns the set of fields that can be used for searching for users. Each field
     * returned must support wild-card and keyword searching. For example, an
     * implementation might send back the set {"Username", "Name", "Email"}. Any of
     * those three fields can then be used in a search with the
     * {@link #findUsers(Set,String)} method.<p>
     *
     * This method should throw an UnsupportedOperationException if this
     * operation is not supported by the backend user store.
     *
     * @return the valid search fields.
     * @throws UnsupportedOperationException if the provider does not
     *      support the operation (this is an optional operation).
     */
    public Set<String> getSearchFields() throws UnsupportedOperationException {
        return provider.getSearchFields();
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
283
     * Searches for users based on a set of fields and a query string. The fields must
284 285 286 287
     * be taken from the values returned by {@link #getSearchFields()}. The query can
     * include wildcards. For example, a search on the field "Name" with a query of "Ma*"
     * might return user's with the name "Matt", "Martha" and "Madeline".<p>
     *
Matt Tucker's avatar
Matt Tucker committed
288 289
     * This method throws an UnsupportedOperationException if this operation is
     * not supported by the user provider.
290 291 292 293 294 295 296 297 298 299 300 301
     *
     * @param fields the fields to search on.
     * @param query the query string.
     * @return a Collection of users that match the search.
     * @throws UnsupportedOperationException if the provider does not
     *      support the operation (this is an optional operation).
     */
    public Collection<User> findUsers(Set<String> fields, String query)
            throws UnsupportedOperationException
    {
        return provider.findUsers(fields, query);
    }
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
    /**
     * Searches for users based on a set of fields and a query string. The fields must
     * be taken from the values returned by {@link #getSearchFields()}. The query can
     * include wildcards. For example, a search on the field "Name" with a query of "Ma*"
     * might return user's with the name "Matt", "Martha" and "Madeline".<p>
     *
     * The startIndex and numResults parameters are used to page through search
     * results. For example, if the startIndex is 0 and numResults is 10, the first
     * 10 search results will be returned. Note that numResults is a request for the
     * number of results to return and that the actual number of results returned
     * may be fewer.<p>
     *
     * This method should throw an UnsupportedOperationException if this
     * operation is not supported by the backend user store.
     *
     * @param fields the fields to search on.
     * @param query the query string.
     * @param startIndex the starting index in the search result to return.
     * @param numResults the number of users to return in the search result.
     * @return a Collection of users that match the search.
     * @throws UnsupportedOperationException if the provider does not
     *      support the operation (this is an optional operation).
     */
    public Collection<User> findUsers(Set<String> fields, String query, int startIndex,
            int numResults)
            throws UnsupportedOperationException
    {
        return provider.findUsers(fields, query, startIndex, numResults);
    }

333 334 335 336 337 338 339
    /**
     * Returns true if the specified local username belongs to a registered local user.
     *
     * @param username to username of the user to check it it's a registered user.
     * @return true if the specified JID belongs to a local registered user.
     */
    public boolean isRegisteredUser(String username) {
340 341 342
        if (username == null || "".equals(username)) {
            return false;
        }
343 344 345 346 347 348
        try {
            getUser(username);
            return true;
        }
        catch (UserNotFoundException e) {
            return false;
349 350 351 352 353 354 355 356 357 358 359 360 361 362
        }
    }

    /**
     * Returns true if the specified JID belongs to a local or remote registered user. For
     * remote users (i.e. domain does not match local domain) a disco#info request is going
     * to be sent to the bare JID of the user.
     *
     * @param user to JID of the user to check it it's a registered user.
     * @return true if the specified JID belongs to a local or remote registered user.
     */
    public boolean isRegisteredUser(JID user) {
        XMPPServer server = XMPPServer.getInstance();
        if (server.isLocal(user)) {
363 364 365 366 367 368 369
            try {
                getUser(user.getNode());
                return true;
            }
            catch (UserNotFoundException e) {
                return false;
            }
370 371 372
        }
        else {
            // Look up in the cache using the full JID
373
            Boolean isRegistered = remoteUsersCache.get(user.toString());
374 375
            if (isRegistered == null) {
                // Check if the bare JID of the user is cached
376 377 378 379 380 381
                isRegistered = remoteUsersCache.get(user.toBareJID());
                if (isRegistered == null) {
                    // No information is cached so check user identity and cache it
                    // A disco#info is going to be sent to the bare JID of the user. This packet
                    // is going to be handled by the remote server.
                    IQ iq = new IQ(IQ.Type.get);
382
                    iq.setFrom(server.getServerInfo().getXMPPDomain());
383 384 385 386 387 388 389
                    iq.setTo(user.toBareJID());
                    iq.setChildElement("query", "http://jabber.org/protocol/disco#info");
                    // Send the disco#info request to the remote server. The reply will be
                    // processed by the IQResultListener (interface that this class implements)
                    server.getIQRouter().addIQResultListener(iq.getID(), this);
                    synchronized (user.toBareJID().intern()) {
                        server.getIQRouter().route(iq);
390
                        // Wait for the reply to be processed. Time out in 1 minute.
391
                        try {
392
                            user.toBareJID().intern().wait(60000);
393 394 395 396
                        }
                        catch (InterruptedException e) {
                            // Do nothing
                        }
397
                    }
398 399 400 401 402 403 404
                    // Get the discovered result
                    isRegistered = remoteUsersCache.get(user.toBareJID());
                    if (isRegistered == null) {
                        // Disco failed for some reason (i.e. we timed out before getting a result)
                        // so assume that user is not anonymous and cache result
                        isRegistered = Boolean.FALSE;
                        remoteUsersCache.put(user.toString(), isRegistered);
405
                    }
406 407
                }
            }
408
            return isRegistered;
409 410 411 412 413 414 415 416 417 418
        }
    }

    public void receivedAnswer(IQ packet) {
        JID from = packet.getFrom();
        // Assume that the user is not a registered user
        Boolean isRegistered = Boolean.FALSE;
        // Analyze the disco result packet
        if (IQ.Type.result == packet.getType()) {
            Element child = packet.getChildElement();
419 420 421 422 423 424 425 426
            if (child != null) {
                for (Iterator it=child.elementIterator("identity"); it.hasNext();) {
                    Element identity = (Element) it.next();
                    String accountType = identity.attributeValue("type");
                    if ("registered".equals(accountType) || "admin".equals(accountType)) {
                        isRegistered = Boolean.TRUE;
                        break;
                    }
427 428 429 430
                }
            }
        }
        // Update cache of remote registered users
431
        remoteUsersCache.put(from.toBareJID(), isRegistered);
432 433 434 435 436 437

        // Wake up waiting thread
        synchronized (from.toBareJID().intern()) {
            from.toBareJID().intern().notifyAll();
        }
    }
438

439 440 441 442
    public void answerTimeout(String packetId) {
        Log.warn("An answer to a previously sent IQ stanza was never received. Packet id: " + packetId);
    }

443
    private void initProvider() {
444 445 446 447
        // Convert XML based provider setup to Database based
        JiveGlobals.migrateProperty("provider.user.className");

        String className = JiveGlobals.getProperty("provider.user.className",
448
                "org.jivesoftware.openfire.user.DefaultUserProvider");
449 450 451 452 453 454 455 456 457 458 459 460
        // Check if we need to reset the provider class
        if (provider == null || !className.equals(provider.getClass().getName())) {
            try {
                Class c = ClassUtils.forName(className);
                provider = (UserProvider) c.newInstance();
            }
            catch (Exception e) {
                Log.error("Error loading user provider: " + className, e);
                provider = new DefaultUserProvider();
            }
        }
    }
461
}