Search in sources :

Example 11 with UserAlreadyExistsException

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

the class UserServiceLegacy method userSerivceRequest.

@GET
@Path("/userservice")
public Response userSerivceRequest() throws IOException {
    // Printwriter for writing out responses to browser
    PrintWriter out = response.getWriter();
    if (!plugin.getAllowedIPs().isEmpty()) {
        // Get client's IP address
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null) {
            ipAddress = request.getHeader("X_FORWARDED_FOR");
            if (ipAddress == null) {
                ipAddress = request.getHeader("X-Forward-For");
                if (ipAddress == null) {
                    ipAddress = request.getRemoteAddr();
                }
            }
        }
        if (!plugin.getAllowedIPs().contains(ipAddress)) {
            Log.warn("User service rejected service to IP address: " + ipAddress);
            replyError("RequestNotAuthorised", response, out);
            return Response.status(200).build();
        }
    }
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String type = request.getParameter("type");
    String secret = request.getParameter("secret");
    String groupNames = request.getParameter("groups");
    String item_jid = request.getParameter("item_jid");
    String sub = request.getParameter("subscription");
    // Check that our plugin is enabled.
    if (!plugin.isEnabled()) {
        Log.warn("User service plugin is disabled: " + request.getQueryString());
        replyError("UserServiceDisabled", response, out);
        return Response.status(200).build();
    }
    // Check this request is authorised
    if (secret == null || !secret.equals(plugin.getSecret())) {
        Log.warn("An unauthorised user service request was received: " + request.getQueryString());
        replyError("RequestNotAuthorised", response, out);
        return Response.status(200).build();
    }
    // Some checking is required on the username
    if (username == null && !"grouplist".equals(type)) {
        replyError("IllegalArgumentException", response, out);
        return Response.status(200).build();
    }
    if ((type.equals("add_roster") || type.equals("update_roster") || type.equals("delete_roster")) && (item_jid == null || !(sub == null || sub.equals("-1") || sub.equals("0") || sub.equals("1") || sub.equals("2") || sub.equals("3")))) {
        replyError("IllegalArgumentException", response, out);
        return Response.status(200).build();
    }
    // Check the request type and process accordingly
    try {
        if ("grouplist".equals(type)) {
            String message = "";
            for (String groupname : userServiceController.getAllGroups()) {
                message += "<groupname>" + groupname + "</groupname>";
            }
            replyMessage(message, response, out);
        } else {
            username = username.trim().toLowerCase();
            username = JID.escapeNode(username);
            username = Stringprep.nodeprep(username);
            if ("add".equals(type)) {
                userServiceController.createUser(username, password, name, email, groupNames);
                replyMessage("ok", response, out);
            } else if ("delete".equals(type)) {
                userServiceController.deleteUser(username);
                replyMessage("ok", response, out);
            } else if ("enable".equals(type)) {
                userServiceController.enableUser(username);
                replyMessage("ok", response, out);
            } else if ("disable".equals(type)) {
                userServiceController.disableUser(username);
                replyMessage("ok", response, out);
            } else if ("update".equals(type)) {
                userServiceController.updateUser(username, password, name, email, groupNames);
                replyMessage("ok", response, out);
            } else if ("add_roster".equals(type)) {
                userServiceController.addRosterItem(username, item_jid, name, sub, groupNames);
                replyMessage("ok", response, out);
            } else if ("update_roster".equals(type)) {
                userServiceController.updateRosterItem(username, item_jid, name, sub, groupNames);
                replyMessage("ok", response, out);
            } else if ("delete_roster".equals(type)) {
                userServiceController.deleteRosterItem(username, item_jid);
                replyMessage("ok", response, out);
            } else if ("usergrouplist".equals(type)) {
                String message = "";
                for (String groupname : userServiceController.getUserGroups(username)) {
                    message += "<groupname>" + groupname + "</groupname>";
                }
                replyMessage(message, response, out);
            } else {
                Log.warn("The userService servlet received an invalid request of type: " + type);
            // TODO Do something
            }
        }
    } catch (UserAlreadyExistsException e) {
        replyError("UserAlreadyExistsException", response, out);
    } catch (UserNotFoundException e) {
        replyError("UserNotFoundException", response, out);
    } catch (IllegalArgumentException e) {
        replyError("IllegalArgumentException", response, out);
    } catch (SharedGroupException e) {
        replyError("SharedGroupException", response, out);
    } catch (Exception e) {
        Log.error("Error: ", e);
        replyError(e.toString(), response, out);
    }
    return Response.status(200).build();
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) SharedGroupException(org.jivesoftware.openfire.SharedGroupException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) IOException(java.io.IOException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) SharedGroupException(org.jivesoftware.openfire.SharedGroupException) PrintWriter(java.io.PrintWriter) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 12 with UserAlreadyExistsException

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

the class UserServiceController 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.plugin.rest.exceptions.ServiceException) JID(org.xmpp.packet.JID) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException)

Example 13 with UserAlreadyExistsException

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

the class UserServiceLegacyController method addRosterItem.

/**
	 * Add new roster item for specified user.
	 *
	 * @param username            the username of the local user to add roster item to.
	 * @param itemJID            the JID of the roster item to be added.
	 * @param itemName            the nickname of the roster item.
	 * @param subscription            the type of subscription of the roster item. Possible values
	 *            are: -1(remove), 0(none), 1(to), 2(from), 3(both).
	 * @param groupNames            the name of a group to place contact into.
	 * @throws UserNotFoundException             if the user does not exist in the local server.
	 * @throws UserAlreadyExistsException             if roster item with the same JID already exists.
	 * @throws SharedGroupException             if roster item cannot be added to a shared group.
	 */
public void addRosterItem(String username, String itemJID, String itemName, String subscription, String groupNames) throws UserNotFoundException, UserAlreadyExistsException, SharedGroupException {
    getUser(username);
    Roster r = rosterManager.getRoster(username);
    JID j = new JID(itemJID);
    try {
        r.getRosterItem(j);
        throw new UserAlreadyExistsException(j.toBareJID());
    } catch (UserNotFoundException e) {
    // Roster item does not exist. Try to add it.
    }
    if (r != null) {
        List<String> groups = new ArrayList<String>();
        if (groupNames != null) {
            StringTokenizer tkn = new StringTokenizer(groupNames, ",");
            while (tkn.hasMoreTokens()) {
                groups.add(tkn.nextToken());
            }
        }
        RosterItem ri = r.createRosterItem(j, itemName, groups, false, true);
        if (subscription == null) {
            subscription = "0";
        }
        ri.setSubStatus(RosterItem.SubType.getTypeFromInt(Integer.parseInt(subscription)));
        r.updateRosterItem(ri);
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) RosterItem(org.jivesoftware.openfire.roster.RosterItem) StringTokenizer(java.util.StringTokenizer) Roster(org.jivesoftware.openfire.roster.Roster) JID(org.xmpp.packet.JID) ArrayList(java.util.ArrayList) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException)

Example 14 with UserAlreadyExistsException

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

the class POP3AuthProvider method authenticate.

@Override
public void authenticate(String username, String password) throws UnauthorizedException {
    if (username == null || password == null) {
        throw new 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();
    }
    Log.debug("POP3AuthProvider.authenticate(" + username + ", ******)");
    // If cache is enabled, see if the auth is in cache.
    if (authCache != null && authCache.containsKey(username)) {
        String hash = authCache.get(username);
        if (StringUtils.hash(password).equals(hash)) {
            return;
        }
    }
    Properties mailProps = new Properties();
    mailProps.setProperty("mail.debug", String.valueOf(debugEnabled));
    Session session = Session.getInstance(mailProps, null);
    Store store;
    try {
        store = session.getStore(useSSL ? "pop3s" : "pop3");
    } catch (NoSuchProviderException e) {
        Log.error(e.getMessage(), e);
        throw new UnauthorizedException(e);
    }
    try {
        if (authRequiresDomain) {
            store.connect(host, port, username + "@" + domain, password);
        } else {
            store.connect(host, port, username, password);
        }
    } catch (Exception e) {
        Log.error(e.getMessage(), e);
        throw new UnauthorizedException(e);
    }
    if (!store.isConnected()) {
        throw new UnauthorizedException("Could not authenticate user");
    }
    try {
        store.close();
    } catch (Exception e) {
    // Ignore.
    }
    // If cache is enabled, add the item to cache.
    if (authCache != null) {
        authCache.put(username, StringUtils.hash(password));
    }
    // See if the user exists in the database. If not, automatically create them.
    UserManager userManager = UserManager.getInstance();
    try {
        userManager.getUser(username);
    } catch (UserNotFoundException unfe) {
        String email = username + "@" + (domain != null ? domain : host);
        try {
            Log.debug("POP3AuthProvider: 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.
            UserManager.getUserProvider().createUser(username, StringUtils.randomString(8), null, email);
        } catch (UserAlreadyExistsException uaee) {
        // Ignore.
        }
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) UserManager(org.jivesoftware.openfire.user.UserManager) Store(javax.mail.Store) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) Properties(java.util.Properties) NoSuchProviderException(javax.mail.NoSuchProviderException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) NoSuchProviderException(javax.mail.NoSuchProviderException) Session(javax.mail.Session)

Example 15 with UserAlreadyExistsException

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

the class AddUser method execute.

@Override
public void execute(SessionData sessionData, Element command) {
    Element note = command.addElement("note");
    // Check if groups cannot be modified (backend is read-only)
    if (UserManager.getUserProvider().isReadOnly()) {
        note.addAttribute("type", "error");
        note.setText("User provider is read only. New users cannot be created.");
        return;
    }
    Map<String, List<String>> data = sessionData.getData();
    // Let's create the jid and check that they are a local user
    JID account;
    try {
        account = new JID(get(data, "accountjid", 0));
    } catch (NullPointerException npe) {
        note.addAttribute("type", "error");
        note.setText("JID required parameter.");
        return;
    }
    if (!XMPPServer.getInstance().isLocal(account)) {
        note.addAttribute("type", "error");
        note.setText("Cannot create remote user.");
        return;
    }
    String password = get(data, "password", 0);
    String passwordRetry = get(data, "password-verify", 0);
    if (password == null || "".equals(password) || !password.equals(passwordRetry)) {
        note.addAttribute("type", "error");
        note.setText("Passwords do not match.");
        return;
    }
    String email = get(data, "email", 0);
    String givenName = get(data, "given_name", 0);
    String surName = get(data, "surname", 0);
    String name = (givenName == null ? "" : givenName) + (surName == null ? "" : surName);
    name = (name.equals("") ? null : name);
    // If provider requires email, validate
    if (UserManager.getUserProvider().isEmailRequired() && !StringUtils.isValidEmailAddress(email)) {
        note.addAttribute("type", "error");
        note.setText("No email was specified.");
        return;
    }
    try {
        UserManager.getInstance().createUser(account.getNode(), password, name, email);
    } catch (UserAlreadyExistsException e) {
        note.addAttribute("type", "error");
        note.setText("User already exists.");
        return;
    }
    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
Also used : JID(org.xmpp.packet.JID) Element(org.dom4j.Element) List(java.util.List) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException)

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