Java Code Examples for org.xmpp.packet.JID#unescapeNode()

The following examples show how to use org.xmpp.packet.JID#unescapeNode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JDBCAdminProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void changeAdmins(final Connection con, final String sql, final List<JID> admins) throws SQLException {
    if (!admins.isEmpty()) {
        try (final PreparedStatement pstmt = con.prepareStatement(sql)) {
            for (final JID jid : admins) {
                // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause.
                final String queryValue = assumePersistedDataIsEscaped() ? jid.getNode() : JID.unescapeNode( jid.getNode() );
                pstmt.setString(1, queryValue);
                pstmt.execute();
            }
        }
    }
}
 
Example 2
Source File: JDBCGroupProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<String> getGroupNames(JID user) {
    List<String> groupNames = new ArrayList<>();
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause.
        final String queryValue;
        if ( server.isLocal(user) ) {
            queryValue = assumePersistedDataIsEscaped() ? user.getNode() : JID.unescapeNode( user.getNode() );
        } else {
            String value = user.toString();
            final int splitIndex = value.lastIndexOf( "@" );
            final String node = value.substring( 0, splitIndex );
            final String processedNode = assumePersistedDataIsEscaped() ? node : JID.unescapeNode( node );
            queryValue = processedNode + value.substring( splitIndex );
        }
        con = getConnection();
        pstmt = con.prepareStatement(userGroupsSQL);
        pstmt.setString(1, queryValue);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            groupNames.add(rs.getString(1));
        }
    }
    catch (SQLException e) {
        Log.error(e.getMessage(), e);
    }
    finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
    }
    return groupNames;
}
 
Example 3
Source File: CrowdManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Authenticates a user with crowd. If authentication failed, raises a <code>RemoteException</code>
 * @param username the username
 * @param password the password
 * @throws RemoteException if an exception occurred communicating with the crowd server
 */
public void authenticate(String username, String password) throws RemoteException {
    username = JID.unescapeNode(username);
    LOG.debug("authenticate '" + String.valueOf(username) + "'");

    final AuthenticatePost authenticatePost = new AuthenticatePost();
    authenticatePost.value = password;
    final StringWriter writer = new StringWriter();
    JAXB.marshal(authenticatePost, writer);

    final HttpUriRequest postRequest = RequestBuilder.post(crowdServer.resolve("authentication?username=" + urlEncode(username)))
        .setConfig(requestConfig)
        .setEntity(new StringEntity(writer.toString(), StandardCharsets.UTF_8))
        .setHeader(HEADER_CONTENT_TYPE_APPLICATION_XML)
        .build();

    try(final CloseableHttpResponse response = client.execute(postRequest, clientContext)) {

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            handleHTTPError(response);
        }
        
    } catch (IOException ioe) {
        handleError(ioe);
    }
    
    LOG.info("authenticated user:" + username);
}
 
Example 4
Source File: JDBCUserPropertyProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> loadProperties( String username ) throws UnsupportedOperationException
{
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause.
    final String queryValue = assumePersistedDataIsEscaped() ? username : JID.unescapeNode( username );

    try
    {
        con = getConnection();
        pstmt = con.prepareStatement( loadPropertiesSQL );
        pstmt.setString( 1, queryValue );
        rs = pstmt.executeQuery();

        final Map<String, String> result = new HashMap<>();
        while ( rs.next() )
        {
            final String propName = rs.getString( 1 );
            final String propValue = rs.getString( 2 );
            result.put( propName, propValue );
        }
        return result;
    }
    catch ( Exception e )
    {
        throw new UnsupportedOperationException( e );
    }
    finally
    {
        DbConnectionManager.closeConnection( rs, pstmt, con );
    }
}
 
Example 5
Source File: JDBCUserPropertyProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public String loadProperty( String username, String propName )
{
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause.
    final String queryValue = assumePersistedDataIsEscaped() ? username : JID.unescapeNode( username );

    try
    {
        con = getConnection();
        pstmt = con.prepareStatement( loadPropertySQL );
        pstmt.setString( 1, queryValue );
        pstmt.setString( 2, propName );
        rs = pstmt.executeQuery();

        if ( rs.next() )
        {
            return rs.getString( 1 );
        }

        return null;
    }
    catch ( Exception e )
    {
        throw new UnsupportedOperationException( e );
    }
    finally
    {
        DbConnectionManager.closeConnection( rs, pstmt, con );
    }
}
 
Example 6
Source File: JDBCUserProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public User loadUser(String username) throws UserNotFoundException {
    if(username.contains("@")) {
        if (!XMPPServer.getInstance().isLocal(new JID(username))) {
            throw new UserNotFoundException("Cannot load user of remote server: " + username);
        }
        username = username.substring(0,username.lastIndexOf("@"));
    }

    // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause.
    final String queryValue = assumePersistedDataIsEscaped() ? username : JID.unescapeNode( username );

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = getConnection();
        pstmt = con.prepareStatement(loadUserSQL);
        pstmt.setString(1, queryValue);
        rs = pstmt.executeQuery();
        if (!rs.next()) {
            throw new UserNotFoundException();
        }
        String name = rs.getString(1);
        String email = rs.getString(2);
        return new User(username, name, email, new Date(), new Date());
    }
    catch (Exception e) {
        throw new UserNotFoundException(e);
    }
    finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
    }
}
 
Example 7
Source File: JDBCAuthProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void setPasswordValue(String username, String password) throws UserNotFoundException {
    Connection con = null;
    PreparedStatement pstmt = null;
    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        } else {
            // Unknown domain.
            throw new UserNotFoundException();
        }
    }
    try {
        con = getConnection();
        pstmt = con.prepareStatement(setPasswordSQL);

        // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause.
        final String queryValue = assumePersistedDataIsEscaped() ? username : JID.unescapeNode( username );
        pstmt.setString(2, queryValue);

        password = hashPassword(password);
        pstmt.setString(1, password);
        pstmt.executeQuery();
    }
    catch (SQLException e) {
        Log.error("Exception in JDBCAuthProvider", e);
        throw new UserNotFoundException();
    }
    finally {
        DbConnectionManager.closeConnection(pstmt, con);
    }
    
}
 
Example 8
Source File: LdapVCardProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the avatar from LDAP, based off the vcard template.
 *
 * If enabled, will replace a blank PHOTO element with one from a DB stored vcard.
 *
 * @param username User we are loading the vcard for.
 * @return The loaded vcard element, or null if none found.
 */
@Override
public Element loadVCard(String username) {
    // Un-escape username.
    username = JID.unescapeNode(username);
    Map<String, String> map = getLdapAttributes(username);
    Log.debug("LdapVCardProvider: Getting mapped vcard for " + username);
    Element vcard = new VCard(template).getVCard(map);
    // If we have a vcard from ldap, but it doesn't have an avatar filled in, then we
    // may fill it with a locally stored vcard element.
    if (dbStorageEnabled && vcard != null && (vcard.element("PHOTO") == null || vcard.element("PHOTO").element("BINVAL") == null || vcard.element("PHOTO").element("BINVAL").getText().matches("\\s*"))) {
        Element avatarElement = loadAvatarFromDatabase(username);
        if (avatarElement != null) {
            Log.debug("LdapVCardProvider: Adding avatar element from local storage");
            Element currentElement = vcard.element("PHOTO");
            if (currentElement != null) {
                vcard.remove(currentElement);
            }
            vcard.add(avatarElement);
        }
    }

    if ( JiveGlobals.getBooleanProperty( PhotoResizer.PROPERTY_RESIZE_ON_LOAD, PhotoResizer.PROPERTY_RESIZE_ON_LOAD_DEFAULT ) )
    {
        PhotoResizer.resizeAvatar( vcard );
    }

    Log.debug("LdapVCardProvider: Returning vcard");
    return vcard;
}
 
Example 9
Source File: LdapVCardProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a merged LDAP vCard combined with a PHOTO element provided in specified vCard.
 *
 * @param username User whose vCard this is.
 * @param mergeVCard vCard element that we are merging PHOTO element from into the LDAP vCard.
 * @return vCard element after merging in PHOTO element to LDAP data.
 */
private Element getMergedVCard(String username, Element mergeVCard) {
    // Un-escape username.
    username = JID.unescapeNode(username);
    Map<String, String> map = getLdapAttributes(username);
    Log.debug("LdapVCardProvider: Retrieving LDAP mapped vcard for " + username);
    if (map.isEmpty()) {
        return null;
    }
    Element vcard = new VCard(template).getVCard(map);
    if (mergeVCard == null) {
        // No vcard passed in?  Hrm.  Fine, return LDAP vcard.
        return vcard;
    }
    if (mergeVCard.element("PHOTO") == null) {
        // Merged vcard has no photo element, return LDAP vcard as is.
        return vcard;
    }
    Element photoElement = mergeVCard.element("PHOTO").createCopy();
    if (photoElement == null || photoElement.element("BINVAL") == null || photoElement.element("BINVAL").getText().matches("\\s*")) {
        // We were passed something null or empty, so lets just return the LDAP based vcard.
        return vcard;
    }
    // Now we need to check that the LDAP vcard doesn't have a PHOTO element that's filled in.
    if (!((vcard.element("PHOTO") == null || vcard.element("PHOTO").element("BINVAL") == null || vcard.element("PHOTO").element("BINVAL").getText().matches("\\s*")))) {
        // Hrm, it does, return the original vcard;
        return vcard;
    }
    Log.debug("LdapVCardProvider: Merging avatar element from passed vcard");
    Element currentElement = vcard.element("PHOTO");
    if (currentElement != null) {
        vcard.remove(currentElement);
    }
    vcard.add(photoElement);
    return vcard;
}
 
Example 10
Source File: JDBCAuthProvider.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the value of the password field. It will be in plain text or hashed
 * format, depending on the password type.
 *
 * @param username user to retrieve the password field for
 * @return the password value.
 * @throws UserNotFoundException if the given user could not be loaded.
 */
private String getPasswordValue(String username) throws UserNotFoundException {
    String password;
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        } else {
            // Unknown domain.
            throw new UserNotFoundException();
        }
    }
    try {
        con = getConnection();
        pstmt = con.prepareStatement(passwordSQL);

        // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause.
        final String queryValue = assumePersistedDataIsEscaped() ? username : JID.unescapeNode( username );
        pstmt.setString(1, queryValue);

        rs = pstmt.executeQuery();

        // If the query had no results, the username and password
        // did not match a user record. Therefore, throw an exception.
        if (!rs.next()) {
            throw new UserNotFoundException();
        }
        password = rs.getString(1);
    }
    catch (SQLException e) {
        Log.error("Exception in JDBCAuthProvider", e);
        throw new UserNotFoundException();
    }
    finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
    }
    return password;
}
 
Example 11
Source File: LdapVCardProvider.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Returns true or false if the change to the existing vcard is valid (only to PHOTO element)
 *
 * @param username User who's LDAP-based vcard we will compare with.
 * @param newvCard New vCard Element we will compare against.
 * @return True or false if the changes made were valid (only to PHOTO element)
 */
private Boolean isValidVCardChange(String username, Element newvCard) {
    if (newvCard == null) {
        // Well if there's nothing to change, of course it's valid.
        Log.debug("LdapVCardProvider: No new vcard provided (no changes), accepting.");
        return true;
    }
    // Un-escape username.
    username = JID.unescapeNode(username);
    Map<String, String> map = getLdapAttributes(username);
    // Retrieve LDAP created vcard for comparison
    Element ldapvCard = new VCard(template).getVCard(map);
    if (ldapvCard == null) {
        // This person has no vcard at all, may not change it!
        Log.debug("LdapVCardProvider: User has no LDAP vcard, nothing they can change, rejecting.");
        return false;
    }
    // If the LDAP vcard has a non-empty PHOTO element set, then there is literally no way this will be accepted.
    Element ldapPhotoElem = ldapvCard.element("PHOTO");
    if (ldapPhotoElem != null) {
        Element ldapBinvalElem = ldapPhotoElem.element("BINVAL");
        if (ldapBinvalElem != null && !ldapBinvalElem.getTextTrim().matches("\\s*")) {
            // LDAP is providing a valid PHOTO element, byebye!
            Log.debug("LdapVCardProvider: LDAP has a PHOTO element set, no way to override, rejecting.");
            return false;
        }
    }
    // Retrieve database vcard, if it exists
    Element dbvCard = defaultProvider.loadVCard(username);
    if (dbvCard != null) {
        Element dbPhotoElem = dbvCard.element("PHOTO");
        if (dbPhotoElem == null) {
            // DB has no photo, lets accept what we got.
            Log.debug("LdapVCardProvider: Database has no PHOTO element, accepting update.");
            return true;
        }
        else {
            Element newPhotoElem = newvCard.element("PHOTO");
            if (newPhotoElem == null) {
                Log.debug("LdapVCardProvider: Photo element was removed, accepting update.");
                return true;
            }
            // Note: NodeComparator never seems to consider these equal, even if they are?
            if (!dbPhotoElem.asXML().equals(newPhotoElem.asXML())) {
                // Photo element was changed.  Ignore all other changes and accept this.
                Log.debug("LdapVCardProvider: PHOTO element changed, accepting update.");
                return true;
            }
        }
    }
    else {
        // No vcard exists in database
        Log.debug("LdapVCardProvider: Database has no vCard stored, accepting update.");
        return true;
    }
    // Ok, either something bad changed or nothing changed.  Either way, user either:
    // 1. should not have tried to change something 'readonly'
    // 2. shouldn't have bothered submitting no changes
    // So we'll consider this a bad return.
    Log.debug("LdapVCardProvider: PHOTO element didn't change, no reason to accept this, rejecting.");
    return false;
}
 
Example 12
Source File: LdapUserProvider.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public User loadUser(String username) throws UserNotFoundException {
    if(username.contains("@")) {
        if (!XMPPServer.getInstance().isLocal(new JID(username))) {
            throw new UserNotFoundException("Cannot load user of remote server: " + username);
        }
        username = username.substring(0,username.lastIndexOf("@"));
    }
    // Un-escape username.
    username = JID.unescapeNode(username);
    DirContext ctx = null;
    try {
        Rdn[] userRDN = manager.findUserRDN(username);
        // Load record.
        final List<String> attributes = new ArrayList<>();
        attributes.add( manager.getUsernameField() );
        attributes.addAll( manager.getNameField().getFields() );
        attributes.add( manager.getEmailField() );
        attributes.add( "createTimestamp" );
        attributes.add( "modifyTimestamp" );

        ctx = manager.getContext(manager.getUsersBaseDN(username));
        Attributes attrs = ctx.getAttributes(LdapManager.escapeForJNDI(userRDN), attributes.toArray(new String[0]));
        String name = LdapUserTester.getPropertyValue(manager.getNameField(), attrs);
        String email = null;
        Attribute emailField = attrs.get(manager.getEmailField());
        if (emailField != null) {
            email = (String)emailField.get();
        }
        Date creationDate = new Date();
        Attribute creationDateField = attrs.get("createTimestamp");
        if (creationDateField != null && "".equals(((String) creationDateField.get()).trim())) {
            creationDate = parseLDAPDate((String) creationDateField.get());
        }
        Date modificationDate = new Date();
        Attribute modificationDateField = attrs.get("modifyTimestamp");
        if (modificationDateField != null && "".equals(((String) modificationDateField.get()).trim())) {
            modificationDate = parseLDAPDate((String)modificationDateField.get());
        }
        // Escape the username so that it can be used as a JID.
        username = JID.escapeNode(username);
        
        // As defined by RFC5803.
        Attribute authPassword = attrs.get("authPassword");
        User user = new User(username, name, email, creationDate, modificationDate);
        if (manager.isFindUsersFromGroupsEnabled() && GroupManager.getInstance().getGroups(user).isEmpty()) {
            throw new UserNotFoundException("User exists in LDAP but is not a member of any Openfire groups");
        }
        if (authPassword != null) {
            // The authPassword attribute can be multivalued.
            // Not sure if this is the right API to loop through them.
            NamingEnumeration values = authPassword.getAll();
            while (values.hasMore()) {
                Attribute authPasswordValue = (Attribute) values.next();
                String[] parts = ((String) authPasswordValue.get()).split("$");
                String[] authInfo = parts[1].split(":");
                String[] authValue = parts[2].split(":");

                String scheme = parts[0].trim();

                // We only support SCRAM-SHA-1 at the moment.
                if ("SCRAM-SHA-1".equals(scheme)) {
                    int iterations = Integer.valueOf(authInfo[0].trim());
                    String salt = authInfo[1].trim();
                    String storedKey = authValue[0].trim();
                    String serverKey = authValue[1].trim();
                    
                    user.setSalt(salt);
                    user.setStoredKey(storedKey);
                    user.setServerKey(serverKey);
                    user.setIterations(iterations);
                    
                    break;
                }
            }
        }
        return user;
    }
    catch (Exception e) {
        throw new UserNotFoundException(e);
    }
    finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        }
        catch (Exception ex) {
            Log.debug( "An exception occurred while closing the LDAP context after attempting to load user {}", username, ex);
        }
    }
}
 
Example 13
Source File: LdapUserTester.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of attributes and their LDAP values found in LDAP for the specified username.
 *
 * @param username the username of the user to get his attributes from LDAP.
 * @return a list of attributes and their LDAP values found in LDAP for the specified username.
 */
public Map<String, String> getAttributes(String username) {
    Map<String, String> userAttributes = new HashMap<>();
    // Un-escape username.
    username = JID.unescapeNode(username);
    DirContext ctx = null;
    try {
        Rdn[] userRDN = manager.findUserRDN(username);
        // Build list of attributes to load from LDAP
        Map<String, PropertyMapping> ldapMappings = getLdapAttributes();
        Set<String> fields = new HashSet<>();
        for (PropertyMapping mapping : ldapMappings.values()) {
            fields.addAll(mapping.getFields());
        }
        fields.add(manager.getUsernameField());
        // Load records
        ctx = manager.getContext(manager.getUsersBaseDN(username));
        Attributes attrs = ctx.getAttributes(LdapManager.escapeForJNDI(userRDN), fields.toArray(new String[]{}));
        // Build answer
        for (Map.Entry<String, PropertyMapping> entry : ldapMappings.entrySet()) {
            String attribute = entry.getKey();
            String value = getPropertyValue(entry.getValue(), attrs);
            userAttributes.put(attribute, value);
        }
    }
    catch (Exception e) {
        Log.error("An error occurred while trying to get attributes for user: {}", username, e);
        // TODO something else?
    }
    finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        }
        catch (Exception ex) {
            Log.debug("An exception occurred while trying to close a LDAP context after trying to get attributes for user {}.", username, ex);
        }
    }
    return userAttributes;
}