Search in sources :

Example 36 with UserNotFoundException

use of org.jivesoftware.openfire.user.UserNotFoundException in project Openfire by igniterealtime.

the class NativeAuthProvider method authenticate.

@Override
public void authenticate(String username, String password) throws UnauthorizedException {
    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. Return authentication failed.
            throw new UnauthorizedException();
        }
    }
    try {
        // very well. Therefore, synchronize access to Shaj to throttle auth checks.
        synchronized (this) {
            if (!Shaj.checkPassword(domain, username, password)) {
                throw new UnauthorizedException();
            }
        }
    } catch (UnauthorizedException ue) {
        throw ue;
    } catch (Exception e) {
        throw new UnauthorizedException(e);
    }
    // See if the user exists in the database. If not, automatically create them.
    UserManager userManager = UserManager.getInstance();
    try {
        userManager.getUser(username);
    } catch (UserNotFoundException unfe) {
        try {
            Log.debug("Automatically creating new user account for " + username);
            // Create user; use a random password for better safety in the future.
            // Note that we have to go to the user provider directly -- because the
            // provider is read-only, UserManager will usually deny access to createUser.
            UserProvider provider = UserManager.getUserProvider();
            if (!(provider instanceof NativeUserProvider)) {
                Log.error("Error: not using NativeUserProvider so authentication with " + "NativeAuthProvider will likely fail. Using: " + provider.getClass().getName());
            }
            UserManager.getUserProvider().createUser(username, StringUtils.randomString(8), null, null);
        } catch (UserAlreadyExistsException uaee) {
        // Ignore.
        }
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) UserProvider(org.jivesoftware.openfire.user.UserProvider) NativeUserProvider(org.jivesoftware.openfire.user.NativeUserProvider) UserManager(org.jivesoftware.openfire.user.UserManager) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) NativeUserProvider(org.jivesoftware.openfire.user.NativeUserProvider)

Example 37 with UserNotFoundException

use of org.jivesoftware.openfire.user.UserNotFoundException in project Openfire by igniterealtime.

the class IQAdminHandler method handleItemsElement.

/**
     * Handles packets that includes item elements. Depending on the item's attributes the
     * interpretation of the request may differ. For example, an item that only contains the
     * "affiliation" attribute is requesting the list of participants or members. Whilst if the item
     * contains the affiliation together with a jid means that the client is changing the
     * affiliation of the requested jid.
     *
     * @param senderRole the role of the user that sent the request packet.
     * @param itemsList  the list of items sent by the client.
     * @param reply      the iq packet that will be sent back as a reply to the client's request.
     * @throws ForbiddenException If the user is not allowed to perform his request.
     * @throws ConflictException If the desired room nickname is already reserved for the room or
     *                           if the room was going to lose all of its owners.
     * @throws NotAllowedException Thrown if trying to ban an owner or an administrator.
     * @throws CannotBeInvitedException If the user being invited as a result of being added to a members-only room still does not have permission
     */
private void handleItemsElement(MUCRole senderRole, List<Element> itemsList, IQ reply) throws ForbiddenException, ConflictException, NotAllowedException, CannotBeInvitedException {
    Element item;
    String affiliation;
    String roleAttribute;
    boolean hasJID = itemsList.get(0).attributeValue("jid") != null;
    boolean hasNick = itemsList.get(0).attributeValue("nick") != null;
    // Check if the client is requesting or changing the list of moderators/members/etc.
    if (!hasJID && !hasNick) {
        // The client is requesting the list of moderators/members/participants/outcasts
        // Create the result that will hold an item for each
        // moderator/member/participant/outcast
        Element result = reply.setChildElement("query", "http://jabber.org/protocol/muc#admin");
        for (Object anItem : itemsList) {
            item = (Element) anItem;
            affiliation = item.attributeValue("affiliation");
            roleAttribute = item.attributeValue("role");
            Element metaData;
            if ("outcast".equals(affiliation)) {
                // The client is requesting the list of outcasts
                if (MUCRole.Affiliation.admin != senderRole.getAffiliation() && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
                    throw new ForbiddenException();
                }
                for (JID jid : room.getOutcasts()) {
                    if (GroupJID.isGroup(jid)) {
                        try {
                            // add each group member to the result (clients don't understand groups)
                            Group group = GroupManager.getInstance().getGroup(jid);
                            for (JID groupMember : group.getAll()) {
                                metaData = addAffiliationToResult(affiliation, result, groupMember);
                            }
                        } catch (GroupNotFoundException gnfe) {
                            logger.warn("Invalid group JID in the outcast list: " + jid);
                        }
                    } else {
                        metaData = addAffiliationToResult(affiliation, result, jid);
                    }
                }
            } else if ("member".equals(affiliation)) {
                // In a members-only room members can get the list of members
                if (!room.isMembersOnly() && MUCRole.Affiliation.admin != senderRole.getAffiliation() && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
                    throw new ForbiddenException();
                }
                for (JID jid : room.getMembers()) {
                    if (GroupJID.isGroup(jid)) {
                        try {
                            // add each group member to the result (clients don't understand groups)
                            Group group = GroupManager.getInstance().getGroup(jid);
                            for (JID groupMember : group.getAll()) {
                                metaData = addAffiliationToResult(affiliation, result, groupMember);
                            }
                        } catch (GroupNotFoundException gnfe) {
                            logger.warn("Invalid group JID in the member list: " + jid);
                        }
                    } else {
                        metaData = addAffiliationToResult(affiliation, result, jid);
                    }
                }
            } else if ("moderator".equals(roleAttribute)) {
                // The client is requesting the list of moderators
                if (MUCRole.Affiliation.admin != senderRole.getAffiliation() && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
                    throw new ForbiddenException();
                }
                for (MUCRole role : room.getModerators()) {
                    metaData = result.addElement("item", "http://jabber.org/protocol/muc#admin");
                    metaData.addAttribute("role", "moderator");
                    metaData.addAttribute("jid", role.getUserAddress().toString());
                    metaData.addAttribute("nick", role.getNickname());
                    metaData.addAttribute("affiliation", role.getAffiliation().toString());
                }
            } else if ("participant".equals(roleAttribute)) {
                // The client is requesting the list of participants
                if (MUCRole.Role.moderator != senderRole.getRole()) {
                    throw new ForbiddenException();
                }
                for (MUCRole role : room.getParticipants()) {
                    metaData = result.addElement("item", "http://jabber.org/protocol/muc#admin");
                    metaData.addAttribute("role", "participant");
                    metaData.addAttribute("jid", role.getUserAddress().toString());
                    metaData.addAttribute("nick", role.getNickname());
                    metaData.addAttribute("affiliation", role.getAffiliation().toString());
                }
            } else if ("owner".equals(affiliation)) {
                // The client is requesting the list of owners
                for (JID jid : room.getOwners()) {
                    if (GroupJID.isGroup(jid)) {
                        try {
                            // add each group member to the result (clients don't understand groups)
                            Group group = GroupManager.getInstance().getGroup(jid);
                            for (JID groupMember : group.getAll()) {
                                metaData = addAffiliationToResult(affiliation, result, groupMember);
                            }
                        } catch (GroupNotFoundException gnfe) {
                            logger.warn("Invalid group JID in the owner list: " + jid);
                        }
                    } else {
                        metaData = addAffiliationToResult(affiliation, result, jid);
                    }
                }
            } else if ("admin".equals(affiliation)) {
                // The client is requesting the list of admins
                for (JID jid : room.getAdmins()) {
                    if (GroupJID.isGroup(jid)) {
                        try {
                            // add each group member to the result (clients don't understand groups)
                            Group group = GroupManager.getInstance().getGroup(jid);
                            for (JID groupMember : group.getAll()) {
                                metaData = addAffiliationToResult(affiliation, result, groupMember);
                            }
                        } catch (GroupNotFoundException gnfe) {
                            logger.warn("Invalid group JID in the admin list: " + jid);
                        }
                    } else {
                        metaData = addAffiliationToResult(affiliation, result, jid);
                    }
                }
            } else {
                reply.setError(PacketError.Condition.bad_request);
            }
        }
    } else {
        // The client is modifying the list of moderators/members/participants/outcasts
        String nick;
        String target;
        boolean hasAffiliation;
        // Keep a registry of the updated presences
        List<Presence> presences = new ArrayList<>(itemsList.size());
        // Collect the new affiliations or roles for the specified jids
        for (Object anItem : itemsList) {
            try {
                item = (Element) anItem;
                affiliation = item.attributeValue("affiliation");
                hasAffiliation = affiliation != null;
                target = (hasAffiliation ? affiliation : item.attributeValue("role"));
                List<JID> jids = new ArrayList<>();
                // jid could be of the form "full JID" or "bare JID" depending if we are
                // going to change a role or an affiliation
                nick = item.attributeValue("nick");
                if (hasJID) {
                    // could be a group JID
                    jids.add(GroupJID.fromString(item.attributeValue("jid")));
                } else {
                    // Get the JID based on the requested nick
                    for (MUCRole role : room.getOccupantsByNickname(nick)) {
                        if (!jids.contains(role.getUserAddress())) {
                            jids.add(role.getUserAddress());
                        }
                    }
                }
                for (JID jid : jids) {
                    if ("moderator".equals(target)) {
                        // Add the user as a moderator of the room based on the full JID
                        presences.add(room.addModerator(jid, senderRole));
                    } else if ("owner".equals(target)) {
                        presences.addAll(room.addOwner(jid, senderRole));
                    } else if ("admin".equals(target)) {
                        presences.addAll(room.addAdmin(jid, senderRole));
                    } else if ("participant".equals(target)) {
                        // Add the user as a participant of the room based on the full JID
                        presences.add(room.addParticipant(jid, item.elementTextTrim("reason"), senderRole));
                    } else if ("visitor".equals(target)) {
                        // Add the user as a visitor of the room based on the full JID
                        presences.add(room.addVisitor(jid, senderRole));
                    } else if ("member".equals(target)) {
                        // Add the user as a member of the room based on the bare JID
                        boolean hadAffiliation = room.getAffiliation(jid) != MUCRole.Affiliation.none;
                        presences.addAll(room.addMember(jid, nick, senderRole));
                        // are not disabled system-wide xmpp.muc.skipInvite
                        if (!skipInvite && !hadAffiliation && room.isMembersOnly()) {
                            List<JID> invitees = new ArrayList<>();
                            if (GroupJID.isGroup(jid)) {
                                try {
                                    Group group = GroupManager.getInstance().getGroup(jid);
                                    for (JID inGroup : group.getAll()) {
                                        invitees.add(inGroup);
                                    }
                                } catch (GroupNotFoundException gnfe) {
                                    logger.error("Failed to send invitations for group members", gnfe);
                                }
                            } else {
                                invitees.add(jid);
                            }
                            for (JID invitee : invitees) {
                                room.sendInvitation(invitee, null, senderRole, null);
                            }
                        }
                    } else if ("outcast".equals(target)) {
                        // Add the user as an outcast of the room based on the bare JID
                        presences.addAll(room.addOutcast(jid, item.elementTextTrim("reason"), senderRole));
                    } else if ("none".equals(target)) {
                        if (hasAffiliation) {
                            // Set that this jid has a NONE affiliation based on the bare JID
                            presences.addAll(room.addNone(jid, senderRole));
                        } else {
                            // Kick the user from the room
                            if (MUCRole.Role.moderator != senderRole.getRole()) {
                                throw new ForbiddenException();
                            }
                            presences.add(room.kickOccupant(jid, senderRole.getUserAddress(), senderRole.getNickname(), item.elementTextTrim("reason")));
                        }
                    } else {
                        reply.setError(PacketError.Condition.bad_request);
                    }
                }
            } catch (UserNotFoundException e) {
            // Do nothing
            }
        }
        // Send the updated presences to the room occupants
        for (Presence presence : presences) {
            room.send(presence);
        }
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) Group(org.jivesoftware.openfire.group.Group) ForbiddenException(org.jivesoftware.openfire.muc.ForbiddenException) GroupJID(org.jivesoftware.openfire.group.GroupJID) JID(org.xmpp.packet.JID) Element(org.dom4j.Element) ArrayList(java.util.ArrayList) MUCRole(org.jivesoftware.openfire.muc.MUCRole) Presence(org.xmpp.packet.Presence) GroupNotFoundException(org.jivesoftware.openfire.group.GroupNotFoundException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 38 with UserNotFoundException

use of org.jivesoftware.openfire.user.UserNotFoundException in project Openfire by igniterealtime.

the class IQAdminHandler method addAffiliationToResult.

private Element addAffiliationToResult(String affiliation, Element parent, JID jid) {
    Element result = parent.addElement("item", "http://jabber.org/protocol/muc#admin");
    result.addAttribute("affiliation", affiliation);
    result.addAttribute("jid", jid.toString());
    try {
        List<MUCRole> roles = room.getOccupantsByBareJID(jid);
        MUCRole role = roles.get(0);
        result.addAttribute("role", role.getRole().toString());
        result.addAttribute("nick", role.getNickname());
    } catch (UserNotFoundException e) {
    // the JID is note currently an occupant
    }
    return result;
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) MUCRole(org.jivesoftware.openfire.muc.MUCRole) Element(org.dom4j.Element)

Example 39 with UserNotFoundException

use of org.jivesoftware.openfire.user.UserNotFoundException in project Openfire by igniterealtime.

the class LdapUserProvider method loadUser.

@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 {
        String userDN = manager.findUserDN(username);
        // Load record.
        String[] attributes = new String[] { manager.getUsernameField(), manager.getNameField(), manager.getEmailField(), "createTimestamp", "modifyTimestamp" };
        ctx = manager.getContext(manager.getUsersBaseDN(username));
        Attributes attrs = ctx.getAttributes(userDN, attributes);
        String name = null;
        Attribute nameField = attrs.get(manager.getNameField());
        if (nameField != null) {
            name = (String) nameField.get();
        }
        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 (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 ignored) {
        // Ignore.
        }
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) User(org.jivesoftware.openfire.user.User) JID(org.xmpp.packet.JID) Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) DirContext(javax.naming.directory.DirContext) Date(java.util.Date) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Example 40 with UserNotFoundException

use of org.jivesoftware.openfire.user.UserNotFoundException in project Openfire by igniterealtime.

the class MUCRoomHistory method addMessage.

public void addMessage(Message packet) {
    boolean isSubjectChangeRequest = isSubjectChangeRequest(packet);
    JID fromJID = packet.getFrom();
    // unless the message is changing the room's subject
    if (!isSubjectChangeRequest && (fromJID == null || fromJID.toString().length() == 0 || fromJID.equals(room.getRole().getRoleAddress()))) {
        return;
    }
    // Do not store regular messages if there is no message strategy (keep subject change requests)
    if (!isSubjectChangeRequest && !historyStrategy.isHistoryEnabled()) {
        return;
    }
    // Ignore empty messages (no subject AND no body)
    if (!isSubjectChangeRequest && (packet.getBody() == null || packet.getBody().trim().length() == 0)) {
        return;
    }
    Message packetToAdd = packet.createCopy();
    // Check if the room has changed its configuration
    if (isNonAnonymousRoom != room.canAnyoneDiscoverJID()) {
        isNonAnonymousRoom = room.canAnyoneDiscoverJID();
        // TODO Make this update in a separate thread
        for (Iterator<Message> it = getMessageHistory(); it.hasNext(); ) {
            Message message = it.next();
            Element delayElement = message.getChildElement("delay", "urn:xmpp:delay");
            if (room.canAnyoneDiscoverJID()) {
                // Set the Full JID as the "from" attribute
                try {
                    MUCRole role = room.getOccupant(message.getFrom().getResource());
                    delayElement.addAttribute("from", role.getUserAddress().toString());
                } catch (UserNotFoundException e) {
                // Ignore.
                }
            } else {
                // Set the Room JID as the "from" attribute
                delayElement.addAttribute("from", message.getFrom().toString());
            }
        }
    }
    // Add the delay information to the message
    Element delayInformation = packetToAdd.addChildElement("delay", "urn:xmpp:delay");
    Date current = new Date();
    delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(current));
    if (room.canAnyoneDiscoverJID()) {
        // Set the Full JID as the "from" attribute
        try {
            MUCRole role = room.getOccupant(packet.getFrom().getResource());
            delayInformation.addAttribute("from", role.getUserAddress().toString());
        } catch (UserNotFoundException e) {
        // Ignore.
        }
    } else {
        // Set the Room JID as the "from" attribute
        delayInformation.addAttribute("from", packet.getFrom().toString());
    }
    historyStrategy.addMessage(packetToAdd);
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) JID(org.xmpp.packet.JID) Message(org.xmpp.packet.Message) Element(org.dom4j.Element) Date(java.util.Date)

Aggregations

UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)118 JID (org.xmpp.packet.JID)50 Element (org.dom4j.Element)28 Roster (org.jivesoftware.openfire.roster.Roster)27 RosterItem (org.jivesoftware.openfire.roster.RosterItem)26 User (org.jivesoftware.openfire.user.User)25 UserAlreadyExistsException (org.jivesoftware.openfire.user.UserAlreadyExistsException)23 IQ (org.xmpp.packet.IQ)15 ArrayList (java.util.ArrayList)14 UnauthorizedException (org.jivesoftware.openfire.auth.UnauthorizedException)12 SharedGroupException (org.jivesoftware.openfire.SharedGroupException)11 Group (org.jivesoftware.openfire.group.Group)10 UserManager (org.jivesoftware.openfire.user.UserManager)10 Workgroup (org.jivesoftware.xmpp.workgroup.Workgroup)10 Presence (org.xmpp.packet.Presence)10 NotFoundException (org.jivesoftware.util.NotFoundException)9 SQLException (java.sql.SQLException)8 List (java.util.List)8 IOException (java.io.IOException)7 Connection (java.sql.Connection)7