Search in sources :

Example 16 with UserAlreadyExistsException

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

the class IQRegisterHandler method handleIQ.

@Override
public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
    ClientSession session = sessionManager.getSession(packet.getFrom());
    IQ reply = null;
    // If no session was found then answer an error (if possible)
    if (session == null) {
        Log.error("Error during registration. Session not found in " + sessionManager.getPreAuthenticatedKeys() + " for key " + packet.getFrom());
        // This error packet will probably won't make it through
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.internal_server_error);
        return reply;
    }
    if (IQ.Type.get.equals(packet.getType())) {
        // If inband registration is not allowed, return an error.
        if (!registrationEnabled) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.forbidden);
        } else {
            reply = IQ.createResultIQ(packet);
            if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                try {
                    User user = userManager.getUser(session.getUsername());
                    Element currentRegistration = probeResult.createCopy();
                    currentRegistration.addElement("registered");
                    currentRegistration.element("username").setText(user.getUsername());
                    currentRegistration.element("password").setText("");
                    currentRegistration.element("email").setText(user.getEmail() == null ? "" : user.getEmail());
                    currentRegistration.element("name").setText(user.getName());
                    Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
                    Iterator fields = form.elementIterator("field");
                    Element field;
                    while (fields.hasNext()) {
                        field = (Element) fields.next();
                        if ("username".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getUsername());
                        } else if ("name".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getName());
                        } else if ("email".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getEmail() == null ? "" : user.getEmail());
                        }
                    }
                    reply.setChildElement(currentRegistration);
                } catch (UserNotFoundException e) {
                    reply.setChildElement(probeResult.createCopy());
                }
            } else {
                // This is a workaround. Since we don't want to have an incorrect TO attribute
                // value we need to clean up the TO attribute. The TO attribute will contain an
                // incorrect value since we are setting a fake JID until the user actually
                // authenticates with the server.
                reply.setTo((JID) null);
                reply.setChildElement(probeResult.createCopy());
            }
        }
    } else if (IQ.Type.set.equals(packet.getType())) {
        try {
            Element iqElement = packet.getChildElement();
            if (iqElement.element("remove") != null) {
                // If inband registration is not allowed, return an error.
                if (!registrationEnabled) {
                    reply = IQ.createResultIQ(packet);
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.forbidden);
                } else {
                    if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                        User user = userManager.getUser(session.getUsername());
                        // Delete the user
                        userManager.deleteUser(user);
                        // Delete the roster of the user
                        rosterManager.deleteRoster(session.getAddress());
                        // Delete the user from all the Groups
                        GroupManager.getInstance().deleteUser(user);
                        reply = IQ.createResultIQ(packet);
                        session.process(reply);
                        // Take a quick nap so that the client can process the result
                        Thread.sleep(10);
                        // Close the user's connection
                        final StreamError error = new StreamError(StreamError.Condition.not_authorized);
                        for (ClientSession sess : sessionManager.getSessions(user.getUsername())) {
                            sess.deliverRawText(error.toXML());
                            sess.close();
                        }
                        // The reply has been sent so clean up the variable
                        reply = null;
                    } else {
                        throw new UnauthorizedException();
                    }
                }
            } else {
                String username;
                String password = null;
                String email = null;
                String name = null;
                User newUser;
                DataForm registrationForm;
                FormField field;
                Element formElement = iqElement.element("x");
                // Check if a form was used to provide the registration info
                if (formElement != null) {
                    // Get the sent form
                    registrationForm = new DataForm(formElement);
                    // Get the username sent in the form
                    List<String> values = registrationForm.getField("username").getValues();
                    username = (!values.isEmpty() ? values.get(0) : " ");
                    // Get the password sent in the form
                    field = registrationForm.getField("password");
                    if (field != null) {
                        values = field.getValues();
                        password = (!values.isEmpty() ? values.get(0) : " ");
                    }
                    // Get the email sent in the form
                    field = registrationForm.getField("email");
                    if (field != null) {
                        values = field.getValues();
                        email = (!values.isEmpty() ? values.get(0) : " ");
                    }
                    // Get the name sent in the form
                    field = registrationForm.getField("name");
                    if (field != null) {
                        values = field.getValues();
                        name = (!values.isEmpty() ? values.get(0) : " ");
                    }
                } else {
                    // Get the registration info from the query elements
                    username = iqElement.elementText("username");
                    password = iqElement.elementText("password");
                    email = iqElement.elementText("email");
                    name = iqElement.elementText("name");
                }
                if (email != null && email.matches("\\s*")) {
                    email = null;
                }
                if (name != null && name.matches("\\s*")) {
                    name = null;
                }
                // stringprep validity now.
                if (username != null) {
                    Stringprep.nodeprep(username);
                }
                if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                    // Flag that indicates if the user is *only* changing his password
                    boolean onlyPassword = false;
                    if (iqElement.elements().size() == 2 && iqElement.element("username") != null && iqElement.element("password") != null) {
                        onlyPassword = true;
                    }
                    // If users are not allowed to change their password, return an error.
                    if (password != null && !canChangePassword) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    } else // If inband registration is not allowed, return an error.
                    if (!onlyPassword && !registrationEnabled) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    } else {
                        User user = userManager.getUser(session.getUsername());
                        if (user.getUsername().equalsIgnoreCase(username)) {
                            if (password != null && password.trim().length() > 0) {
                                user.setPassword(password);
                            }
                            if (!onlyPassword) {
                                user.setEmail(email);
                            }
                            newUser = user;
                        } else if (password != null && password.trim().length() > 0) {
                            // An admin can create new accounts when logged in.
                            newUser = userManager.createUser(username, password, null, email);
                        } else {
                            // Deny registration of users with no password
                            reply = IQ.createResultIQ(packet);
                            reply.setChildElement(packet.getChildElement().createCopy());
                            reply.setError(PacketError.Condition.not_acceptable);
                            return reply;
                        }
                    }
                } else {
                    // If inband registration is not allowed, return an error.
                    if (!registrationEnabled) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    } else // information was not provided
                    if (password == null || password.trim().length() == 0) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.not_acceptable);
                        return reply;
                    } else {
                        // Create the new account
                        newUser = userManager.createUser(username, password, name, email);
                    }
                }
                // Set and save the extra user info (e.g. full name, etc.)
                if (newUser != null && name != null && !name.equals(newUser.getName())) {
                    newUser.setName(name);
                }
                reply = IQ.createResultIQ(packet);
            }
        } catch (UserAlreadyExistsException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.conflict);
        } catch (UserNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.bad_request);
        } catch (StringprepException e) {
            // The specified username is not correct according to the stringprep specs
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.jid_malformed);
        } catch (IllegalArgumentException e) {
            // At least one of the fields passed in is not valid
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_acceptable);
            Log.warn(e.getMessage(), e);
        } catch (UnsupportedOperationException e) {
            // The User provider is read-only so this operation is not allowed
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_allowed);
        } catch (Exception e) {
            // Some unexpected error happened so return an internal_server_error
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            Log.error(e.getMessage(), e);
        }
    }
    if (reply != null) {
        // why is this done here instead of letting the iq handler do it?
        session.process(reply);
    }
    return null;
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) User(org.jivesoftware.openfire.user.User) Element(org.dom4j.Element) IQ(org.xmpp.packet.IQ) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) StringprepException(gnu.inet.encoding.StringprepException) PacketException(org.jivesoftware.openfire.PacketException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) StringprepException(gnu.inet.encoding.StringprepException) StreamError(org.xmpp.packet.StreamError) ClientSession(org.jivesoftware.openfire.session.ClientSession) Iterator(java.util.Iterator) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) DataForm(org.xmpp.forms.DataForm) List(java.util.List) FormField(org.xmpp.forms.FormField)

Example 17 with UserAlreadyExistsException

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

the class UserCreationPlugin method createUsers.

public void createUsers(String userPrefix, int from, int total) {
    // Create users
    UserManager userManager = XMPPServer.getInstance().getUserManager();
    System.out.println("Creating users accounts: " + total);
    int created = 0;
    for (int i = from; i < from + total; i++) {
        try {
            String username = userPrefix + i;
            userManager.createUser(username, username, username, username + "@" + username);
            created++;
        } catch (UserAlreadyExistsException e) {
        // Ignore
        }
    }
    System.out.println("Accounts created successfully: " + created);
}
Also used : UserManager(org.jivesoftware.openfire.user.UserManager) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException)

Example 18 with UserAlreadyExistsException

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

the class UserServicePluginNG method addRosterItem.

/**
	 * Adds the roster item.
	 *
	 * @param username
	 *            the username
	 * @param rosterItemEntity
	 *            the roster item entity
	 * @throws ServiceException
	 *             the service exception
	 * @throws UserAlreadyExistsException
	 *             the user already exists exception
	 * @throws SharedGroupException
	 *             the shared group exception
	 * @throws UserNotFoundException
	 *             the user not found exception
	 */
public void addRosterItem(String username, RosterItemEntity rosterItemEntity) throws ServiceException, UserAlreadyExistsException, SharedGroupException, UserNotFoundException {
    Roster roster = getUserRoster(username);
    if (rosterItemEntity.getJid() == null) {
        throw new ServiceException("JID is null", "JID", "IllegalArgumentException", Response.Status.BAD_REQUEST);
    }
    JID jid = new JID(rosterItemEntity.getJid());
    try {
        roster.getRosterItem(jid);
        throw new UserAlreadyExistsException(jid.toBareJID());
    } catch (UserNotFoundException e) {
    // Roster item does not exist. Try to add it.
    }
    if (roster != null) {
        RosterItem rosterItem = roster.createRosterItem(jid, rosterItemEntity.getNickname(), rosterItemEntity.getGroups(), false, true);
        UserUtils.checkSubType(rosterItemEntity.getSubscriptionType());
        rosterItem.setSubStatus(RosterItem.SubType.getTypeFromInt(rosterItemEntity.getSubscriptionType()));
        roster.updateRosterItem(rosterItem);
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) RosterItem(org.jivesoftware.openfire.roster.RosterItem) Roster(org.jivesoftware.openfire.roster.Roster) ServiceException(org.jivesoftware.openfire.exceptions.ServiceException) JID(org.xmpp.packet.JID) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException)

Example 19 with UserAlreadyExistsException

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

the class JustMarriedPlugin method copyRoster.

private static void copyRoster(User currentUser, User newUser, String currentUserName) {
    Roster newRoster = newUser.getRoster();
    Roster currentRoster = currentUser.getRoster();
    for (RosterItem item : currentRoster.getRosterItems()) {
        try {
            List<String> groups = item.getGroups();
            RosterItem justCreated = newRoster.createRosterItem(item.getJid(), item.getNickname(), groups, true, true);
            justCreated.setAskStatus(item.getAskStatus());
            justCreated.setRecvStatus(item.getRecvStatus());
            justCreated.setSubStatus(item.getSubStatus());
            for (Group gr : item.getSharedGroups()) {
                justCreated.addSharedGroup(gr);
            }
            for (Group gr : item.getInvisibleSharedGroups()) {
                justCreated.addInvisibleSharedGroup(gr);
            }
            newRoster.updateRosterItem(justCreated);
            addNewUserToOthersRoster(newUser, item, currentUserName);
        } catch (UserAlreadyExistsException e) {
            Log.error("Could not create roster item for user " + item.getJid(), e);
        } catch (SharedGroupException e) {
            Log.error("Could not create roster item for user " + item.getJid() + " because it is a contact from a shared group", e);
        } catch (UserNotFoundException e) {
            Log.error("Could not update Roster item for user " + newUser.getName() + " because it was not properly created.", e);
        }
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) RosterItem(org.jivesoftware.openfire.roster.RosterItem) Group(org.jivesoftware.openfire.group.Group) Roster(org.jivesoftware.openfire.roster.Roster) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) SharedGroupException(org.jivesoftware.openfire.SharedGroupException)

Example 20 with UserAlreadyExistsException

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

the class BaseTransport method addOrUpdateRosterItem.

/**
     * Either updates or adds a JID to a user's roster.
     *
     * Tries to only edit the roster if it has to.
     *
     * @param userjid JID of user to have item added to their roster.
     * @param contactjid JID to add to roster.
     * @param nickname Nickname of item. (can be null)
     * @param groups List of group the item is to be placed in. (can be null)
     * @param subtype Specific subscription setting.
     * @param asktype Specific ask setting.
     * @throws UserNotFoundException if userjid not found.
     */
public void addOrUpdateRosterItem(JID userjid, JID contactjid, String nickname, Collection<String> groups, RosterItem.SubType subtype, RosterItem.AskType asktype) throws UserNotFoundException {
    Log.debug("add or update roster item " + contactjid + " for: " + userjid);
    try {
        final Roster roster = rosterManager.getRoster(userjid.getNode());
        try {
            RosterItem gwitem = roster.getRosterItem(contactjid);
            Log.debug("Found existing roster item " + contactjid + " for: " + userjid + ". We will update if required.");
            boolean changed = false;
            if (gwitem.getSubStatus() != subtype) {
                gwitem.setSubStatus(subtype);
                changed = true;
            }
            if (gwitem.getAskStatus() != asktype) {
                gwitem.setAskStatus(asktype);
                changed = true;
            }
            // gnickname is not null, nickname is not null, if different, set gnickname to nickname
            if ((gwitem.getNickname() != null && nickname == null) || (gwitem.getNickname() == null && nickname != null) || (gwitem.getNickname() != null && nickname != null && !gwitem.getNickname().equals(nickname))) {
                gwitem.setNickname(nickname);
                changed = true;
            }
            List<String> curgroups = gwitem.getGroups();
            // curgroups is not null, groups is not null, if their sizes are different or curgroups does not contain all of groups, set curgroups to groups
            if (((curgroups != null && curgroups.size() > 0) && (groups == null || groups.size() == 0)) || ((curgroups == null || curgroups.size() == 0) && (groups != null && groups.size() > 0)) || (curgroups != null && groups != null && ((curgroups.size() != groups.size()) || !curgroups.containsAll(groups)))) {
                try {
                    gwitem.setGroups((List<String>) (groups != null ? groups : new ArrayList<String>()));
                    changed = true;
                } catch (Exception ee) {
                    Log.debug("Exception while setting groups for roster item:", ee);
                }
            }
            if (changed) {
                Log.debug("Updating existing roster item " + contactjid + " for: " + userjid);
                roster.updateRosterItem(gwitem);
            } else {
                Log.debug("Update of existing roster item " + contactjid + " for: " + userjid + " can be skipped - nothing changed.");
            }
        } catch (UserNotFoundException e) {
            try {
                // Create new roster item for the gateway service or legacy contact. Only
                // roster items related to the gateway service will be persistent. Roster
                // items of legacy users are never persisted in the DB.  (unless tweak enabled)
                Log.debug("Creating new roster item " + contactjid + " for: " + userjid + ". No existing item was found.");
                final RosterItem gwitem = roster.createRosterItem(contactjid, false, contactjid.getNode() == null || JiveGlobals.getBooleanProperty("plugin.gateway.tweak.persistentroster", false));
                gwitem.setSubStatus(subtype);
                gwitem.setAskStatus(asktype);
                gwitem.setNickname(nickname);
                try {
                    gwitem.setGroups((List<String>) groups);
                } catch (Exception ee) {
                    Log.debug("Exception while setting groups for gateway item:", ee);
                }
                roster.updateRosterItem(gwitem);
            } catch (UserAlreadyExistsException ee) {
                Log.debug("getRosterItem claims user exists, but couldn't find via getRosterItem?", ee);
            } catch (Exception ee) {
                Log.debug("Exception while creating roster item:", ee);
            }
        }
    } catch (UserNotFoundException e) {
        throw new UserNotFoundException("Could not find roster for " + userjid.toString());
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) Roster(org.jivesoftware.openfire.roster.Roster) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) NotFoundException(org.jivesoftware.util.NotFoundException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Aggregations

UserAlreadyExistsException (org.jivesoftware.openfire.user.UserAlreadyExistsException)23 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)19 RosterItem (org.jivesoftware.openfire.roster.RosterItem)10 Roster (org.jivesoftware.openfire.roster.Roster)9 UserManager (org.jivesoftware.openfire.user.UserManager)7 JID (org.xmpp.packet.JID)7 SharedGroupException (org.jivesoftware.openfire.SharedGroupException)6 Element (org.dom4j.Element)5 User (org.jivesoftware.openfire.user.User)5 ArrayList (java.util.ArrayList)4 UnauthorizedException (org.jivesoftware.openfire.auth.UnauthorizedException)4 ServiceException (org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException)4 StringprepException (gnu.inet.encoding.StringprepException)3 IOException (java.io.IOException)3 NotFoundException (org.jivesoftware.util.NotFoundException)3 PrintWriter (java.io.PrintWriter)2 List (java.util.List)2 StringTokenizer (java.util.StringTokenizer)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2