/** * Handle message * * @param \Thruway\Message\Message $msg * @return boolean */ public function handlesMessage(Message $msg) { $handledMsgCodes = [Message::MSG_PUBLISHED]; if (in_array($msg->getMsgCode(), $handledMsgCodes)) { return true; } elseif ($msg instanceof ErrorMessage && $msg->getErrorMsgCode() == Message::MSG_PUBLISH) { return true; } else { return false; } }
/** * @param Message $msg * @return mixed */ public function handlesMessage(Message $msg) { $handledMsgCodes = array(Message::MSG_SUBSCRIBED, Message::MSG_UNSUBSCRIBED, Message::MSG_EVENT); if (in_array($msg->getMsgCode(), $handledMsgCodes)) { return true; } elseif ($msg instanceof ErrorMessage && $msg->getErrorMsgCode() == Message::MSG_SUBSCRIBE) { return true; } else { return false; } }
public function deserialize($serializedData) { if (null === ($data = @json_decode($serializedData, true))) { throw new DeserializationException("Error decoding json \"" . $serializedData . "\""); } $msg = Message::createMessageFromArray($data); return $msg; }
public function testPublishBlackWhiteListing() { $publishMessageRawJSON = "[16,12345,{},\"example.topic\"]"; /** @var \Thruway\Message\PublishMessage $publishMessage */ $publishMessage = \Thruway\Message\Message::createMessageFromArray(json_decode($publishMessageRawJSON)); $this->assertInstanceOf('\\Thruway\\Message\\PublishMessage', $publishMessage); $this->assertEquals((object) [], $publishMessage->getOptions()); $this->assertEquals("example.topic", $publishMessage->getTopicName()); }
public function processHello(array $args) { /** @var \Thruway\Message\HelloMessage $helloMessage */ $helloMessage = \Thruway\Message\Message::createMessageFromArray($args[0]); if ($helloMessage->getDetails()->authid == 'authenticate_me') { return ["CHALLENGE", ["challenge_method" => 'extra_auth', "challenge" => '']]; } return ['NOCHALLENGE', (object) ['authid' => 'theauth', '_thruway_authextra' => ['from' => 'hello', 'one' => 1, 'two' => [1, 2]]]]; }
/** * Handles all messages for authentication (Hello and Authenticate) * This is called by the Realm to handle authentication * * @param \Thruway\Realm $realm * @param \Thruway\Session $session * @param \Thruway\Message\Message $msg * @throws \Exception */ public function onAuthenticationMessage(Realm $realm, Session $session, Message $msg) { if ($session->isAuthenticated()) { throw new \Exception("Message sent to authentication manager for already authenticated session."); } // trusted transports do not need any authentication if ($session->getTransport()->isTrusted()) { $authDetails = new AuthenticationDetails(); $authDetails->setAuthMethod('internalClient'); $authDetails->setAuthId('internal'); // set the authid if the hello has one if ($msg instanceof HelloMessage) { $details = $msg->getDetails(); if (isset($details)) { if (isset($details['authid'])) { $authDetails->setAuthId($details['authid']); } } } $authDetails->addAuthRole("authenticated_user"); $authDetails->addAuthRole("admin"); $session->setAuthenticationDetails($authDetails); $session->setAuthenticated(true); $session->sendMessage(new WelcomeMessage($session->getSessionId(), ['authid' => $authDetails->getAuthId(), 'authmethod' => $authDetails->getAuthMethod(), 'authrole' => $authDetails->getAuthRole(), 'authroles' => $authDetails->getAuthRoles()])); return; } if (!$this->readyToAuthenticate()) { $session->abort(new \stdClass(), 'thruway.authenticator.not_ready'); return; } if ($msg instanceof HelloMessage) { if ($session->getAuthenticationDetails() !== null) { // Todo: probably shouldn't be so dramatic here throw new \Exception("Hello message sent to authentication manager when there is already authentication details attached."); } $this->handleHelloMessage($realm, $session, $msg); } else { if ($msg instanceof AuthenticateMessage) { $this->handleAuthenticateMessage($realm, $session, $msg); } else { throw new \Exception("Invalid message type sent to AuthenticationManager."); } } }
/** * Process HelloMessage * * @param array $args * @return array<string|array> */ public function processHello(array $args) { if (!isset($args[0])) { return ["FAILURE"]; } $helloMessage = \Thruway\Message\Message::createMessageFromArray($args[0]); if ($helloMessage instanceof HelloMessage && isset($helloMessage->getDetails()->transport->query_params->token) && $helloMessage->getDetails()->transport->query_params->token === 'sadfsaf') { return ["NOCHALLENGE", ["authid" => "joe"]]; } return ["FAILURE"]; }
/** * @param Message $msg * @return mixed */ public function handlesMessage(Message $msg) { $handledMsgCodes = array(Message::MSG_RESULT); if (in_array($msg->getMsgCode(), $handledMsgCodes)) { return true; } elseif ($msg instanceof ErrorMessage && $msg->getErrorMsgCode() == Message::MSG_CALL) { return true; } else { return false; } }
public function onMessage(TransportInterface $transport, Message $msg) { /** @var $session Session */ $session = $this->sessions[$transport]; // see if the session is in a realm if ($session->getRealm() === null) { // hopefully this is a HelloMessage or we have no place for this message to go if ($msg instanceof HelloMessage) { if (RealmManager::validRealmName($msg->getRealm())) { $realm = $this->realmManager->getRealm($msg->getRealm()); $realm->onMessage($session, $msg); } else { // TODO send bad realm error back and shutdown $session->shutdown(); } } else { $session->shutdown(); } } else { $realm = $session->getRealm(); $realm->onMessage($session, $msg); } }
function xtestPongMessage() { $rawPong = "[261, 12345]"; $pongMsg = Message::createMessageFromRaw($rawPong); $this->assertTrue($pongMsg instanceof PongMessage, "Serialized to PongMessage class"); $this->assertTrue($pongMsg->getRequestId() == 12345, "Request id preserved"); $this->assertEquals(json_encode(json_decode($rawPong)), $pongMsg->getSerializedMessage(), "Serialized version matches"); $rawPong = "[261, 12345, {\"test\": \"good\"}, [67890]]"; $pongMsg = Message::createMessageFromRaw($rawPong); $this->assertTrue($pongMsg instanceof PongMessage, "Serialized to PongMessage class"); /** @var $pongMsg PongMessage */ $this->assertTrue($pongMsg->getRequestId() == 12345, "Request id preserved"); $this->assertTrue($pongMsg->getDetails()['test'] == "good", "Details deserialized correctly"); $this->assertTrue($pongMsg->getEcho()[0] == "67890", "Echo deserialized correctly"); $this->assertEquals(json_encode(json_decode($rawPong)), $pongMsg->getSerializedMessage(), "Serialized version matches"); }
/** * This calls an RPC in the InternalClient object that calls ping from the server * side and returns the result. */ public function xtestServerPing() { $this->_conn->on('open', function (\Thruway\ClientSession $session) { $session->call('com.example.ping', [])->then(function ($res) { $this->_conn->close(); $this->_testResult = \Thruway\Message\Message::createMessageFromRaw(json_encode($res[0])); }, function ($error) { $this->_conn->close(); $this->_error = $error; }); }); $this->_conn->open(); $this->assertNull($this->_error, "Got this error when pinging: {$this->_error}"); $this->assertTrue($this->_testResult instanceof \Thruway\Message\PongMessage); $this->assertEquals("echo content", $this->_testResult->getEcho()[0], "Ping echoed correctly"); }
/** * Get argument for serialization * * @return array */ public function getArgumentsForSerialization() { $a = []; $args = $this->getArguments(); $argsKw = $this->getArgumentsKw(); if ($args !== null && is_array($args) && count($args) > 0) { $a = array_merge($a, [$args]); if ($argsKw !== null && Message::isAssoc($argsKw) && count((array) $argsKw) > 0) { $a = array_merge($a, [$argsKw]); } } else { if ($argsKw !== null && Message::isAssoc($argsKw) && count((array) $argsKw) > 0) { $a = array_merge($a, [[], $argsKw]); } } return $a; }
/** * The arguments given by the server are the actual hello message ($args[0]) * and some session information ($args[1]) * * The session information is an associative array that contains the sessionId and realm * * @param array $args * @return array */ public function processHello(array $args) { $helloMsg = array_shift($args); $sessionInfo = array_shift($args); if (!is_array($helloMsg)) { return ["ERROR"]; } if (!is_object($sessionInfo)) { return ["ERROR"]; } $helloMsg = Message::createMessageFromArray($helloMsg); if (!$helloMsg instanceof HelloMessage || !$sessionInfo || !isset($helloMsg->getDetails()->authid) || !$this->getUserDb() instanceof WampCraUserDbInterface) { return ["ERROR"]; } $authid = $helloMsg->getDetails()->authid; $user = $this->getUserDb()->get($authid); if (!$user) { return ["FAILURE"]; } // create a challenge $nonce = bin2hex(openssl_random_pseudo_bytes(22)); $authRole = "user"; $authMethod = "wampcra"; $authProvider = "userdb"; $now = new \DateTime(); $timeStamp = $now->format($now::ISO8601); if (!isset($sessionInfo->sessionId)) { return ["ERROR"]; } $sessionId = $sessionInfo->sessionId; $challenge = ["authid" => $authid, "authrole" => $authRole, "authprovider" => $authProvider, "authmethod" => $authMethod, "nonce" => $nonce, "timestamp" => $timeStamp, "session" => $sessionId]; $serializedChallenge = json_encode($challenge); $challengeDetails = ["challenge" => $serializedChallenge, "challenge_method" => $this->getMethodName()]; if ($user['salt'] !== null) { // we are using salty password $saltInfo = ["salt" => $user['salt'], "keylen" => 32, "iterations" => 1000]; $challengeDetails = array_merge($challengeDetails, $saltInfo); } return ["CHALLENGE", (object) $challengeDetails]; }
public function handleRouterStart(RouterStartEvent $event) { /** @var Session $session */ $session = null; // create a new transport for the client side to use $clientTransport = new InternalClientTransport(function ($msg) use(&$session) { $session->dispatchMessage(Message::createMessageFromArray(json_decode(json_encode($msg)))); }, $this->loop); // create a new transport for the router side to use $transport = new InternalClientTransport(function ($msg) use($clientTransport) { $this->internalClient->onMessage($clientTransport, Message::createMessageFromArray(json_decode(json_encode($msg)))); }, $this->loop); $transport->setTrusted($this->trusted); $session = $this->router->createNewSession($transport); $this->session = $session; // connect the transport to the Router/Peer $this->router->getEventDispatcher()->dispatch("connection_open", new ConnectionOpenEvent($session)); // open the client side $this->internalClient->onOpen($clientTransport); // internal client shouldn't retry $this->internalClient->setAttemptRetry(false); // tell the internal client to start up $this->internalClient->start(false); }
/** * Handle transport recived message * * @param \Thruway\Transport\TransportInterface $transport * @param \Thruway\Message\Message $msg * @return void */ public function onMessage(TransportInterface $transport, Message $msg) { /* @var $session \Thruway\Session */ $session = $this->sessions[$transport]; // see if the session is in a realm if ($session->getRealm() === null) { if ($msg instanceof AbortMessage) { $session->shutdown(); return; } // hopefully this is a HelloMessage or we have no place for this message to go if ($msg instanceof HelloMessage) { try { $realm = $this->realmManager->getRealm($msg->getRealm()); $realm->onMessage($session, $msg); } catch (\Exception $e) { // TODO: Test this $errorUri = "wamp.error.unknown"; $description = $e->getMessage(); if ($e instanceof InvalidRealmNameException || $e instanceof RealmNotFoundException) { $errorUri = "wamp.error.no_such_realm"; } $session->abort(['description' => $description], $errorUri); } } else { $session->abort(new \stdClass(), "wamp.error.unknown"); } } else { $realm = $session->getRealm(); $realm->onMessage($session, $msg); } }
/** * Returns true if this role handles this message. * Error messages are checked according to the * message the error corresponds to. * * @param \Thruway\Message\Message $msg * @return boolean */ public function handlesMessage(Message $msg) { $handledMsgCodes = [Message::MSG_REGISTERED, Message::MSG_UNREGISTERED, Message::MSG_INVOCATION, Message::MSG_REGISTER]; $codeToCheck = $msg->getMsgCode(); if ($msg instanceof ErrorMessage) { $codeToCheck = $msg->getErrorMsgCode(); } if (in_array($codeToCheck, $handledMsgCodes)) { return true; } else { return false; } }
/** * Set arguments * * @param mixed $argumentsKw */ public function setArgumentsKw($argumentsKw) { $this->argumentsKw = Message::shouldBeDictionary($argumentsKw); }
/** * @param Message $msg * @return bool */ public function handlesMessage(Message $msg) { $handledMsgCodes = array(Message::MSG_CALL, Message::MSG_CANCEL, Message::MSG_REGISTER, Message::MSG_UNREGISTER, Message::MSG_YIELD); if (in_array($msg->getMsgCode(), $handledMsgCodes)) { return true; } elseif ($msg instanceof ErrorMessage && $msg->getErrorMsgCode() == Message::MSG_INVOCATION) { return true; } else { return false; } }
/** * @param Message $msg * @return bool */ public function handlesMessage(Message $msg) { $handledMsgCodes = array(Message::MSG_SUBSCRIBE, Message::MSG_UNSUBSCRIBE, Message::MSG_PUBLISH); if (in_array($msg->getMsgCode(), $handledMsgCodes)) { return true; } else { return false; } }
/** * @expectedException InvalidArgumentException * @throws \Thruway\Message\MessageException */ public function testObjectAsRealmName() { $msg = \Thruway\Message\Message::createMessageFromArray([\Thruway\Message\Message::MSG_HELLO, new stdClass(), new stdClass()]); }
/** * Returns true if this role handles this message. * * @param \Thruway\Message\Message $msg * @return boolean */ public function handlesMessage(Message $msg) { $handledMsgCodes = [Message::MSG_SUBSCRIBED, Message::MSG_UNSUBSCRIBED, Message::MSG_EVENT, Message::MSG_SUBSCRIBE, Message::MSG_UNSUBSCRIBE]; $codeToCheck = $msg->getMsgCode(); if ($msg instanceof ErrorMessage) { $codeToCheck = $msg->getErrorMsgCode(); } if (in_array($codeToCheck, $handledMsgCodes)) { return true; } else { return false; } }
/** * process call * * @param \Thruway\ClientSession $session * @param string $procedureName * @param mixed $arguments * @param mixed $argumentsKw * @param mixed $options * @return \React\Promise\Promise */ public function call(ClientSession $session, $procedureName, $arguments = null, $argumentsKw = null, $options = null) { //This promise gets resolved in Caller::processResult $futureResult = new Deferred(); $requestId = Session::getUniqueId(); $this->callRequests[$requestId] = ["procedure_name" => $procedureName, "future_result" => $futureResult]; if (!(is_array($options) && Message::isAssoc($options))) { if ($options !== null) { Logger::warning($this, "Options don't appear to be the correct type."); } $options = new \stdClass(); } $callMsg = new CallMessage($requestId, $options, $procedureName, $arguments, $argumentsKw); $session->sendMessage($callMsg); return $futureResult->promise(); }
/** * Constructor * * @param \stdClass $details * @param mixed $responseURI */ public function __construct($details, $responseURI) { parent::__construct(); $this->setDetails($details); $this->setResponseURI($responseURI); }