Java Code Examples for org.jivesoftware.openfire.auth.UnauthorizedException

The following are top voted examples for showing how to use org.jivesoftware.openfire.auth.UnauthorizedException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: message-server   File: MmxAppUtil.java   Source Code and License 6 votes vote down vote up
public static String checkAppId(String username) throws UnauthorizedException {
  if (username.contains(APPID_DELIMITER)) {
    // Check that the specified domain matches the server's domain
    int index = username.indexOf(APPID_DELIMITER);
    String appId = username.substring(index + 1);
    Log.info("app id is "+appId);

    AppEntity appEntity = appFound(appId);
    if (appEntity != null) {
      username = username.substring(0, index);
    } else {
      // Unknown app key. Return authentication failed.
      throw new UnauthorizedException("Fail to authenticate the connection for user " + username  + ". Cannot find app with app id "+appId);
    }
  }
  return username;
}
 
Example 2
Project: message-server   File: MMXPushNSHandler.java   Source Code and License 6 votes vote down vote up
@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
  LOGGER.trace("handleIQ : {}", iq);
  JID fromJID = iq.getFrom();
  String appId = JIDUtil.getAppId(fromJID);
  Element element = iq.getChildElement();
  String customType = element.attributeValue(Constants.MMX_ATTR_COMMAND);
  String dst = element.attributeValue(Constants.MMX_ATTR_DST);
  LOGGER.trace("handleIQ : dst={}, type={}", dst, customType);
  
  MMXPushManager pushMsgMgr = MMXPushManager.getInstance();
  MMXid to = new MMXid(JIDUtil.getUserId(dst), JIDUtil.getResource(dst), null);
  PushResult result = pushMsgMgr.send(fromJID, appId, to,
      Action.PUSH, customType, element.getText());
  return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(result));
}
 
Example 3
Project: message-server   File: MMXWakeupNSHandler.java   Source Code and License 6 votes vote down vote up
@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
  LOGGER.trace("handleIQ : {}", iq);
  JID fromJID = iq.getFrom();
  String appId = JIDUtil.getAppId(fromJID);
  Element element = iq.getChildElement();
  String customType = element.attributeValue(Constants.MMX_ATTR_COMMAND);
  String dst = element.attributeValue(Constants.MMX_ATTR_DST);
  LOGGER.trace("handleIQ : dst={}, type={}", dst, customType);
  
  MMXPushManager pushMsgMgr = MMXPushManager.getInstance();
  MMXid to = new MMXid(JIDUtil.getUserId(dst), JIDUtil.getResource(dst), null);
  PushResult result = pushMsgMgr.send(fromJID, appId, to,
      Action.WAKEUP, customType, element.getText());
  return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(result));
}
 
Example 4
Project: message-server   File: MMXUserHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Handle delete user.  The initiator (e.g. app-server user) must be from 
 * the same app.
 * @param packet
 * @return
 * @throws UnauthorizedException
 */
IQ handleDeleteUser(IQ packet, JID from, String appId, String payload) 
                        throws UnauthorizedException {
  UserCreate userRqt = UserCreate.fromJson(payload);
  AppDAO appDAO = new AppDAOImpl(getConnectionProvider());

  IQ validationError = validateUserDeleteRequest(packet, userRqt, appDAO);
  if (validationError != null) {
    return validationError;
  }
  String userId = userRqt.getUserId();
  String constructedUserId = JIDUtil.makeNode(userId, appId);
  MMXUserManager userManager = getUserManager();
  userManager.deleteUser(constructedUserId);
  LOGGER.info("Deleted a user with userId:" + constructedUserId);
  MMXStatus userResp = new MMXStatus();
  userResp.setCode(UserOperationStatusCode.USER_DELETED.getCode());
  userResp.setMessage(UserOperationStatusCode.USER_DELETED.getMessage());
  IQ response = IQUtils.createResultIQ(packet, userResp.toJson());
  return response;
}
 
Example 5
Project: message-server   File: MMXUserHandler.java   Source Code and License 6 votes vote down vote up
IQ handleListUsers(IQ packet, JID from, String appId, String payload)
    throws UnauthorizedException {
  ListOfUserId userIds = GsonData.getGson().fromJson(payload, ListOfUserId.class);
  HashMap<String, UserInfo> map = new HashMap<String, UserInfo>(userIds.size());
  UserManager userManager = XMPPServer.getInstance().getUserManager();
  for (UserId userId : userIds) {
    String uid = userId.getUserId().toLowerCase();
    String userName = JIDUtil.makeNode(uid, appId);
    try {
      User user = userManager.getUser(userName);
      map.put(uid, new UserInfo()
        .setUserId(uid)
        .setDisplayName(user.getName())
        .setEmail(user.getEmail()));
    } catch (UserNotFoundException e) {
      // Ignored.
    }
  }
  IQ response = IQUtils.createResultIQ(packet, GsonData.getGson().toJson(map));
  return response;
}
 
Example 6
Project: message-server   File: MMXUserHandler.java   Source Code and License 6 votes vote down vote up
IQ handleGetUser(IQ packet, JID from, String appId, String payload) 
    throws UnauthorizedException {
  String userName;
  UserId userId = UserId.fromJson(payload);
  if (userId == null || userId.getUserId() == null)
    userName = from.getNode();
  else
    userName = JIDUtil.makeNode(userId.getUserId().toLowerCase(), appId);
  
  try {
    UserManager userManager = XMPPServer.getInstance().getUserManager();
    User user = userManager.getUser(userName);
    UserInfo accountInfo = new UserInfo()
      .setUserId(userId.getUserId())
      .setDisplayName(user.getName())
      .setEmail(user.getEmail());
    IQ response = IQUtils.createResultIQ(packet, accountInfo.toJson());
    return response;
  } catch (UserNotFoundException e) {
    return IQUtils.createErrorIQ(packet,
        UserOperationStatusCode.USER_NOT_FOUND.getMessage(),
        UserOperationStatusCode.USER_NOT_FOUND.getCode());
  }
}
 
Example 7
Project: message-server   File: AppHandler.java   Source Code and License 6 votes vote down vote up
@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
  Log.info("AppHandler.handleIQ called");
  String command = IQUtils.getCommand(iq);
  if ("create".equals(command)) {
    return handleCreateApp(iq);
  } else if ("read".equals(command)) {
    return handleReadApps(iq);
  } else if ("readMine".equals(command)) {
    return handleReadMyApps(iq);
  } else if ("update".equals(command)) {
    return handleUpdateApp(iq);
  } else if ("delete".equals(command)) {
    return handleDeleteApp(iq);
  }

  return IQUtils.createErrorIQ(iq, "Unsupported operation " + command, 1);
}
 
Example 8
Project: openfire   File: IQSharedGroupHandler.java   Source Code and License 6 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
       IQ result = IQ.createResultIQ(packet);
       String username = packet.getFrom().getNode();
       if (!serverName.equals(packet.getFrom().getDomain()) || username == null) {
           // Users of remote servers are not allowed to get their "shared groups". Users of
           // remote servers cannot have shared groups in this server.
           // Besides, anonymous users do not belong to shared groups so answer an error
           result.setChildElement(packet.getChildElement().createCopy());
           result.setError(PacketError.Condition.not_allowed);
           return result;
       }

       Collection<Group> groups = rosterManager.getSharedGroups(username);
       Element sharedGroups = result.setChildElement("sharedgroup",
               "http://www.jivesoftware.org/protocol/sharedgroup");
       for (Group sharedGroup : groups) {
           String displayName = sharedGroup.getProperties().get("sharedRoster.displayName");
           if (displayName != null) {
               sharedGroups.addElement("group").setText(displayName);
           }
       }
       return result;
   }
 
Example 9
Project: Openfire   File: WebSocketConnection.java   Source Code and License 6 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException
{
    final String xml;
    if (Namespace.NO_NAMESPACE.equals(packet.getElement().getNamespace())) {
        // use string-based operation here to avoid cascading xmlns wonkery
        StringBuilder packetXml = new StringBuilder(packet.toXML());
        packetXml.insert(packetXml.indexOf(" "), " xmlns=\"jabber:client\"");
        xml = packetXml.toString();
    } else {
        xml = packet.toXML();
    }
    if (validate()) {
        deliverRawText(xml);
    } else {
        // use fallback delivery mechanism (offline)
        getPacketDeliverer().deliver(packet);
    }
}
 
Example 10
Project: openfire   File: ClearspaceManager.java   Source Code and License 6 votes vote down vote up
private void updateClearspaceSharedSecret(String newSecret) {

        try {
            String path = IM_URL_PREFIX + "updateSharedSecret/";

            // Creates the XML with the data
            Document groupDoc = DocumentHelper.createDocument();
            Element rootE = groupDoc.addElement("updateSharedSecret");
            rootE.addElement("newSecret").setText(newSecret);

            executeRequest(POST, path, groupDoc.asXML());
        } catch (UnauthorizedException ue) {
            Log.error("Error updating the password of Clearspace", ue);
        } catch (Exception e) {
            Log.error("Error updating the password of Clearspace", e);
        }

    }
 
Example 11
Project: g3server   File: PresenceUpdateHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Handle presence updates that affect roster subscriptions.
 *
 * @param presence The presence presence to handle
 * @throws PacketException if the packet is null or the packet could not be routed.
 */
public void process(Presence presence) throws PacketException {
    try {
        process((Packet)presence);
    }
    catch (UnauthorizedException e) {
        try {
            LocalSession session = (LocalSession) sessionManager.getSession(presence.getFrom());
            presence = presence.createCopy();
            if (session != null) {
                presence.setFrom(new JID(null, session.getServerName(), null, true));
                presence.setTo(session.getAddress());
            }
            else {
                JID sender = presence.getFrom();
                presence.setFrom(presence.getTo());
                presence.setTo(sender);
            }
            presence.setError(PacketError.Condition.not_authorized);
            deliverer.deliver(presence);
        }
        catch (Exception err) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), err);
        }
    }
}
 
Example 12
Project: openfire   File: PresenceUpdateHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Handle presence updates that affect roster subscriptions.
 *
 * @param presence The presence presence to handle
 * @throws PacketException if the packet is null or the packet could not be routed.
 */
public void process(Presence presence) throws PacketException {
    try {
        process((Packet)presence);
    }
    catch (UnauthorizedException e) {
        try {
            LocalSession session = (LocalSession) sessionManager.getSession(presence.getFrom());
            presence = presence.createCopy();
            if (session != null) {
                presence.setFrom(new JID(null, session.getServerName(), null, true));
                presence.setTo(session.getAddress());
            }
            else {
                JID sender = presence.getFrom();
                presence.setFrom(presence.getTo());
                presence.setTo(sender);
            }
            presence.setError(PacketError.Condition.not_authorized);
            deliverer.deliver(presence);
        }
        catch (Exception err) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), err);
        }
    }
}
 
Example 13
Project: openfire   File: MultiplexerPacketDeliverer.java   Source Code and License 6 votes vote down vote up
public void deliver(Packet packet) throws UnauthorizedException, PacketException {
    // Check if we can send the packet using another session
    if (connectionManagerDomain == null) {
        // Packet deliverer has not yet been configured so handle unprocessed packet
        handleUnprocessedPacket(packet);
    }
    else {
        // Try getting another session to the same connection manager 
        ConnectionMultiplexerSession session =
                multiplexerManager.getMultiplexerSession(connectionManagerDomain);
        if (session == null || session.isClosed()) {
            // No other session was found so handle unprocessed packet
            handleUnprocessedPacket(packet);
        }
        else {
            // Send the packet using this other session to the same connection manager
            session.process(packet);
        }
    }
}
 
Example 14
Project: Openfire   File: HttpBindServlet.java   Source Code and License 6 votes vote down vote up
protected void createNewSession(AsyncContext context, Element rootNode)
        throws IOException
{
    final long rid = getLongAttribute(rootNode.attributeValue("rid"), -1);

    try {
        final X509Certificate[] certificates = (X509Certificate[]) context.getRequest().getAttribute("javax.servlet.request.X509Certificate");
        final HttpConnection connection = new HttpConnection(rid, context.getRequest().isSecure(), certificates, context);
        final InetAddress address = InetAddress.getByName(context.getRequest().getRemoteAddr());
        connection.setSession(sessionManager.createSession(address, rootNode, connection));
        if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
            Log.info(new Date() + ": HTTP RECV(" + connection.getSession().getStreamID().getID() + "): " + rootNode.asXML());
        }
    }
    catch (UnauthorizedException | HttpBindException e) {
        // Server wasn't initialized yet.
        sendLegacyError(context, BoshBindingError.internalServerError, "Server has not finished initialization." );
    }
}
 
Example 15
Project: g3server   File: ComponentStanzaHandler.java   Source Code and License 6 votes vote down vote up
@Override
protected void processIQ(IQ packet) throws UnauthorizedException {
       if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
           // Session is not authenticated so return error
           IQ reply = new IQ();
           reply.setChildElement(packet.getChildElement().createCopy());
           reply.setID(packet.getID());
           reply.setTo(packet.getFrom());
           reply.setFrom(packet.getTo());
           reply.setError(PacketError.Condition.not_authorized);
           session.process(reply);
           return;
       }
       // Keep track of the component that sent an IQ get/set
       if (packet.getType() == IQ.Type.get || packet.getType() == IQ.Type.set) {
           // Handle subsequent bind packets
           LocalComponentSession componentSession = (LocalComponentSession) session;
           // Get the external component of this session
           LocalComponentSession.LocalExternalComponent component =
                   (LocalComponentSession.LocalExternalComponent) componentSession.getExternalComponent();
           component.track(packet);
       }
       super.processIQ(packet);
   }
 
Example 16
Project: g3server   File: ServerStanzaHandler.java   Source Code and License 6 votes vote down vote up
@Override
boolean processUnknowPacket(Element doc) throws UnauthorizedException {
       // Handle subsequent db:result packets
       if ("db".equals(doc.getNamespacePrefix()) && "result".equals(doc.getName())) {
           if (!((LocalIncomingServerSession) session).validateSubsequentDomain(doc)) {
               throw new UnauthorizedException("Failed to validate domain when using piggyback.");
           }
           return true;
       }
       else if ("db".equals(doc.getNamespacePrefix()) && "verify".equals(doc.getName())) {
           // The Receiving Server is reusing an existing connection for sending the
           // Authoritative Server a request for verification of a key
           ((LocalIncomingServerSession) session).verifyReceivedKey(doc);
           return true;
       }
       return false;
   }
 
Example 17
Project: openfire   File: HttpSession.java   Source Code and License 6 votes vote down vote up
private void failDelivery(final Collection<Packet> packets) {
     if (packets == null) {
         // Do nothing if someone asked to deliver nothing :)
         return;
     }
     // use a separate thread to schedule backup delivery
		TaskEngine.getInstance().submit(new Runnable() {
public void run() {
       for (Packet packet : packets) {
 	            try {
     				backupDeliverer.deliver(packet);
 	            }
 	            catch (UnauthorizedException e) {
 	                Log.error("Unable to deliver message to backup deliverer", e);
 	            }
       }
}
		});
 }
 
Example 18
Project: g3server   File: IQAuthHandler.java   Source Code and License 6 votes vote down vote up
private IQ passwordReset(String password, IQ packet, String username, Session session)
        throws UnauthorizedException
{
    IQ response;
    // Check if users can change their passwords and a password was specified
    if (!registerHandler.canChangePassword() || password == null || password.length() == 0) {
        throw new UnauthorizedException();
    }
    else {
        try {
            userManager.getUser(username).setPassword(password);
            response = IQ.createResultIQ(packet);
            List<String> params = new ArrayList<String>();
            params.add(username);
            params.add(session.toString());
            Log.info(LocaleUtils.getLocalizedString("admin.password.update", params));
        }
        catch (UserNotFoundException e) {
            throw new UnauthorizedException();
        }
    }
    return response;
}
 
Example 19
Project: Openfire   File: IQListHandler.java   Source Code and License 6 votes vote down vote up
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    IQ reply = IQ.createResultIQ(packet);
    ListRequest listRequest = new ListRequest(packet.getChildElement());
    JID from = packet.getFrom();

    Element listElement = reply.setChildElement("list", NAMESPACE);
    Collection<Conversation> conversations = list(from, listRequest);
    XmppResultSet resultSet = listRequest.getResultSet();

    for (Conversation conversation : conversations) {
        addChatElement(listElement, conversation);
    }

    if (resultSet != null) {
        listElement.add(resultSet.createResultElement());
    }

    return reply;
}
 
Example 20
Project: g3server   File: PacketTransporterImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Delivers the given packet based on packet recipient and sender. The
 * deliverer defers actual routing decisions to other classes.
 * <h2>Warning</h2>
 * Be careful to enforce concurrency DbC of concurrent by synchronizing
 * any accesses to class resources.
 *
 * @param packet The packet to route
 * @throws NullPointerException If the packet is null or the
 *                              packet could not be routed
 */
public void deliver(Packet packet) throws UnauthorizedException, PacketException {
    if (packet == null) {
        throw new NullPointerException();
    }

    if (xmppServer != null && xmppServer.isLocal(packet.getTo())) {
        deliverer.deliver(packet);
    }
    else if (transportHandler != null) {
        transportHandler.process(packet);
    }
    else {
        Log.warn("Could not deliver message: no deliverer available "
                + packet.toString());
    }
}
 
Example 21
Project: g3server   File: ClearspaceManager.java   Source Code and License 6 votes vote down vote up
private void updateClearspaceSharedSecret(String newSecret) {

        try {
            String path = IM_URL_PREFIX + "updateSharedSecret/";

            // Creates the XML with the data
            Document groupDoc = DocumentHelper.createDocument();
            Element rootE = groupDoc.addElement("updateSharedSecret");
            rootE.addElement("newSecret").setText(newSecret);

            executeRequest(POST, path, groupDoc.asXML());
        } catch (UnauthorizedException ue) {
            Log.error("Error updating the password of Clearspace", ue);
        } catch (Exception e) {
            Log.error("Error updating the password of Clearspace", e);
        }

    }
 
Example 22
Project: message-server   File: MmxAppUtil.java   Source Code and License 5 votes vote down vote up
public static String extractUserName(String username) throws UnauthorizedException {
  String result = username.trim().toLowerCase();
  if (username.contains(DOMAIN_DELIMITER)) {
    // Check that the specified domain matches the server's domain
    int index = username.lastIndexOf(DOMAIN_DELIMITER);
    String domain = username.substring(index + 1);
    result = username.substring(0, index);
  }
  return result;
}
 
Example 23
Project: message-server   File: MsgAckIQHandler.java   Source Code and License 5 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
  long start = System.nanoTime();
  try {
    Element element = packet.getChildElement();
    String payload = element.getText();
    MsgAck acknowledgement = GsonData.getGson().fromJson(payload, MsgAck.class);
    String from = acknowledgement.getFrom();
    String to = acknowledgement.getTo();
    String messageId = acknowledgement.getMsgId();

    // Remove the offline message for end-point.
    MMXOfflineStorageUtil.removeMessage(to, messageId);
    // Remove the offline message for user added when there were no active sessions.
    MMXOfflineStorageUtil.removeMessage(packet.getFrom().toBareJID(), messageId);

    String appId = JIDUtil.getAppId(to);
    String deviceId = JIDUtil.getResource(to);
    MessageDAO messageDAO = getMessageDAO();
    int count = messageDAO.messageDelivered(appId, deviceId, messageId);
    if (count == 0) {
      LOGGER.warn(String.format("No message updated for appId:%s deviceId:%s messageId:%s", appId, deviceId, messageId));
    }
  } catch (Throwable t) {
    LOGGER.warn("Throwable in handleIQ", t);
  }
  /**
   * based on discussion with login2 we are returning 200 even if an exception is encountered when processing
   * these ack. The reason is the client can't deal with an error response.
   */
  MMXStatus response = new MMXStatus();
  response.setCode(MsgAckOperationStatusCode.DELIVERY_ACK_PROCESSED.getCode());
  IQ result = IQUtils.createResultIQ(packet, response.toJson());
  long end = System.nanoTime();
  long delta = end - start;
  String template = "Processed msgack in [%d] milliseconds";
  LOGGER.info(String.format(template, TimeUnit.MILLISECONDS.convert(delta, TimeUnit.NANOSECONDS)));
  return result;
}
 
Example 24
Project: message-server   File: MMXUserHandler.java   Source Code and License 5 votes vote down vote up
IQ handleUpdateUser(IQ packet, JID from, String appId, String payload)
    throws UnauthorizedException {
  UserInfo request = UserInfo.fromJson(payload);
  String userName = from.getNode();
  
  try {
    UserManager userManager = XMPPServer.getInstance().getUserManager();
    User user = userManager.getUser(userName);
    if (user == null) {
      throw new UserNotFoundException();
    }
    if (request.getEmail() != null) {
      user.setEmail(request.getEmail());
    }
    if (request.getDisplayName() != null) {
      user.setName(request.getDisplayName());
    }
  } catch (UserNotFoundException e) {
    return IQUtils.createErrorIQ(packet,
          UserOperationStatusCode.USER_NOT_FOUND.getMessage(),
          UserOperationStatusCode.USER_NOT_FOUND.getCode());
  }

  MMXStatus userResp = new MMXStatus();
  userResp.setCode(UserOperationStatusCode.USER_UPDATED.getCode());
  userResp.setMessage(UserOperationStatusCode.USER_UPDATED.getMessage());
  IQ response = IQUtils.createResultIQ(packet, userResp.toJson());
  return response;
}
 
Example 25
Project: message-server   File: MMXUserHandler.java   Source Code and License 5 votes vote down vote up
IQ handleSearchUser(IQ packet, JID from, String appId, String payload)
                              throws UnauthorizedException {
  UserQuery.SearchRequest rqt = UserQuery.SearchRequest.fromJson(payload);
  IQ validationError = validateUserSearchRequest(packet, rqt);
  if (validationError != null) {
    return validationError;
  }

  UserDAO userDAO = new UserDAOImpl(getConnectionProvider());
  AppDAO appDAO = new AppDAOImpl(getConnectionProvider());
  // get the server user for this app
  String serverUserId = appDAO.getAppForAppKey(appId).getServerUserId();
  String serverUserIdWithoutAppId = Helper.removeSuffix(serverUserId, JIDUtil.APP_ID_DELIMITER);

  int offset = rqt.getOffset();
  int limit = rqt.getLimit();
  UserQuery.Response response = new UserQuery.Response();

  PaginationInfo paginationInfo = PaginationInfo.build(limit, offset);

  UserQueryBuilder builder = new UserQueryBuilder();
  QueryBuilderResult queryBuilderResult = builder.buildQuery(rqt, appId, paginationInfo);

  SearchResult<UserEntity> searchResult = userDAO.getUsersWithPagination(queryBuilderResult, paginationInfo);

  userDAO.getUsers(queryBuilderResult);
  List<UserInfo> userList = new ArrayList<UserInfo>(searchResult.getResults().size());

  UserEntityPostProcessor processor = new UserEntityPostProcessor();
  for (UserEntity ue : searchResult.getResults()) {
    // Strip the app ID and not to filter out server user and anonymous user.
    processor.postProcess(ue);
    UserInfo user = UserBuilder.build(ue);
    userList.add(user);
  }
  response.setUsers(userList);
  response.setTotalCount(searchResult.getTotal());
  return IQUtils.createResultIQ(packet, response.toJson());
}
 
Example 26
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAddingUserWithNonExistingApp() throws UnauthorizedException {
  UserCreate request = new UserCreate();
  request.setDisplayName("Tommy");
  request.setApiKey("appnotexisting");
  request.setAppId(sAppID);
  request.setUserId("tom");
  request.setEmail("[email protected]");

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, "create");
  element.setText(request.toJson());

  IQ userCreateIQ = new IQ();
  userCreateIQ.setChildElement(element);
  userCreateIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleCreateUser(userCreateIQ, element.getText());

  assertNotNull(response);

  IQ.Type type = response.getType();
  assertEquals("Non matching type", IQ.Type.error, type);

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  MMXStatus status = MMXStatus.fromJson(payload);

  int code = status.getCode();
  String message = status.getMessage();

  assertEquals("Non matching message", MMXUserHandler.UserOperationStatusCode.INVALID_API_KEY.getMessage(), message);

}
 
Example 27
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAddingExistingUser() throws UnauthorizedException {
  UserCreate request = new UserCreate();
  request.setDisplayName("Tommy");
  request.setApiKey("3171f18a-9fcc-4e84-8cb9-aad6ea7bf017");
  request.setAppId(sAppID);
  request.setUserId("tom");
  request.setEmail("[email protected]");
  request.setPriKey("guestsecretcode");

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, "create");
  element.setText(request.toJson());

  IQ userCreateIQ = new IQ();
  userCreateIQ.setChildElement(element);
  userCreateIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleCreateUser(userCreateIQ, element.getText());

  assertNotNull(response);
  assertNotNull(response);

  IQ.Type type = response.getType();
  assertEquals("Non matching type", IQ.Type.error, type);

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  MMXStatus status = MMXStatus.fromJson(payload);

  String message = status.getMessage();

  assertEquals("Non matching message", MMXUserHandler.UserOperationStatusCode.INVALID_USER_ID_TAKEN.getMessage(), message);
}
 
Example 28
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAddingUserWithVeryLongUserId() throws UnauthorizedException {
  UserCreate request = new UserCreate();
  request.setDisplayName("Tommy");
  request.setApiKey("3171f18a-9fcc-4e84-8cb9-aad6ea7bf017");
  request.setAppId(sAppID);
  request.setUserId("SuperLongAndVeryAmazingIsThisUsersUserNameButIWantItLongSoThatIt");
  request.setEmail("[email protected]");
  request.setPriKey("guestsecretcode");

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, "create");
  element.setText(request.toJson());

  IQ userCreateIQ = new IQ();
  userCreateIQ.setChildElement(element);
  userCreateIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleCreateUser(userCreateIQ, element.getText());

  assertNotNull(response);
  assertNotNull(response);

  IQ.Type type = response.getType();
  assertEquals("Non matching type", IQ.Type.error, type);

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  MMXStatus status = MMXStatus.fromJson(payload);

  String message = status.getMessage();

  assertEquals("Non matching message", MMXUserHandler.UserOperationStatusCode.INVALID_USER_ID_TOO_LONG.getMessage(), message);
}
 
Example 29
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 5 votes vote down vote up
/**
 * Running this test causes Openfire to spit out a message about home directory not
 * being configured. Hence disabling it for now.
 * @throws UnauthorizedException
 */
@Ignore
@Test
public void testCreatingAValidUser() throws UnauthorizedException {
  UserCreate request = new UserCreate();
  request.setDisplayName("Tommy");
  request.setApiKey("app1");
  request.setAppId(sAppID);
  request.setUserId("login3");
  request.setEmail("[email protected]");

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, "create");
  element.setText(request.toJson());

  IQ userCreateIQ = new IQ();
  userCreateIQ.setChildElement(element);
  userCreateIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleCreateUser(userCreateIQ, element.getText());

  assertNotNull(response);
  assertNotNull(response);

  IQ.Type type = response.getType();
  assertEquals("Non matching type", IQ.Type.result, type);

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  MMXStatus status = MMXStatus.fromJson(payload);

  String message = status.getMessage();

  assertEquals("Non matching message", MMXUserHandler.UserOperationStatusCode.USER_CREATED.getMessage(), message);
}
 
Example 30
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 5 votes vote down vote up
@Ignore
//@Test
public void testDeletingAValidUser() throws UnauthorizedException {
  UserCreate request = new UserCreate();
  request.setDisplayName("Tommy");
  request.setApiKey("app1");
  request.setAppId(sAppID);
  request.setUserId("login3");
  request.setEmail("[email protected]");

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, Constants.UserCommand.delete.name());
  element.setText(request.toJson());

  IQ userCreateIQ = new IQ();
  JID from = new JID("login3%[email protected]",true);
  userCreateIQ.setFrom(from);
  userCreateIQ.setChildElement(element);
  userCreateIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleDeleteUser(userCreateIQ, from, "i0sqlunda4q", element.getText());

  assertNotNull(response);
  assertNotNull(response);

  IQ.Type type = response.getType();
  assertEquals("Non matching type", IQ.Type.result, type);

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  MMXStatus status = MMXStatus.fromJson(payload);

  String message = status.getMessage();

  assertEquals("Non matching message", MMXUserHandler.UserOperationStatusCode.USER_DELETED.getMessage(), message);
}
 
Example 31
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAddingAnonymousUser() throws UnauthorizedException {
  UserCreate request = new UserCreate();
  request.setDisplayName("AnonUser1");
  request.setApiKey("3171f18a-9fcc-4e84-8cb9-aad6ea7bf017");
  request.setAppId(sAppID);
  request.setUserId("deviceid-1");
  request.setEmail("unknown");
  request.setCreateMode(UserCreateMode.GUEST);
  request.setPriKey("guestsecretcode");

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, "create");
  element.setText(request.toJson());

  IQ userCreateIQ = new IQ();
  userCreateIQ.setChildElement(element);
  userCreateIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleCreateUser(userCreateIQ, element.getText());

  assertNotNull(response);

  IQ.Type type = response.getType();

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  MMXStatus status = MMXStatus.fromJson(payload);

  int code = status.getCode();
  String message = status.getMessage();

  assertTrue(message.length() > 0);
  assertEquals(UserOperationStatusCode.USER_CREATED.getCode(), code);
}
 
Example 32
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUpgradeToRealUser() throws UnauthorizedException {
  UserCreate request = new UserCreate();
  request.setDisplayName("RealUser1");
  request.setApiKey("3171f18a-9fcc-4e84-8cb9-aad6ea7bf017");
  request.setAppId(sAppID);
  request.setUserId("RealUser1");
  request.setEmail("[email protected]");
  request.setCreateMode(UserCreateMode.UPGRADE_USER);
  request.setPriKey("guestsecretcode");

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, "create");
  element.setText(request.toJson());

  IQ userCreateIQ = new IQ();
  JID from = new JID("login3%[email protected]",true);
  userCreateIQ.setFrom(from);
  userCreateIQ.setChildElement(element);
  userCreateIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleCreateUser(userCreateIQ, element.getText());

  assertNotNull(response);

  IQ.Type type = response.getType();

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  MMXStatus status = MMXStatus.fromJson(payload);

  int code = status.getCode();
  String message = status.getMessage();

  assertTrue(message.length() > 0);
  assertEquals(UserOperationStatusCode.USER_CREATED.getCode(), code);
}
 
Example 33
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testQueryUsers1() throws UnauthorizedException {

  List<MMXAttribute<UserQuery.Type>> clist = new ArrayList<MMXAttribute<UserQuery.Type>>(4);
  {
    MMXAttribute<UserQuery.Type> c = new MMXAttribute<UserQuery.Type>(UserQuery.Type.displayName, "login3");
    clist.add(c);
  }
  UserQuery.BulkSearchRequest query = new UserQuery.BulkSearchRequest(clist, null);

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, Constants.UserCommand.query.name());
  element.setText(query.toJson());

  IQ queryIQ = new IQ();
  queryIQ.setFrom(sFrom);
  queryIQ.setChildElement(element);
  queryIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleQueryUser(queryIQ, sFrom, sAppID, element.getText());

  assertNotNull(response);

  IQ.Type type = response.getType();
  assertEquals("Non matching type", IQ.Type.result, type);

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  UserQuery.Response responseList = UserQuery.Response.fromJson(payload);

  List<UserInfo> userList = responseList.getUsers();

  assertTrue("User list is empty", !userList.isEmpty());

}
 
Example 34
Project: openfire   File: LocalMUCUser.java   Source Code and License 5 votes vote down vote up
public void process(Packet packet) throws UnauthorizedException, PacketException {
    if (packet instanceof IQ) {
        process((IQ)packet);
    }
    else if (packet instanceof Message) {
        process((Message)packet);
    }
    else if (packet instanceof Presence) {
        process((Presence)packet);
    }
}
 
Example 35
Project: Openfire   File: SessionManager.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new <tt>ClientSession</tt> with the specified streamID.
 *
 * @param connection the connection to create the session from.
 * @param id the streamID to use for the new session.
 * @return a newly created session.
 */
public HttpSession createClientHttpSession(long rid, InetAddress address, StreamID id, HttpConnection connection, Locale language)
        throws UnauthorizedException {
    if (serverName == null) {
        throw new UnauthorizedException("Server not initialized");
    }
    PacketDeliverer backupDeliverer = server.getPacketDeliverer();
    HttpSession session = new HttpSession(backupDeliverer, serverName, address, id, rid, connection, language);
    Connection conn = session.getConnection();
    conn.init(session);
    conn.registerCloseListener(clientSessionListener, session);
    localSessionManager.getPreAuthenticatedSessions().put(session.getAddress().getResource(), session);
    connectionsCounter.incrementAndGet();
    return session;
}
 
Example 36
Project: openfire   File: IQPrefHandler.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public IQ handleIQ(IQ packet) throws UnauthorizedException
{
    IQ reply = IQ.createResultIQ(packet);
    Element prefRequest = packet.getChildElement();

    System.err.println("Received pref message from " + packet.getFrom());

    if (prefRequest.element("default") != null)
    {
        Element defaultItem = prefRequest.element("default");

        // User requests to set default modes
        defaultItem.attribute("save"); // body, false, message, stream
        defaultItem.attribute("otr");
        defaultItem.attribute("expire");
    }

    for (Element item : (List<Element>) prefRequest.elements("item"))
    {
        // User requests to set modes for a contact
        item.attribute("jid");
        item.attribute("save"); // body, false, message, stream
        item.attribute("otr");
        item.attribute("expire");
    }

    for (Element method : (List<Element>) prefRequest.elements("method"))
    {
        // User requests to set archiving method preferences
        method.attribute("type");
        method.attribute("use");
    }

    return reply;
}
 
Example 37
Project: Openfire   File: LocalClientSession.java   Source Code and License 5 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException {
    if (conn != null) {
        conn.deliver(packet);
    }
    streamManager.sentStanza(packet);
}
 
Example 38
Project: openfire   File: FileTransferProxy.java   Source Code and License 5 votes vote down vote up
public void process(Packet packet) throws UnauthorizedException, PacketException {
    // Check if the packet is a disco request or a packet with namespace iq:register
    if (packet instanceof IQ) {
        if (handleIQ((IQ) packet)) {
            // Do nothing
        }
        else {
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setChildElement(((IQ) packet).getChildElement().createCopy());
            reply.setError(PacketError.Condition.feature_not_implemented);
            router.route(reply);
        }
    }
}
 
Example 39
Project: openfire   File: RoutingTableImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Routes packets that are sent to other XMPP domains than the local XMPP
 * domain.
 * 
 * @param jid
 *            the recipient of the packet to route.
 * @param packet
 *            the packet to route.
 * @throws PacketException
 *             thrown if the packet is malformed (results in the sender's
 *             session being shutdown).
 * @return <tt>true</tt> if the packet was routed successfully,
 *         <tt>false</tt> otherwise.
 */
private boolean routeToRemoteDomain(JID jid, Packet packet,
		boolean routed) {
	byte[] nodeID = serversCache.get(jid.getDomain());
	if (nodeID != null) {
	    if (server.getNodeID().equals(nodeID)) {
	        // This is a route to a remote server connected from this node
	        try {
	            localRoutingTable.getRoute(jid.getDomain()).process(packet);
	            routed = true;
	        } catch (UnauthorizedException e) {
	            Log.error("Unable to route packet " + packet.toXML(), e);
	        }
	    }
	    else {
	        // This is a route to a remote server connected from other node
	        if (remotePacketRouter != null) {
	            routed = remotePacketRouter.routePacket(nodeID, jid, packet);
	        }
	    }
	}
	else {
	    // Return a promise of a remote session. This object will queue packets pending
	    // to be sent to remote servers
	    OutgoingSessionPromise.getInstance().process(packet);
	    routed = true;
	}
	return routed;
}
 
Example 40
Project: Openfire   File: FileTransferProxy.java   Source Code and License 5 votes vote down vote up
@Override
public void process(Packet packet) throws UnauthorizedException, PacketException {
    // Check if the packet is a disco request or a packet with namespace iq:register
    if (packet instanceof IQ) {
        if (handleIQ((IQ) packet)) {
            // Do nothing
        }
        else {
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setChildElement(((IQ) packet).getChildElement().createCopy());
            reply.setError(PacketError.Condition.feature_not_implemented);
            router.route(reply);
        }
    }
}
 
Example 41
Project: openfire   File: ServerSocketReader.java   Source Code and License 5 votes vote down vote up
@Override
boolean createSession(String namespace) throws UnauthorizedException, XmlPullParserException,
           IOException {
       if ("jabber:server".equals(namespace)) {
           // The connected client is a server so create an IncomingServerSession
           session = LocalIncomingServerSession.createSession(serverName, reader, connection);
           return true;
       }
       return false;
   }
 
Example 42
Project: Openfire   File: SocketPacketWriteHandler.java   Source Code and License 5 votes vote down vote up
@Override
 public void process(Packet packet) throws UnauthorizedException, PacketException {
    try {
        JID recipient = packet.getTo();
        // Check if the target domain belongs to a remote server or a component
        if (server.matchesComponent(recipient) || server.isRemote(recipient)) {
            routingTable.routePacket(recipient, packet, false);
        }
        // The target domain belongs to the local server
        else if (recipient == null || (recipient.getNode() == null && recipient.getResource() == null)) {
            // no TO was found so send back the packet to the sender
            routingTable.routePacket(packet.getFrom(), packet, false);
        }
        else if (recipient.getResource() != null || !(packet instanceof Presence)) {
            // JID is of the form <[email protected]/resource>
            routingTable.routePacket(recipient, packet, false);
        }
        else {
            // JID is of the form <[email protected]>
            for (JID route : routingTable.getRoutes(recipient, null)) {
                routingTable.routePacket(route, packet, false);
            }
        }
    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error.deliver") + "\n" + packet.toString(), e);
    }
}
 
Example 43
Project: g3server   File: IQPrivateHandler.java   Source Code and License 5 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
       IQ replyPacket;
       Element child = packet.getChildElement();
       Element dataElement = (Element) child.elementIterator().next();

       if (dataElement != null) {
           if (IQ.Type.get.equals(packet.getType())) {
               replyPacket = IQ.createResultIQ(packet);
               Element dataStored = privateStorage.get(packet.getFrom().getNode(), dataElement);
               dataStored.setParent(null);

               child.remove(dataElement);
               child.setParent(null);
               replyPacket.setChildElement(child);
               child.add(dataStored);
           }
           else {
               privateStorage.add(packet.getFrom().getNode(), dataElement);
               replyPacket = IQ.createResultIQ(packet);
           }
       }
       else {
           replyPacket = IQ.createResultIQ(packet);
           replyPacket.setChildElement("query", "jabber:iq:private");
       }
       return replyPacket;
   }
 
Example 44
Project: openfire   File: CrowdAuthProvider.java   Source Code and License 5 votes vote down vote up
/**
    * Returns if the username and password are valid; otherwise this
    * method throws an UnauthorizedException.<p>
    *
    * If {@link #isPlainSupported()} returns false, this method should
    * throw an UnsupportedOperationException.
    *
    * @param username the username or full JID.
    * @param password the password
    * @throws UnauthorizedException if the username and password do
    *      not match any existing user.
    * @throws ConnectionException it there is a problem connecting to user and group sytem
    * @throws InternalUnauthenticatedException if there is a problem authentication Openfire itself into the user and group system
    */
public void authenticate(String username, String password) throws UnauthorizedException, ConnectionException, InternalUnauthenticatedException {
	if (manager == null) {
		throw new ConnectionException("Unable to connect to Crowd");
	}

       if (username == null || password == null || "".equals(password.trim())) {
           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();
           }
       }

       try {
		manager.authenticate(username, password);
	} catch (RemoteException re) {
		throw new UnauthorizedException();
	}
}
 
Example 45
Project: g3server   File: ComponentStanzaHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected void processPresence(Presence packet) throws UnauthorizedException {
       if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
           // Session is not authenticated so return error
           Presence reply = new Presence();
           reply.setID(packet.getID());
           reply.setTo(packet.getFrom());
           reply.setFrom(packet.getTo());
           reply.setError(PacketError.Condition.not_authorized);
           session.process(reply);
           return;
       }
       super.processPresence(packet);
   }
 
Example 46
Project: Openfire   File: ComponentStanzaHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected void processMessage(Message packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        Message reply = new Message();
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    super.processMessage(packet);
}
 
Example 47
Project: g3server   File: MediaProxyService.java   Source Code and License 5 votes vote down vote up
public void process(Packet packet) throws UnauthorizedException, PacketException {
    // Check if user is allowed to send packet to this service
    if (packet instanceof IQ) {
        // Handle disco packets
        IQ iq = (IQ) packet;
        // Ignore IQs of type ERROR or RESULT
        if (IQ.Type.error == iq.getType() || IQ.Type.result == iq.getType()) {
            return;
        }
        processIQ(iq);
    }
}
 
Example 48
Project: openfire   File: SessionManager.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a session for a remote server. The session should be created only after the
 * remote server has been authenticated either using "server dialback" or SASL.
 *
 * @param conn the connection to the remote server.
 * @param id the stream ID used in the stream element when authenticating the server.
 * @return the newly created {@link IncomingServerSession}.
 * @throws UnauthorizedException if the local server has not been initialized yet.
 */
public LocalIncomingServerSession createIncomingServerSession(Connection conn, StreamID id)
        throws UnauthorizedException {
    if (serverName == null) {
        throw new UnauthorizedException("Server not initialized");
    }
    LocalIncomingServerSession session = new LocalIncomingServerSession(serverName, conn, id);
    conn.init(session);
    // Register to receive close notification on this session so we can
    // remove its route from the sessions set
    conn.registerCloseListener(incomingServerListener, session);

    return session;
}
 
Example 49
Project: g3server   File: RemoteMUCUser.java   Source Code and License 5 votes vote down vote up
public void process(Packet packet) throws UnauthorizedException, PacketException {
    if (packet instanceof IQ) {
        throw new UnsupportedOperationException("Cannot process IQ packets of remote users: " + packet);
    }
    else if (packet instanceof Message) {
        throw new UnsupportedOperationException("Cannot process Message packets of remote users: " + packet);
    }
    else if (packet instanceof Presence) {
        process((Presence)packet);
    }
}
 
Example 50
Project: openfire   File: HttpSessionManager.java   Source Code and License 5 votes vote down vote up
private HttpSession createSession(long rid, InetAddress address, HttpConnection connection) throws UnauthorizedException {
    // Create a ClientSession for this user.
    StreamID streamID = SessionManager.getInstance().nextStreamID();
    // Send to the server that a new client session has been created
    HttpSession session = sessionManager.createClientHttpSession(rid, address, streamID, connection);
    // Register that the new session is associated with the specified stream ID
    sessionMap.put(streamID.getID(), session);
    session.addSessionCloseListener(sessionListener);
    return session;
}
 
Example 51
Project: g3server   File: SessionManager.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a session for a remote server. The session should be created only after the
 * remote server has been authenticated either using "server dialback" or SASL.
 *
 * @param conn the connection to the remote server.
 * @param id the stream ID used in the stream element when authenticating the server.
 * @return the newly created {@link IncomingServerSession}.
 * @throws UnauthorizedException if the local server has not been initialized yet.
 */
public LocalIncomingServerSession createIncomingServerSession(Connection conn, StreamID id)
        throws UnauthorizedException {
    if (serverName == null) {
        throw new UnauthorizedException("Server not initialized");
    }
    LocalIncomingServerSession session = new LocalIncomingServerSession(serverName, conn, id);
    conn.init(session);
    // Register to receive close notification on this session so we can
    // remove its route from the sessions set
    conn.registerCloseListener(incomingServerListener, session);

    return session;
}
 
Example 52
Project: g3server   File: HttpSessionManager.java   Source Code and License 5 votes vote down vote up
private HttpSession createSession(long rid, InetAddress address, HttpConnection connection) throws UnauthorizedException {
    // Create a ClientSession for this user.
    StreamID streamID = SessionManager.getInstance().nextStreamID();
    // Send to the server that a new client session has been created
    HttpSession session = sessionManager.createClientHttpSession(rid, address, streamID, connection);
    // Register that the new session is associated with the specified stream ID
    sessionMap.put(streamID.getID(), session);
    session.addSessionCloseListener(sessionListener);
    return session;
}
 
Example 53
Project: g3server   File: ServerSocketReader.java   Source Code and License 5 votes vote down vote up
@Override
boolean createSession(String namespace) throws UnauthorizedException, XmlPullParserException,
           IOException {
       if ("jabber:server".equals(namespace)) {
           // The connected client is a server so create an IncomingServerSession
           session = LocalIncomingServerSession.createSession(serverName, reader, connection);
           return true;
       }
       return false;
   }
 
Example 54
Project: message-server   File: MessageStateHandler.java   Source Code and License 4 votes vote down vote up
@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
  JID fromJID = iq.getFrom();
  String appId = JIDUtil.getAppId(fromJID);
  //read the command
  Element element = iq.getChildElement();
  String payload = element.getText();
  String commandId = element.attributeValue(Constants.MMX_ATTR_COMMAND);

  if (commandId == null || commandId.isEmpty() || commandId.trim().isEmpty()) {
    return IQUtils.createErrorIQ(iq,
        MessageStatusCode.INVALID_COMMAND.getMessage(),
        MessageStatusCode.INVALID_COMMAND.getCode());
  }

  Constants.MessageCommand command = null;
  try {
    command = Constants.MessageCommand.valueOf(commandId);
  } catch (IllegalArgumentException e) {
    LOGGER.info("Invalid device command string:" + commandId, e);
  }
  if (command == null) {
    return IQUtils.createErrorIQ(iq,
        MessageStatusCode.INVALID_COMMAND.getMessage(),
        MessageStatusCode.INVALID_COMMAND.getCode());
  }

  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Processing command:" + command.toString());
  }

  switch (command) {
  case query:
    return processMessageQuery(iq, appId, payload);
  case getTags:
    return processGetTags(iq, appId, payload);
  case setTags:
    return processSetTags(iq, appId, payload);
  case addTags:
    return processAddTags(iq, appId, payload);
  case removeTags:
    return processRemoveTags(iq, appId, payload);
  case getEvents:
    return processGetEvents(iq, appId, payload);
  case setEvents:
    return processSetEvents(iq, appId, payload);
  case addEvents:
    return processAddEvents(iq, appId, payload);
  case removeEvents:
    return processRemoveEvents(iq, appId, payload);
  default:
    LOGGER.info("Unknown message command");
    return IQUtils.createErrorIQ(iq,
        MessageStatusCode.INVALID_COMMAND.getMessage(),
        MessageStatusCode.INVALID_COMMAND.getCode());
  }
}
 
Example 55
Project: message-server   File: MMXUserHandler.java   Source Code and License 4 votes vote down vote up
IQ handleCreateUser(IQ packet, String payload) throws UnauthorizedException {
  UserCreate userRqt = UserCreate.fromJson(payload);
  AppDAO appDAO = new AppDAOImpl(getConnectionProvider());

  IQ validationError = validateUserCreateRequest(packet, userRqt, appDAO);
  if (validationError != null) {
    return validationError;
  }
  String displayName = userRqt.getDisplayName();
  String userId = userRqt.getUserId();
  String apiKey = userRqt.getApiKey();
  AppEntity appEntity = appDAO.getAppUsingAPIKey(apiKey);

  UserCreateMode createMode = userRqt.getCreateMode();

  String userPassword = userRqt.getPassword();
  if (userPassword == null && UserCreateMode.GUEST == createMode) {
    // create the password for guess access
    userPassword = AppHelper.generateRandomPositiveKey();
  }
  // The userID must be escaped first.
  String userName = JIDUtil.makeNode(userId, appEntity.getAppId());
  String email = userRqt.getEmail();

  Map<String, String> extras = userRqt.getExtras();
  if (extras == null) {
    extras = new HashMap<String, String>();
  }
  // "anonymous" users get marked as "guest" in the creation mode.
  if (UserCreateMode.GUEST == createMode) {
    extras.put(Constants.MMX_PROP_NAME_USER_GUEST_MODE, Constants.MMX_PROP_VALUE_USER_GUEST_TRUE);
  }

  MMXUserManager userManager = getUserManager();
  User newUser = userManager.createUser(userName, userPassword, displayName, email, extras);

  if (UserCreateMode.UPGRADE_USER == createMode) { // mark the current user to remove it
    userManager.markRemoveCurrentGuestUser(packet.getFrom().toBareJID());
  }
  if (newUser != null) {
    // Add the tags (if any) for the new user.
    List<String> tags = userRqt.getTags();
    if (tags != null) {
      TagDAO tagDao = DBUtil.getTagDAO();
      for (String tag : tags) {
        if (!tag.isEmpty()) {
          try {
            tagDao.createUsernameTag(tag, appEntity.getAppId(), userName);
          } catch (Exception e) {
            LOGGER.error("Unable to set a tag to "+userName, e);
          }
        }
      }
    }
    
    LOGGER.info("Created a new user with username:" + userName);
    MMXStatus userResp = new MMXStatus();
    // return the generated password for guest mode
    if (UserCreateMode.GUEST == createMode) {
      userResp.setCode(UserOperationStatusCode.GUEST_USER_CREATED.getCode());
      userResp.setMessage(userPassword);
    } else {
      userResp.setCode(UserOperationStatusCode.USER_CREATED.getCode());
      userResp.setMessage(UserOperationStatusCode.USER_CREATED.getMessage());
    }
    IQ response = IQUtils.createResultIQ(packet, userResp.toJson());
    return response;
  } else {
    return IQUtils.createErrorIQ(packet, UserOperationStatusCode.USER_CREATION_FAILED.getMessage(),
        UserOperationStatusCode.USER_CREATION_FAILED.getCode());
  }
}
 
Example 56
Project: message-server   File: AppHandler.java   Source Code and License 4 votes vote down vote up
/**
 * <pre>
 *  <iq type="set" from="[email protected]/resource" ...>
 *    <reg xlms="com.magnet:mmx:app" command="read" type="application/json" ...>
 *    {
 *      "appKey": "...",
 *    }
 *    </reg>
 *  </iq>
 *
 *  <iq type="result"...>
 *    <reg xlms="com.magnet:mmx:app" ctype="application/json" ...>
 *    {
 *      "appName": "...",
 *      "apiKey": "...",
 *      "serverUser": "...",
 *      "serverKey": "...",
 *      "gcm":
 *      {
 *        "googleApiKey" : "...",
 *        "googleProjectId" : "..."
 *      },
 *      "apns":
 *      {
 *        "pwd" : "..."
 *      }
 *    }
 *    </reg>
 *  </iq>
 * </pre>
 */
private IQ handleReadApps(IQ iq) throws UnauthorizedException {
  Element element = iq.getChildElement();

  JID from = iq.getFrom();
  if (Helper.isAppMgmtPermitted(from)) {
    throw new UnauthorizedException("No admin privilege to register application");
  }

  String payload = element.getText();
  AppRead.Request appRqt = AppRead.Request.fromJson(payload);

  AppRead.Response appResp = null;
  try {
    appResp = mmxAppManager.getApp(appRqt.getAppId());
  } catch (AppDoesntExistException e) {
    return IQUtils.createErrorIQ(iq, e.getMessage(), 1);
  }

  // TODO: How do we set the serverKey?

  IQ response = IQUtils.createResultIQ(iq, appResp.toJson());

  return response;
}
 
Example 57
Project: message-server   File: AppHandler.java   Source Code and License 4 votes vote down vote up
/**
 * <pre>
 *  <iq type="set" from="[email protected]/resource" ...>
 *    <reg xlms="com.magnet:mmx:app" command="update" type="application/json" ...>
 *    {
 *      "appKey": "...",
 *      "appName": "...",
 *      "gcm":
 *      {
 *        "googleApiKey" : "...",
 *        "googleProjectId" : "..."
 *      },
 *      "apns":
 *      {
 *        "cert" : "...",
 *        "pwd" : "..."
 *      }
 *    }
 *    </reg>
 *  </iq>
 *
 *  <iq type="result"...>
 *    <reg xlms="com.magnet:mmx:app" ctype="application/json" ... />
 *  </iq>
 * </pre>
 */
private IQ handleUpdateApp(IQ iq) throws UnauthorizedException {
  Element element = iq.getChildElement();

  JID from = iq.getFrom();
  if (!Helper.isAppMgmtPermitted(from)) {
    throw new UnauthorizedException("No admin privilege to register application");
  }

  String payload = element.getText();
  AppUpdate appUpdateRqt = AppUpdate.fromJson(payload);

  String apnsCertInBase64 = appUpdateRqt.getApns().getCert();
  /*String apnsCertPath = null;
if (appUpdateRqt.getApns() != null && apnsCertInBase64 != null) {
	// Save APNS cert to file system.
	try {
		apnsCertPath = databaseHandler.getApnsCertPath(appUpdateRqt.getAppId());
	} catch (AppDoesntExistException e) {
		return IQUtils.createError(iq, Constants.MMX_APP_REG,
          Constants.MMX_NS_APP, e.getMessage(), 1);
	}
	if (apnsCertPath == null) {
		// No APNS cert was stored before. Create one.
		try {
			String userName = databaseHandler.getServerUser(appUpdateRqt.getAppId());
			XMPPServer server = XMPPServer.getInstance();
			User user = server.getUserManager().getUser(userName);
			apnsCertPath = saveAPNSCertForApp(user, apnsCertInBase64);
		} catch (AppDoesntExistException | UserNotFoundException e) {
			return IQUtils.createError(iq, Constants.MMX_APP_REG,
            Constants.MMX_NS_APP, e.getMessage(), 1);
		}
	} else {
		updateAPNSCertForApp(apnsCertPath, apnsCertInBase64);
	}
}*/

  AppRead.Response appReadResp = null;
  MMXStatus appResp = null;
  try {
    mmxAppManager.updateApp(appUpdateRqt.getAppId(), appUpdateRqt.getAppName(),
        appUpdateRqt.getGcm().getGoogleApiKey(), appUpdateRqt.getGcm().getGoogleProjectId(),
        apnsCertInBase64, appUpdateRqt.getApns().getPwd());
  } catch (AppDoesntExistException e) {
    return IQUtils.createErrorIQ(iq, e.getMessage(), StatusCode.NOT_FOUND);
  }

  IQ response = IQUtils.createResultIQ(iq, appResp.toJson());

  return response;
}
 
Example 58
Project: message-server   File: DeviceHandler.java   Source Code and License 4 votes vote down vote up
@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
  LOGGER.info("handleIQ is called");
  AppDAO dao = new AppDAOImpl(new OpenFireDBConnectionProvider());
  JID fromJID = iq.getFrom();
  String appId = JIDUtil.getAppId(fromJID);

  AppEntity appEntity = dao.getAppForAppKey(appId);
  if (appEntity == null) {
    return IQUtils.createErrorIQ(iq,
        DeviceOperationStatusCode.INVALID_APP_ID.getMessage(),
        DeviceOperationStatusCode.INVALID_APP_ID.getCode());
  }
  /*
    retrieve the command that we are processing
   */
  Element element = iq.getChildElement();
  String payload = element.getText();
  String command = element.attributeValue(COMMAND_KEY);
  if (command == null || command.isEmpty() || command.trim().isEmpty()) {
    return IQUtils.createErrorIQ(iq, 
        DeviceOperationStatusCode.INVALID_COMMAND_VALUE.getMessage(),
        DeviceOperationStatusCode.INVALID_COMMAND_VALUE.getCode());
  }

  Constants.DeviceCommand deviceCommand = null;
  try {
    deviceCommand = Constants.DeviceCommand.valueOf(command.toUpperCase());
  } catch (IllegalArgumentException e) {
    LOGGER.info("Invalid device command string:" + command, e);
  }
  if (deviceCommand == null) {
    return IQUtils.createErrorIQ(iq, 
        DeviceOperationStatusCode.INVALID_COMMAND_VALUE.getMessage(),
        DeviceOperationStatusCode.INVALID_COMMAND_VALUE.getCode());
  }

  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Processing command:" + deviceCommand.toString());
  }

  switch (deviceCommand) {
  case REGISTER:
    return processRegistration(iq, fromJID, appEntity, payload);
  case UNREGISTER:
    return processDeRegistration(iq, fromJID, appEntity, payload);
  case QUERY:
    return processQuery(iq, fromJID, appEntity, payload);
  case GETTAGS:
    return processGetTags(iq, fromJID, appEntity, payload);
  case SETTAGS:
    return processSetTags(iq, fromJID, appEntity, payload);
  case ADDTAGS:
    return processAddTags(iq, fromJID, appEntity, payload);
  case REMOVETAGS:
    return processRemoveTags(iq, fromJID, appEntity, payload);
  }
  return null;
}
 
Example 59
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testQueryUsers2() throws UnauthorizedException {

  List<MMXAttribute<UserQuery.Type>> clist = new ArrayList<MMXAttribute<UserQuery.Type>>(4);
  {
    MMXAttribute<UserQuery.Type> c = new MMXAttribute<UserQuery.Type>(
        UserQuery.Type.email, "net.com");
    clist.add(c);
  }
  UserQuery.BulkSearchRequest query = new UserQuery.BulkSearchRequest(
      clist, Integer.valueOf(3));

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, Constants.UserCommand.query.name());
  element.setText(query.toJson());

  IQ queryIQ = new IQ();
  queryIQ.setFrom(sFrom);
  queryIQ.setChildElement(element);
  queryIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleQueryUser(queryIQ, sFrom, sAppID, element.getText());

  assertNotNull(response);

  IQ.Type type = response.getType();
  assertEquals("Non matching type", IQ.Type.result, type);

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  UserQuery.Response responseList = UserQuery.Response.fromJson(payload);

  List<UserInfo> userList = responseList.getUsers();

  assertTrue("User list is empty", !userList.isEmpty());

  int size = userList.size();
  assertEquals("Didn't get matching user list", 3, size);

  int total = responseList.getTotalCount();
  assertEquals("Didn't get matching user list total size", 5, total);
}
 
Example 60
Project: message-server   File: MMXUserHandlerTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testQueryUsers3() throws UnauthorizedException {

  List<MMXAttribute<UserQuery.Type>> clist = new ArrayList<MMXAttribute<UserQuery.Type>>(4);
  {
    MMXAttribute<UserQuery.Type> c = new MMXAttribute<UserQuery.Type>(
        UserQuery.Type.email, "net.com");
    clist.add(c);
  }
  UserQuery.BulkSearchRequest query = new UserQuery.BulkSearchRequest(
      clist, Integer.valueOf(10));

  DocumentFactory factory = new DocumentFactory();
  final Element element = factory.createElement(Constants.MMX, Constants.MMX_NS_USER);
  element.addAttribute(Constants.MMX_ATTR_COMMAND, Constants.UserCommand.query.name());
  element.setText(query.toJson());

  IQ queryIQ = new IQ();
  queryIQ.setFrom(sFrom);
  queryIQ.setChildElement(element);
  queryIQ.setType(IQ.Type.set);

  MMXUserHandler userHandler = new StubMMXUserHandler("stubbed mmx user handler");
  IQ response = userHandler.handleQueryUser(queryIQ, sFrom, sAppID, element.getText());

  assertNotNull(response);

  IQ.Type type = response.getType();
  assertEquals("Non matching type", IQ.Type.result, type);

  String payload = response.getChildElement().getStringValue();
  assertNotNull("Null payload", payload);

  UserQuery.Response responseList = UserQuery.Response.fromJson(payload);

  List<UserInfo> userList = responseList.getUsers();

  assertTrue("User list is empty", !userList.isEmpty());

  int size = userList.size();
  assertEquals("Didn't get matching user list", 5, size);

  int total = responseList.getTotalCount();
  assertEquals("Didn't get matching user list total size", 5, total);
}