LdapUserIDProvider.java 20.6 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 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 239 240 241 242 243 244 245 246 247 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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
/**
 *
 * $RCSfile$
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2003 JiveSoftware. All rights reserved.
 *
 * This software is the proprietary information of Jive Software.
 * Use is subject to license terms.
 */
package org.jivesoftware.messenger.ldap;

import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.SequenceManager;
import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.LongList;
import org.jivesoftware.messenger.user.UserIDProvider;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.messenger.user.spi.DbUserIDProvider;
import org.jivesoftware.database.DbConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;


/**
 * <p>Ldap implementation of the UserIDProvider interface.</p>
 * <p>The LdapUserIDProvider can operate in two modes -- in the pure LDAP mode, all user data is stored in the LDAP
 * store. This mode generally requires modifications to the LDAP schema to accommodate data that Messenger needs.</p>
 * <p>In the mixed mode, data that Messenger needs is stored locally.</p>
 * * @author Jim Berrettini
 */


public class LdapUserIDProvider implements UserIDProvider {
    private LdapManager manager;
    /**
     * <p>Object type for users.</p>
     */
    public static final int USER_TYPE = 0;
    /**
     * <p>Object type for chatbots.</p>
     */
    public static final int CHATBOT_TYPE = 1;
    /**
     * <p>The default domain id - the messenger domain.</p>
     */
    public static final long DEFAULT_DOMAIN = 1;

    private static final String GET_USERID = "SELECT objectID FROM jiveUserID WHERE username=? AND domainID=? AND objectType=?";
    private static final String GET_USERNAME = "SELECT username FROM jiveUserID WHERE objectID=? AND domainID=? AND objectType=?";
    private static final String USER_COUNT = "SELECT count(*) FROM jiveUser";
    private static final String INSERT_USERID = "INSERT INTO jiveUserID (username,domainID,objectType,objectID) VALUES (?,?,?,?)";
    private static final String ALL_USERS = "SELECT userID from jiveUser";

    public LdapUserIDProvider() {
        manager = LdapManager.getInstance();
    }

    /**
     * <p>Obtain the user's username from their ID.</p>
     *
     * @param id the userID of the user
     * @return the name of the user with the given userID
     * @throws UserNotFoundException if no such user exists
     */
    public String getUsername(long id) throws UserNotFoundException {
        if (manager.getMode() == LdapManager.ALL_LDAP_MODE) {
            // Find userDN.
            DirContext ctx = null;
            try {
                ctx = manager.getContext();
                // Search for the dn based on the username.
                SearchControls constraints = new SearchControls();
                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
                constraints.setReturningAttributes(new String[]{"jiveUserID"});

                StringBuffer filter = new StringBuffer();
                filter.append("(").append("jiveUserID").append("=");
                filter.append(id).append(")");

                NamingEnumeration answer = ctx.search("", filter.toString(), constraints);
                if (answer == null || !answer.hasMoreElements()) {
                    throw new UserNotFoundException("User not found: " + id);
                }
                String userDN = ((SearchResult)answer.next()).getName();
                // Make sure there are no more search results. If there are, then
                // the userID isn't unique on the LDAP server (a perfectly possible
                // scenario since only fully qualified dn's need to be unqiue).
                // There really isn't a way to handle this, so throw an exception.
                // The baseDN must be set correctly so that this doesn't happen.
                if (answer.hasMoreElements()) {
                    throw new UserNotFoundException("LDAP username lookup matched multiple entries.");
                }
            }
            catch (Exception e) {
                throw new UserNotFoundException(e);
            }
            finally {
                try {
                    ctx.close();
                }
                catch (Exception e) {
                }
            }
            return getUsernameFromLdap(id);
        }
        else {
            return getUsernameFromDb(id);
        }
    }


    /**
     * <p>Obtain the user's username from their ID.</p>
     *
     * @param username the username to look up
     * @return the userID corrresponding to the given username
     * @throws UserNotFoundException
     */
    public long getUserID(String username) throws UserNotFoundException {
        if (manager.getMode() == LdapManager.ALL_LDAP_MODE) {
            return getUserIDFromLdap(username);
        }

        long id = 0L;
        try {
            id = getUserIDLocally(username);
        }
        catch (UserNotFoundException e) {
            id = generateNewUserIDLocally(username);
        }
        return id;
    }

    /**
     * <p>Obtain the total number of users on the system.</p>
     *
     * @return total number of users on the system.
     */
    public int getUserCount() {
        int count = 0;
        // If using the pure LDAP mode.
        if (manager.getMode() == LdapManager.ALL_LDAP_MODE) {
            // Note: the performance of this check may suffer badly for very large
            // numbers of users since we manually iterate through results to get
            // a count.
            DirContext ctx = null;
            try {
                ctx = manager.getContext();
                // Search for the dn based on the username.
                SearchControls constraints = new SearchControls();
                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
                constraints.setReturningAttributes(new String[]{"jiveUserID"});
                String filter = "(jiveUserID=*)";
                NamingEnumeration answer = ctx.search("", filter, constraints);
                while (answer.hasMoreElements()) {
                    count++;
                    answer.nextElement();
                }
            }
            catch (Exception e) {
                Log.error(e);
            }
            finally {
                try {
                    ctx.close();
                }
                catch (Exception e) {
                }
            }
        }
        // Otherwise, we're using the mixed LDAP mode.
        else {
            Connection con = null;
            PreparedStatement pstmt = null;

            try {
                con = DbConnectionManager.getConnection();
                pstmt = con.prepareStatement(USER_COUNT);
                ResultSet rs = pstmt.executeQuery();
                if (rs.next()) {
                    count = rs.getInt(1);
                }
            }
            catch (SQLException e) {
                Log.error(e);
            }
            finally {
                try {
                    if (pstmt != null) {
                        pstmt.close();
                    }
                }
                catch (Exception e) {
                    Log.error(e);
                }
                try {
                    if (con != null) {
                        con.close();
                    }
                }
                catch (Exception e) {
                    Log.error(e);
                }
            }
        }
        return count;
    }

    /**
     * <p>Obtain a list all user IDs on the system.</p>
     *
     * @return LongList of user ID's
     */
    public LongList getUserIDs() {
        LongList users = new LongList(500);

        if (manager.getMode() == LdapManager.LDAP_DB_MODE) { // if in mixed mode, get id's from DB.
            Connection con = null;
            PreparedStatement pstmt = null;
            try {
                con = DbConnectionManager.getConnection();
                pstmt = con.prepareStatement(ALL_USERS);
                ResultSet rs = pstmt.executeQuery();
                // Set the fetch size. This will prevent some JDBC drivers from trying
                // to load the entire result set into memory.
                DbConnectionManager.setFetchSize(rs, 500);
                while (rs.next()) {
                    users.add(rs.getLong(1));
                }
            }
            catch (SQLException e) {
                Log.error(e);
            }
            finally {
                try {
                    if (pstmt != null) {
                        pstmt.close();
                    }
                }
                catch (Exception e) {
                    Log.error(e);
                }
                try {
                    if (con != null) {
                        con.close();
                    }
                }
                catch (Exception e) {
                    Log.error(e);
                }
            }
            return users;
        }
        // else, in LDAP-only mode
        DirContext ctx = null;
        try {
            ctx = manager.getContext();
            // Search for the dn based on the username.
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            constraints.setReturningAttributes(new String[]{"jiveUserID"});
            String filter = "(jiveUserID=*)";
            NamingEnumeration answer = ctx.search("", filter, constraints);

            while (answer.hasMoreElements()) {
                // Get the next userID.
                users.add(Long.parseLong((String)(((SearchResult)answer.next()).getAttributes().get("jiveUserID")).get()));
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                ctx.close();
            }
            catch (Exception e) {
            }
        }
        return users;
    }

    /**
     * Get paginated sublist of userID's
     *
     * @param startIndex index to begin sublist with.
     * @param numResults maximum number of results to return.
     * @return sublist of userID's.
     */
    public LongList getUserIDs(int startIndex, int numResults) {
        LongList users = new LongList();
        if (manager.getMode() == LdapManager.LDAP_DB_MODE) { // if in mixed mode, get id's from DB.
            Connection con = null;
            PreparedStatement pstmt = null;

            try {
                con = DbConnectionManager.getConnection();
                pstmt = con.prepareStatement(ALL_USERS);
                ResultSet rs = pstmt.executeQuery();
                DbConnectionManager.setFetchSize(rs, startIndex + numResults);
                // Move to start of index
                for (int i = 0; i < startIndex; i++) {
                    rs.next();
                }
                // Now read in desired number of results (or stop if we run out of results).
                for (int i = 0; i < numResults; i++) {
                    if (rs.next()) {
                        users.add(rs.getLong(1));
                    }
                    else {
                        break;
                    }
                }
            }
            catch (SQLException e) {
                Log.error(e);
            }
            finally {
                try {
                    if (pstmt != null) {
                        pstmt.close();
                    }
                }
                catch (Exception e) {
                    Log.error(e);
                }
                try {
                    if (con != null) {
                        con.close();
                    }
                }
                catch (Exception e) {
                    Log.error(e);
                }
            }
            return users;
        }
        // else, in LDAP-only mode
        DirContext ctx = null;
        try {
            ctx = manager.getContext();
            // Search for the dn based on the username.
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            constraints.setReturningAttributes(new String[]{"jiveUserID"});
            String filter = "(jiveUserID=*)";
            NamingEnumeration answer = ctx.search("", filter, constraints);
            for (int i = 0; i < startIndex; i++) {
                answer.next();
            }
            // Now read in desired number of results (or stop if we run out of results).
            for (int i = 0; i < numResults; i++) {
                if (answer.hasMoreElements()) {
                    // Get the next userID.
                    users.add(Long.parseLong((String)(((SearchResult)answer.next()).getAttributes().get("jiveUserID")).get()));
                }
                else {
                    break;
                }
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                ctx.close();
            }
            catch (Exception e) {
            }
        }
        return users;
    }

    /**
     * This is used when operating in mixed mode -- generate a new user ID for a user stored in our database.
     *
     * @param username
     * @return id corresponding to that username
     * @throws UserNotFoundException
     */
    private long generateNewUserIDLocally(String username) throws UserNotFoundException {
        long id = -1;
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            id = SequenceManager.nextID(JiveConstants.USER);
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(INSERT_USERID);
            pstmt.setString(1, username);
            pstmt.setLong(2, DbUserIDProvider.DEFAULT_DOMAIN);
            pstmt.setLong(3, DbUserIDProvider.USER_TYPE);
            pstmt.setLong(4, id);
            pstmt.execute();
        }
        catch (SQLException e) {
            Log.error(e);
            throw new UserNotFoundException(e);
        }
        finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            }
            catch (Exception e) {
                Log.error(e);
            }
            try {
                if (con != null) {
                    con.close();
                }
            }
            catch (Exception e) {
                Log.error(e);
            }
        }
        return id;
    }

    /**
     * This is used when operating in mixed mode -- get user ID for a user stored locally.
     *
     * @param username
     * @return user id corresponding to that username.
     * @throws UserNotFoundException
     */
    private long getUserIDLocally(String username) throws UserNotFoundException {
        long id = -1;
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(GET_USERID);
            pstmt.setString(1, username);
            pstmt.setLong(2, DEFAULT_DOMAIN);
            pstmt.setLong(3, USER_TYPE);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                id = rs.getLong(1);
            }
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            }
            catch (Exception e) {
                Log.error(e);
            }
            try {
                if (con != null) {
                    con.close();
                }
            }
            catch (Exception e) {
                Log.error(e);
            }
        }
        if (id == -1) {
            throw new UserNotFoundException();
        }
        return id;
    }

    /**
     * This method is used when operating in pure LDAP mode. Get user ID from the LDAP store.
     *
     * @param username
     * @return user id corresponding to that username.
     * @throws UserNotFoundException
     */
    private long getUserIDFromLdap(String username) throws UserNotFoundException {
        DirContext ctx = null;
        try {
            String userDN = manager.findUserDN(username);
            ctx = manager.getContext();
            String[] attributes = new String[]{"jiveUserID"};
            Attributes attrs = ctx.getAttributes(userDN, attributes);
            return Long.parseLong((String)attrs.get("jiveUserID").get());
        }
        catch (Exception e) {
            Log.error(e);
            throw new UserNotFoundException(e);
        }
        finally {
            try {
                ctx.close();
            }
            catch (Exception e) {
            }
        }

    }

    /**
     * This method is used in mixed mode. Get the username that corresponds to a given ID.
     *
     * @param id
     * @return username for that user id.
     * @throws UserNotFoundException
     */
    private String getUsernameFromDb(long id) throws UserNotFoundException {
        String name = null;
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(GET_USERNAME);
            pstmt.setLong(1, id);
            pstmt.setLong(2, DEFAULT_DOMAIN);
            pstmt.setLong(3, USER_TYPE);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                name = rs.getString(1);
            }
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            }
            catch (Exception e) {
                Log.error(e);
            }
            try {
                if (con != null) {
                    con.close();
                }
            }
            catch (Exception e) {
                Log.error(e);
            }
        }
        if (name == null) {
            throw new UserNotFoundException();
        }
        return name;
    }

    /**
     * This method is used when operating in pure LDAP mode. Get the username that corresponds to a given ID.
     *
     * @param id
     * @return
     * @throws UserNotFoundException
     */
    private String getUsernameFromLdap(long id) throws UserNotFoundException {
        DirContext ctx = null;
        try {
            ctx = manager.getContext();
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            constraints.setReturningAttributes(new String[]{"jiveUserID"});
            StringBuffer filter = new StringBuffer();
            filter.append("(").append("jiveUserID").append("=");
            filter.append(id).append(")");
            NamingEnumeration answer = ctx.search("", filter.toString(), constraints);
            if (answer == null || !answer.hasMoreElements()) {
                throw new UserNotFoundException("User not found: " + id);
            }
            String userDN = ((SearchResult)answer.next()).getName();
            return getUsernameFromUserDN(userDN);

        }
        catch (NamingException e) {
            Log.error(e);
            throw new UserNotFoundException(e);
        }
        catch (UserNotFoundException e) {
            Log.error(e);
            throw new UserNotFoundException(e);
        }
        finally {
            try {
                ctx.close();
            }
            catch (Exception e) {
            }
        }

    }

    /**
     * Helper function to retrieve username from userDN.
     *
     * @param userDN
     * @return username
     * @throws NamingException
     */
    private String getUsernameFromUserDN(String userDN) throws NamingException {
        DirContext ctx = null;
        try {
            ctx = manager.getContext();
            // Load record.
            String[] attributes = new String[]{manager.getUsernameField()};
            Attributes attrs = ctx.getAttributes(userDN, attributes);
            return (String)attrs.get(manager.getUsernameField()).get();
        }
        finally {
            try {
                ctx.close();
            }
            catch (Exception e) {
            }
        }

    }
}