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();
}
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);
}
}
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);
}
}
use of org.jivesoftware.openfire.user.UserAlreadyExistsException in project Openfire by igniterealtime.
the class LocalMUCRoom method joinRoom.
@Override
public LocalMUCRole joinRoom(String nickname, String password, HistoryRequest historyRequest, LocalMUCUser user, Presence presence) throws UnauthorizedException, UserAlreadyExistsException, RoomLockedException, ForbiddenException, RegistrationRequiredException, ConflictException, ServiceUnavailableException, NotAcceptableException {
if (((MultiUserChatServiceImpl) mucService).getMUCDelegate() != null) {
if (!((MultiUserChatServiceImpl) mucService).getMUCDelegate().joiningRoom(this, user.getAddress())) {
// Delegate said no, reject join.
throw new UnauthorizedException();
}
}
LocalMUCRole joinRole = null;
lock.writeLock().lock();
boolean clientOnlyJoin = false;
// A "client only join" here is one where the client is already joined, but has re-joined.
try {
// If the room has a limit of max user then check if the limit has been reached
if (!canJoinRoom(user)) {
throw new ServiceUnavailableException();
}
final JID bareJID = user.getAddress().asBareJID();
boolean isOwner = owners.includes(bareJID);
// If the room is locked and this user is not an owner raise a RoomLocked exception
if (isLocked()) {
if (!isOwner) {
throw new RoomLockedException();
}
}
// Check if the nickname is already used in the room
if (occupantsByNickname.containsKey(nickname.toLowerCase())) {
List<MUCRole> occupants = occupantsByNickname.get(nickname.toLowerCase());
MUCRole occupant = occupants.size() > 0 ? occupants.get(0) : null;
if (occupant != null && !occupant.getUserAddress().toBareJID().equals(bareJID.toBareJID())) {
// Nickname is already used, and not by the same JID
throw new UserAlreadyExistsException();
}
if (occupant.getUserAddress().equals(user.getAddress())) {
// This user is already an occupant. The client thinks it isn't. (Or else this is a broken gmail).
clientOnlyJoin = true;
}
}
// Unauthorized exception
if (isPasswordProtected()) {
if (password == null || !password.equals(getPassword())) {
throw new UnauthorizedException();
}
}
// raise a ConflictException
if (members.containsValue(nickname.toLowerCase())) {
if (!nickname.toLowerCase().equals(members.get(bareJID))) {
throw new ConflictException();
}
}
if (isLoginRestrictedToNickname()) {
String reservedNickname = members.get(bareJID);
if (reservedNickname != null && !nickname.toLowerCase().equals(reservedNickname)) {
throw new NotAcceptableException();
}
}
// Set the corresponding role based on the user's affiliation
MUCRole.Role role;
MUCRole.Affiliation affiliation;
if (isOwner) {
// The user is an owner. Set the role and affiliation accordingly.
role = MUCRole.Role.moderator;
affiliation = MUCRole.Affiliation.owner;
} else if (mucService.isSysadmin(bareJID)) {
// The user is a system administrator of the MUC service. Treat him as an owner
// although he won't appear in the list of owners
role = MUCRole.Role.moderator;
affiliation = MUCRole.Affiliation.owner;
} else if (admins.includes(bareJID)) {
// The user is an admin. Set the role and affiliation accordingly.
role = MUCRole.Role.moderator;
affiliation = MUCRole.Affiliation.admin;
} else // explicit outcast status has higher precedence than member status
if (outcasts.contains(bareJID)) {
// The user is an outcast. Raise a "Forbidden" exception.
throw new ForbiddenException();
} else if (members.includesKey(bareJID)) {
// The user is a member. Set the role and affiliation accordingly.
role = MUCRole.Role.participant;
affiliation = MUCRole.Affiliation.member;
} else // this checks if the user is an outcast implicitly (via a group)
if (outcasts.includes(bareJID)) {
// The user is an outcast. Raise a "Forbidden" exception.
throw new ForbiddenException();
} else {
// The user has no affiliation (i.e. NONE). Set the role accordingly.
if (isMembersOnly()) {
// "Registration Required" exception.
throw new RegistrationRequiredException();
}
role = (isModerated() ? MUCRole.Role.visitor : MUCRole.Role.participant);
affiliation = MUCRole.Affiliation.none;
}
if (!clientOnlyJoin) {
// Create a new role for this user in this room
joinRole = new LocalMUCRole(mucService, this, nickname, role, affiliation, user, presence, router);
// Add the new user as an occupant of this room
List<MUCRole> occupants = occupantsByNickname.get(nickname.toLowerCase());
if (occupants == null) {
occupants = new ArrayList<>();
occupantsByNickname.put(nickname.toLowerCase(), occupants);
}
occupants.add(joinRole);
// Update the tables of occupants based on the bare and full JID
List<MUCRole> list = occupantsByBareJID.get(bareJID);
if (list == null) {
list = new ArrayList<>();
occupantsByBareJID.put(bareJID, list);
}
list.add(joinRole);
occupantsByFullJID.put(user.getAddress(), joinRole);
} else {
// Grab the existing one.
joinRole = (LocalMUCRole) occupantsByFullJID.get(user.getAddress());
}
} finally {
lock.writeLock().unlock();
}
// Notify other cluster nodes that a new occupant joined the room
CacheFactory.doClusterTask(new OccupantAddedEvent(this, joinRole));
// Send presence of existing occupants to new occupant
sendInitialPresences(joinRole);
// It is assumed that the room is new based on the fact that it's locked and
// that it was locked when it was created.
boolean isRoomNew = isLocked() && creationDate.getTime() == lockedTime;
try {
// Send the presence of this new occupant to existing occupants
Presence joinPresence = joinRole.getPresence().createCopy();
broadcastPresence(joinPresence, true);
} catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
// confirmed" message
if (!isRoomNew && isLocked()) {
// http://xmpp.org/extensions/xep-0045.html#enter-locked
Presence presenceItemNotFound = new Presence(Presence.Type.error);
presenceItemNotFound.setError(PacketError.Condition.item_not_found);
presenceItemNotFound.setFrom(role.getRoleAddress());
joinRole.send(presenceItemNotFound);
}
if (historyRequest == null) {
Iterator<Message> history = roomHistory.getMessageHistory();
while (history.hasNext()) {
joinRole.send(history.next());
}
} else {
historyRequest.sendHistory(joinRole, roomHistory);
}
Message roomSubject = roomHistory.getChangedSubject();
if (roomSubject != null) {
joinRole.send(roomSubject);
}
if (!clientOnlyJoin) {
// Update the date when the last occupant left the room
setEmptyDate(null);
// Fire event that occupant joined the room
MUCEventDispatcher.occupantJoined(getRole().getRoleAddress(), user.getAddress(), joinRole.getNickname());
}
return joinRole;
}
use of org.jivesoftware.openfire.user.UserAlreadyExistsException in project Openfire by igniterealtime.
the class LocalMUCUser method process.
public void process(Presence packet) {
// Ignore presences of type ERROR sent to a room
if (Presence.Type.error == packet.getType()) {
return;
}
lastPacketTime = System.currentTimeMillis();
JID recipient = packet.getTo();
String group = recipient.getNode();
if (group != null) {
MUCRole role = roles.get(group);
Element mucInfo = packet.getChildElement("x", "http://jabber.org/protocol/muc");
if (role == null || mucInfo != null) {
// Alternative is that mucInfo is not null, in which case the client thinks it isn't in the room, so we should join anyway.
if (recipient.getResource() != null && recipient.getResource().trim().length() > 0) {
if (packet.isAvailable()) {
try {
// Get or create the room
MUCRoom room = server.getChatRoom(group, packet.getFrom());
// User must support MUC in order to create a room
HistoryRequest historyRequest = null;
String password = null;
// Check for password & requested history if client supports MUC
if (mucInfo != null) {
password = mucInfo.elementTextTrim("password");
if (mucInfo.element("history") != null) {
historyRequest = new HistoryRequest(mucInfo);
}
}
// The user joins the room
role = room.joinRoom(recipient.getResource().trim(), password, historyRequest, this, packet.createCopy());
// unlock the room thus creating an "instant" room
if (mucInfo == null && room.isLocked() && !room.isManuallyLocked()) {
room.unlock(role);
}
} catch (UnauthorizedException e) {
sendErrorPacket(packet, PacketError.Condition.not_authorized);
} catch (ServiceUnavailableException e) {
sendErrorPacket(packet, PacketError.Condition.service_unavailable);
} catch (UserAlreadyExistsException | ConflictException e) {
sendErrorPacket(packet, PacketError.Condition.conflict);
} catch (RoomLockedException e) {
// If a user attempts to enter a room while it is "locked" (i.e., before the room creator provides an initial configuration and therefore before the room officially exists), the service MUST refuse entry and return an <item-not-found/> error to the user
sendErrorPacket(packet, PacketError.Condition.item_not_found);
} catch (ForbiddenException e) {
sendErrorPacket(packet, PacketError.Condition.forbidden);
} catch (RegistrationRequiredException e) {
sendErrorPacket(packet, PacketError.Condition.registration_required);
} catch (NotAcceptableException e) {
sendErrorPacket(packet, PacketError.Condition.not_acceptable);
} catch (NotAllowedException e) {
sendErrorPacket(packet, PacketError.Condition.not_allowed);
}
} else {
// TODO: send error message to user (can't send presence to group you
// haven't joined)
}
} else {
if (packet.isAvailable()) {
// A resource is required in order to join a room
// http://xmpp.org/extensions/xep-0045.html#enter
// If the user does not specify a room nickname (note the bare JID on the 'from' address in the following example), the service MUST return a <jid-malformed/> error
sendErrorPacket(packet, PacketError.Condition.jid_malformed);
}
// TODO: send error message to user (can't send packets to group you haven't
// joined)
}
} else {
// In other words, another user already has this nickname
if (!role.getUserAddress().equals(packet.getFrom())) {
sendErrorPacket(packet, PacketError.Condition.conflict);
} else {
if (Presence.Type.unavailable == packet.getType()) {
try {
// TODO Consider that different nodes can be creating and processing this presence at the same time (when remote node went down)
removeRole(group);
role.getChatRoom().leaveRoom(role);
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
} else {
try {
String resource = (recipient.getResource() == null || recipient.getResource().trim().length() == 0 ? null : recipient.getResource().trim());
if (resource == null || role.getNickname().equalsIgnoreCase(resource)) {
// Occupant has changed his availability status
role.getChatRoom().presenceUpdated(role, packet);
} else {
// Check if occupants are allowed to change their nicknames
if (!role.getChatRoom().canChangeNickname()) {
sendErrorPacket(packet, PacketError.Condition.not_acceptable);
} else // Answer a conflic error if the new nickname is taken
if (role.getChatRoom().hasOccupant(resource)) {
sendErrorPacket(packet, PacketError.Condition.conflict);
} else {
// Send "unavailable" presence for the old nickname
Presence presence = role.getPresence().createCopy();
// Switch the presence to OFFLINE
presence.setType(Presence.Type.unavailable);
presence.setStatus(null);
// Add the new nickname and status 303 as properties
Element frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
frag.element("item").addAttribute("nick", resource);
frag.addElement("status").addAttribute("code", "303");
role.getChatRoom().send(presence);
// Send availability presence for the new nickname
String oldNick = role.getNickname();
role.getChatRoom().nicknameChanged(role, packet, oldNick, resource);
}
}
} catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
}
} else {
// Packets to the groupchat server. This should not occur (should be handled by MultiUserChatServiceImpl instead)
Log.warn(LocaleUtils.getLocalizedString("muc.error.not-supported") + " " + packet.toString());
}
}
Aggregations