From e7e55d79c5913e8c8dd65a363878bf5dc130cd06 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 11:52:13 -0600 Subject: [PATCH 001/114] Update pair() --- lib/toopher_api.php | 29 ++++++++++++++++++++++------- test/test_toopher_api.php | 28 +++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index caad76b..e1291ee 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -51,14 +51,29 @@ function __construct($key, $secret, $baseUrl = '', $httpAdapter = NULL) $this->httpAdapter = (!is_null($httpAdapter)) ? $httpAdapter : new HTTP_Request2_Adapter_Curl(); } - public function pair($pairingPhrase, $userName, $extras = array()) + public function pair($username, $phrase_or_num = '', $kwargs = array()) { - $params = array( - 'pairing_phrase' => $pairingPhrase, - 'user_name' => $userName - ); - $params = array_merge($params, $extras); - return $this->makePairResponse($this->post('pairings/create', $params)); + $params = array('user_name' => $username); + $params = array_merge($params, $kwargs); + if (!empty($phrase_or_num)) + { + if(preg_match('/\d/', $phrase_or_num, $match)) + { + $url = 'pairings/create/sms'; + $params['phone_number'] = $phrase_or_num; + } + else + { + $url = 'pairings/create'; + $params['pairing_phrase'] = $phrase_or_num; + } + } + else + { + $url = 'pairings/create/qr'; + } + $result = $this->post($url, $params); + return $this->makePairResponse($result); } public function getPairingStatus($pairingId) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index e89e9ff..ad9f228 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -51,13 +51,39 @@ public function testCreatePair(){ $resp->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"user"}}'); $mock->addResponse($resp); $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); - $pairing = $toopher->pair('immediate_pair', 'user'); + $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing['id'] == '1', 'bad pairing id'); $this->assertTrue($pairing['enabled'] == true, 'pairing not enabled'); $this->assertTrue($pairing['userId'] == '1', 'bad user id'); $this->assertTrue($pairing['userName'] == 'user', 'bad user name'); } + public function testCreateSmsPair(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); + $resp->appendBody('{"id":"1", "enabled":true, "user":{"id":"1", "name":"user"}}'); + $mock->addResponse($resp); + $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $pairing = $toopher->pair('user', '555-555-5555'); + $this->assertTrue($pairing['id'] == '1', 'bad pairing id'); + $this->assertTrue($pairing['enabled'] == true, 'pairing not enabled'); + $this->assertTrue($pairing['userId'] == '1', 'bad user id'); + $this->assertTrue($pairing['userName'] == 'user', 'bad user name'); + } + + public function testCreateQrPair(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); + $resp->appendBody('{"id":"1", "enabled":true, "user":{"id":"1", "name":"user"}}'); + $mock->addResponse($resp); + $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $pairing = $toopher->pair('user'); + $this->assertTrue($pairing['id'] == '1', 'bad pairing id'); + $this->assertTrue($pairing['enabled'] == true, 'pairing not enabled'); + $this->assertTrue($pairing['userId'] == '1', 'bad user id'); + $this->assertTrue($pairing['userName'] == 'user', 'bad user name'); + } + public function testGetPairingStatus(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); From 3999c7d2cb814bd4dffbd0dc99153c348b7bcaff Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 12:31:17 -0600 Subject: [PATCH 002/114] Update authenticate() --- composer.json | 3 ++- lib/toopher_api.php | 28 +++++++++++++++++++++------- test/test_toopher_api.php | 8 +++++--- 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/composer.json b/composer.json index e59be01..b496c1f 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,8 @@ }, "require-dev" : { "phpunit/phpunit": "3.7.*", - "satooshi/php-coveralls": "dev-master" + "satooshi/php-coveralls": "dev-master", + "rhumsaa/uuid": ">=2.8" }, "autoload":{ "classmap": ["lib"] diff --git a/lib/toopher_api.php b/lib/toopher_api.php index e1291ee..a335d4a 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -81,18 +81,32 @@ public function getPairingStatus($pairingId) return $this->makePairResponse($this->get('pairings/' . $pairingId)); } - public function authenticate($pairingId, $terminalName, $actionName = '', $extras = array()) + public function authenticate($id_or_username, $terminal, $actionName = '', $kwargs = array()) { - $params = array( - 'pairing_id' => $pairingId, - 'terminal_name' => $terminalName - ); + $url = 'authentication_requests/initiate'; + $uuid_pattern = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; + if(preg_match($uuid_pattern, $id_or_username, $match)) + { + $params = array( + 'pairing_id' => $id_or_username, + 'terminal_name' => $terminal + ); + } + else + { + $params = array( + 'user_name' => $id_or_username, + 'terminal_name_extra' => $terminal + ); + } + if(!empty($actionName)) { $params['action_name'] = $actionName; } - $params = array_merge($params, $extras); - return $this->makeAuthResponse($this->post('authentication_requests/initiate', $params)); + $params = array_merge($params, $kwargs); + $result = $this->post($url, $params); + return $this->makeAuthResponse($result); } public function getAuthenticationStatus($authenticationRequestId) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index ad9f228..cb5d2f1 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -22,6 +22,7 @@ */ require_once("bootstrap.php"); +use Rhumsaa\Uuid\Uuid; class ToopherAPITests extends PHPUnit_Framework_TestCase { @@ -108,14 +109,15 @@ public function testGetPairingStatus(){ } public function testCreateAuthenticationWithNoAction(){ + $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); $mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $mock); - $auth = $toopher->authenticate('1', 'term name'); - $this->assertTrue($auth['id'] == '1', 'wrong auth id'); + $auth = $toopher->authenticate($id, 'term name'); + $this->assertTrue($auth['id'] == $id, 'wrong auth id'); $this->assertTrue($auth['pending'] == false, 'wrong auth pending'); $this->assertTrue($auth['granted'] == true, 'wrong auth granted'); $this->assertTrue($auth['automated'] == true, 'wrong auth automated'); From 66988cf179cdaa994be64a781546a91ae5b230a7 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 12:42:24 -0600 Subject: [PATCH 003/114] Add AdvancedApiUsageFactory, ApiRawRequester, and update get() and post() --- lib/toopher_api.php | 44 ++++++++++++++++++++++++++++----- test/test_toopher_api.php | 51 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 6 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index a335d4a..143e8b5 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -49,6 +49,7 @@ function __construct($key, $secret, $baseUrl = '', $httpAdapter = NULL) $this->oauthConsumer = new HTTP_OAuth_Consumer($key, $secret); $this->baseUrl = (!empty($baseUrl)) ? $baseUrl : 'https://api.toopher.com/v1/'; $this->httpAdapter = (!is_null($httpAdapter)) ? $httpAdapter : new HTTP_Request2_Adapter_Curl(); + $this->advanced = new AdvancedApiUsageFactory($key, $secret, $baseUrl, $httpAdapter); } public function pair($username, $phrase_or_num = '', $kwargs = array()) @@ -72,13 +73,13 @@ public function pair($username, $phrase_or_num = '', $kwargs = array()) { $url = 'pairings/create/qr'; } - $result = $this->post($url, $params); + $result = $this->advanced->raw->post($url, $params); return $this->makePairResponse($result); } public function getPairingStatus($pairingId) { - return $this->makePairResponse($this->get('pairings/' . $pairingId)); + return $this->makePairResponse($this->advanced->raw->get('pairings/' . $pairingId)); } public function authenticate($id_or_username, $terminal, $actionName = '', $kwargs = array()) @@ -105,13 +106,13 @@ public function authenticate($id_or_username, $terminal, $actionName = '', $kwar $params['action_name'] = $actionName; } $params = array_merge($params, $kwargs); - $result = $this->post($url, $params); + $result = $this->advanced->raw->post($url, $params); return $this->makeAuthResponse($result); } public function getAuthenticationStatus($authenticationRequestId) { - return $this->makeAuthResponse($this->get('authentication_requests/' . $authenticationRequestId)); + return $this->makeAuthResponse($this->advanced->raw->get('authentication_requests/' . $authenticationRequestId)); } private function makePairResponse($result) @@ -138,13 +139,44 @@ private function makeAuthResponse($result) 'raw' => $result ); } +} + +class AdvancedApiUsageFactory +{ + function __construct($key, $secret, $baseUrl, $httpAdapter) + { + $this->raw = new ApiRawRequester($key, $secret, $baseUrl, $httpAdapter); + } +} + +class ApiRawRequester +{ + protected $oauthConsumer; + protected $baseUrl; + protected $httpAdapter; + + function __construct($key, $secret, $baseUrl, $httpAdapter) + { + if(empty($key)) + { + throw new InvalidArgumentException('Toopher consumer key cannot be empty'); + } + if(empty($secret)) + { + throw new InvalidArgumentException('Toopher consumer secret cannot be empty'); + } + + $this->oauthConsumer = new HTTP_OAuth_Consumer($key, $secret); + $this->baseUrl = (!empty($baseUrl)) ? $baseUrl : 'https://api.toopher.com/v1/'; + $this->httpAdapter = (!is_null($httpAdapter)) ? $httpAdapter : new HTTP_Request2_Adapter_Curl(); + } - private function post($endpoint, $parameters) + public function post($endpoint, $parameters) { return $this->request('POST', $endpoint, $parameters); } - private function get($endpoint) + public function get($endpoint) { return $this->request('GET', $endpoint); } diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index cb5d2f1..00bf07a 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -155,6 +155,57 @@ public function testGetAuthenticationStatus(){ $this->assertTrue($auth['terminalName'] == 'another term name', 'wrong auth terminal name'); } + public function testRawPost(){ + $id = Uuid::uuid4()->toString(); + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $params = array('pairing_id' => $id, 'terminal_name' => 'term name'); + $auth_request = $toopher->advanced->raw->post('authentication_requests/initiate', $params); + $this->assertTrue($auth_request['id'] == $id, 'wrong auth id'); + $this->assertTrue($auth_request['pending'] == false, 'wrong auth pending'); + $this->assertTrue($auth_request['granted'] == true, 'wrong auth granted'); + $this->assertTrue($auth_request['automated'] == true, 'wrong auth automated'); + $this->assertTrue($auth_request['reason'] == 'some reason', 'wrong auth reason'); + $this->assertTrue($auth_request['terminal']['id'] == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request['terminal']['name'] == 'term name', 'wrong auth terminal name'); + } + + + public function testRawGet(){ + $id1 = Uuid::uuid4()->toString(); + $id2 = Uuid::uuid4()->toString(); + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id1); + $resp1->appendBody('{"id":"' . $id1 . '","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id2); + $resp2->appendBody('{"id":"' . $id2 . '","pending":true,"granted":false,"automated":false,"reason":"some other reason","terminal":{"id":"2","name":"another term name"}}'); + $mock->addResponse($resp1); + $mock->addResponse($resp2); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $auth_request = $toopher->advanced->raw->get('authentication_requests/' . $id1); + $this->assertTrue($auth_request['id'] == $id1, 'wrong auth id'); + $this->assertTrue($auth_request['pending'] == false, 'wrong auth pending'); + $this->assertTrue($auth_request['granted'] == true, 'wrong auth granted'); + $this->assertTrue($auth_request['automated'] == true, 'wrong auth automated'); + $this->assertTrue($auth_request['reason'] == 'some reason', 'wrong auth reason'); + $this->assertTrue($auth_request['terminal']['id'] == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request['terminal']['name'] == 'term name', 'wrong auth terminal name'); + + $auth_request = $toopher->advanced->raw->get('authentication_requests/' . $id2); + $this->assertTrue($auth_request['id'] == $id2, 'wrong auth id'); + $this->assertTrue($auth_request['pending'] == true, 'wrong auth pending'); + $this->assertTrue($auth_request['granted'] == false, 'wrong auth granted'); + $this->assertTrue($auth_request['automated'] == false, 'wrong auth automated'); + $this->assertTrue($auth_request['reason'] == 'some other reason', 'wrong auth reason'); + $this->assertTrue($auth_request['terminal']['id'] == '2', 'wrong auth terminal id'); + $this->assertTrue($auth_request['terminal']['name'] == 'another term name', 'wrong auth terminal name'); + } + /** * @expectedException ToopherRequestException */ From 549da75a5040a07ac9a74ed016f0f7fdde340650 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 12:49:25 -0600 Subject: [PATCH 004/114] Add Pairing class --- lib/toopher_api.php | 27 +++++++++++++------------- test/test_toopher_api.php | 40 +++++++++++++++++++-------------------- 2 files changed, 34 insertions(+), 33 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 143e8b5..9435981 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -74,12 +74,12 @@ public function pair($username, $phrase_or_num = '', $kwargs = array()) $url = 'pairings/create/qr'; } $result = $this->advanced->raw->post($url, $params); - return $this->makePairResponse($result); + return new Pairing($result); } public function getPairingStatus($pairingId) { - return $this->makePairResponse($this->advanced->raw->get('pairings/' . $pairingId)); + return new Pairing($this->advanced->raw->get('pairings/' . $pairingId)); } public function authenticate($id_or_username, $terminal, $actionName = '', $kwargs = array()) @@ -115,17 +115,6 @@ public function getAuthenticationStatus($authenticationRequestId) return $this->makeAuthResponse($this->advanced->raw->get('authentication_requests/' . $authenticationRequestId)); } - private function makePairResponse($result) - { - return array( - 'id' => $result['id'], - 'enabled' => $result['enabled'], - 'userId' => $result['user']['id'], - 'userName' => $result['user']['name'], - 'raw' => $result - ); - } - private function makeAuthResponse($result) { return array( @@ -264,4 +253,16 @@ private function json_error_to_string($json_error_code) { } } +class Pairing +{ + function __construct($json_response) + { + $this->id = $json_response['id']; + $this->enabled = $json_response['enabled']; + $this->userId = $json_response['user']['id']; + $this->userName = $json_response['user']['name']; + $this->raw = $json_response; + } +} + ?> diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 00bf07a..e70dcc1 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -53,10 +53,10 @@ public function testCreatePair(){ $mock->addResponse($resp); $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); $pairing = $toopher->pair('user', 'immediate_pair'); - $this->assertTrue($pairing['id'] == '1', 'bad pairing id'); - $this->assertTrue($pairing['enabled'] == true, 'pairing not enabled'); - $this->assertTrue($pairing['userId'] == '1', 'bad user id'); - $this->assertTrue($pairing['userName'] == 'user', 'bad user name'); + $this->assertTrue($pairing->id == '1', 'bad pairing id'); + $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '1', 'bad user id'); + $this->assertTrue($pairing->userName == 'user', 'bad user name'); } public function testCreateSmsPair(){ @@ -66,10 +66,10 @@ public function testCreateSmsPair(){ $mock->addResponse($resp); $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); $pairing = $toopher->pair('user', '555-555-5555'); - $this->assertTrue($pairing['id'] == '1', 'bad pairing id'); - $this->assertTrue($pairing['enabled'] == true, 'pairing not enabled'); - $this->assertTrue($pairing['userId'] == '1', 'bad user id'); - $this->assertTrue($pairing['userName'] == 'user', 'bad user name'); + $this->assertTrue($pairing->id == '1', 'bad pairing id'); + $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '1', 'bad user id'); + $this->assertTrue($pairing->userName == 'user', 'bad user name'); } public function testCreateQrPair(){ @@ -79,10 +79,10 @@ public function testCreateQrPair(){ $mock->addResponse($resp); $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); $pairing = $toopher->pair('user'); - $this->assertTrue($pairing['id'] == '1', 'bad pairing id'); - $this->assertTrue($pairing['enabled'] == true, 'pairing not enabled'); - $this->assertTrue($pairing['userId'] == '1', 'bad user id'); - $this->assertTrue($pairing['userName'] == 'user', 'bad user name'); + $this->assertTrue($pairing->id == '1', 'bad pairing id'); + $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '1', 'bad user id'); + $this->assertTrue($pairing->userName == 'user', 'bad user name'); } public function testGetPairingStatus(){ @@ -96,16 +96,16 @@ public function testGetPairingStatus(){ $toopher = new ToopherAPI('key', 'secret', '', $mock); $pairing = $toopher->getPairingStatus('1'); - $this->assertTrue($pairing['id'] == '1', 'bad pairing id'); - $this->assertTrue($pairing['enabled'] == true, 'pairing not enabled'); - $this->assertTrue($pairing['userId'] == '1', 'bad user id'); - $this->assertTrue($pairing['userName'] == 'paired user', 'bad user name'); + $this->assertTrue($pairing->id == '1', 'bad pairing id'); + $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '1', 'bad user id'); + $this->assertTrue($pairing->userName == 'paired user', 'bad user name'); $pairing = $toopher->getPairingStatus('2'); - $this->assertTrue($pairing['id'] == '2', 'bad pairing id'); - $this->assertTrue($pairing['enabled'] == false, 'pairing not enabled'); - $this->assertTrue($pairing['userId'] == '2', 'bad user id'); - $this->assertTrue($pairing['userName'] == 'unpaired user', 'bad user name'); + $this->assertTrue($pairing->id == '2', 'bad pairing id'); + $this->assertTrue($pairing->enabled == false, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '2', 'bad user id'); + $this->assertTrue($pairing->userName == 'unpaired user', 'bad user name'); } public function testCreateAuthenticationWithNoAction(){ From e3dd31e6a700d6b393c584f013a9c538fdfb691d Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 12:52:48 -0600 Subject: [PATCH 005/114] Add Pairings and getById --- lib/toopher_api.php | 27 ++++++++++++++++++++------- test/test_toopher_api.php | 4 ++-- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 9435981..a1c004f 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -49,7 +49,7 @@ function __construct($key, $secret, $baseUrl = '', $httpAdapter = NULL) $this->oauthConsumer = new HTTP_OAuth_Consumer($key, $secret); $this->baseUrl = (!empty($baseUrl)) ? $baseUrl : 'https://api.toopher.com/v1/'; $this->httpAdapter = (!is_null($httpAdapter)) ? $httpAdapter : new HTTP_Request2_Adapter_Curl(); - $this->advanced = new AdvancedApiUsageFactory($key, $secret, $baseUrl, $httpAdapter); + $this->advanced = new AdvancedApiUsageFactory($key, $secret, $baseUrl, $httpAdapter, $this); } public function pair($username, $phrase_or_num = '', $kwargs = array()) @@ -77,11 +77,6 @@ public function pair($username, $phrase_or_num = '', $kwargs = array()) return new Pairing($result); } - public function getPairingStatus($pairingId) - { - return new Pairing($this->advanced->raw->get('pairings/' . $pairingId)); - } - public function authenticate($id_or_username, $terminal, $actionName = '', $kwargs = array()) { $url = 'authentication_requests/initiate'; @@ -132,9 +127,10 @@ private function makeAuthResponse($result) class AdvancedApiUsageFactory { - function __construct($key, $secret, $baseUrl, $httpAdapter) + function __construct($key, $secret, $baseUrl, $httpAdapter, $api) { $this->raw = new ApiRawRequester($key, $secret, $baseUrl, $httpAdapter); + $this->pairings = new Pairings($api); } } @@ -253,6 +249,23 @@ private function json_error_to_string($json_error_code) { } } +class Pairings +{ + protected $api; + + function __construct($api) + { + $this->api = $api; + } + + + public function getById($pairingId) + { + $result = $this->api->advanced->raw->get('pairings/' . $pairingId); + return new Pairing($result); + } +} + class Pairing { function __construct($json_response) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index e70dcc1..54d9f49 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -95,13 +95,13 @@ public function testGetPairingStatus(){ $mock->addResponse($resp2); $toopher = new ToopherAPI('key', 'secret', '', $mock); - $pairing = $toopher->getPairingStatus('1'); + $pairing = $toopher->advanced->pairings->getById('1'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); $this->assertTrue($pairing->userId == '1', 'bad user id'); $this->assertTrue($pairing->userName == 'paired user', 'bad user name'); - $pairing = $toopher->getPairingStatus('2'); + $pairing = $toopher->advanced->pairings->getById('2'); $this->assertTrue($pairing->id == '2', 'bad pairing id'); $this->assertTrue($pairing->enabled == false, 'pairing not enabled'); $this->assertTrue($pairing->userId == '2', 'bad user id'); From 6aed300a76763b03131da46d61194e74a8fac6c6 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 12:58:01 -0600 Subject: [PATCH 006/114] Add AuthenticationRequest --- lib/toopher_api.php | 33 +++++++++++++------------- test/test_toopher_api.php | 50 +++++++++++++++++++-------------------- 2 files changed, 42 insertions(+), 41 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index a1c004f..d2e9d26 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -102,26 +102,12 @@ public function authenticate($id_or_username, $terminal, $actionName = '', $kwar } $params = array_merge($params, $kwargs); $result = $this->advanced->raw->post($url, $params); - return $this->makeAuthResponse($result); + return new AuthenticationRequest($result); } public function getAuthenticationStatus($authenticationRequestId) { - return $this->makeAuthResponse($this->advanced->raw->get('authentication_requests/' . $authenticationRequestId)); - } - - private function makeAuthResponse($result) - { - return array( - 'id' => $result['id'], - 'pending' => $result['pending'], - 'granted' => $result['granted'], - 'automated' => $result['automated'], - 'reason' => $result['reason'], - 'terminalId' => $result['terminal']['id'], - 'terminalName' => $result['terminal']['name'], - 'raw' => $result - ); + return new AuthenticationRequest($this->advanced->raw->get('authentication_requests/' . $authenticationRequestId)); } } @@ -278,4 +264,19 @@ function __construct($json_response) } } +class AuthenticationRequest +{ + function __construct($json_response) + { + $this->id = $json_response['id']; + $this->pending = $json_response['pending']; + $this->granted = $json_response['granted']; + $this->automated = $json_response['automated']; + $this->reason = $json_response['reason']; + $this->terminalId = $json_response['terminal']['id']; + $this->terminalName = $json_response['terminal']['name']; + $this->raw = $json_response; + } +} + ?> diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 54d9f49..77822be 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -116,14 +116,14 @@ public function testCreateAuthenticationWithNoAction(){ $mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $mock); - $auth = $toopher->authenticate($id, 'term name'); - $this->assertTrue($auth['id'] == $id, 'wrong auth id'); - $this->assertTrue($auth['pending'] == false, 'wrong auth pending'); - $this->assertTrue($auth['granted'] == true, 'wrong auth granted'); - $this->assertTrue($auth['automated'] == true, 'wrong auth automated'); - $this->assertTrue($auth['reason'] == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth['terminalId'] == '1', 'wrong auth terminal id'); - $this->assertTrue($auth['terminalName'] == 'term name', 'wrong auth terminal name'); + $auth_request = $toopher->authenticate($id, 'term name'); + $this->assertTrue($auth_request->id == $id, 'wrong auth id'); + $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); + $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); + $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); + $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); + $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); } public function testGetAuthenticationStatus(){ @@ -136,23 +136,23 @@ public function testGetAuthenticationStatus(){ $mock->addResponse($resp2); $toopher = new ToopherAPI('key', 'secret', '', $mock); - $auth = $toopher->getAuthenticationStatus('1'); - $this->assertTrue($auth['id'] == '1', 'wrong auth id'); - $this->assertTrue($auth['pending'] == false, 'wrong auth pending'); - $this->assertTrue($auth['granted'] == true, 'wrong auth granted'); - $this->assertTrue($auth['automated'] == true, 'wrong auth automated'); - $this->assertTrue($auth['reason'] == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth['terminalId'] == '1', 'wrong auth terminal id'); - $this->assertTrue($auth['terminalName'] == 'term name', 'wrong auth terminal name'); - - $auth = $toopher->getAuthenticationStatus('2'); - $this->assertTrue($auth['id'] == '2', 'wrong auth id'); - $this->assertTrue($auth['pending'] == true, 'wrong auth pending'); - $this->assertTrue($auth['granted'] == false, 'wrong auth granted'); - $this->assertTrue($auth['automated'] == false, 'wrong auth automated'); - $this->assertTrue($auth['reason'] == 'some other reason', 'wrong auth reason'); - $this->assertTrue($auth['terminalId'] == '2', 'wrong auth terminal id'); - $this->assertTrue($auth['terminalName'] == 'another term name', 'wrong auth terminal name'); + $auth_request = $toopher->getAuthenticationStatus('1'); + $this->assertTrue($auth_request->id == '1', 'wrong auth id'); + $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); + $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); + $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); + $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); + $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + + $auth_request = $toopher->getAuthenticationStatus('2'); + $this->assertTrue($auth_request->id == '2', 'wrong auth id'); + $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); + $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); + $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); + $this->assertTrue($auth_request->reason == 'some other reason', 'wrong auth reason'); + $this->assertTrue($auth_request->terminalId == '2', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminalName == 'another term name', 'wrong auth terminal name'); } public function testRawPost(){ From cea5c36bf4051b0aa87c70895629e68309759081 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 13:02:59 -0600 Subject: [PATCH 007/114] Add AuthenticationRequests and getById --- lib/toopher_api.php | 23 ++++++++++++++++++----- test/test_toopher_api.php | 10 +++++----- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index d2e9d26..b345f20 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -104,11 +104,6 @@ public function authenticate($id_or_username, $terminal, $actionName = '', $kwar $result = $this->advanced->raw->post($url, $params); return new AuthenticationRequest($result); } - - public function getAuthenticationStatus($authenticationRequestId) - { - return new AuthenticationRequest($this->advanced->raw->get('authentication_requests/' . $authenticationRequestId)); - } } class AdvancedApiUsageFactory @@ -117,6 +112,7 @@ function __construct($key, $secret, $baseUrl, $httpAdapter, $api) { $this->raw = new ApiRawRequester($key, $secret, $baseUrl, $httpAdapter); $this->pairings = new Pairings($api); + $this->authenticationRequests = new AuthenticationRequests($api); } } @@ -264,6 +260,23 @@ function __construct($json_response) } } +class AuthenticationRequests +{ + protected $api; + + function __construct($api) + { + $this->api = $api; + } + + + public function getById($authenticationRequestId) + { + $result = $this->api->advanced->raw->get('authentication_requests/' . $authenticationRequestId); + return new AuthenticationRequest($result); + } +} + class AuthenticationRequest { function __construct($json_response) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 77822be..4e1e3be 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -136,7 +136,7 @@ public function testGetAuthenticationStatus(){ $mock->addResponse($resp2); $toopher = new ToopherAPI('key', 'secret', '', $mock); - $auth_request = $toopher->getAuthenticationStatus('1'); + $auth_request = $toopher->advanced->authenticationRequests->getById('1'); $this->assertTrue($auth_request->id == '1', 'wrong auth id'); $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); @@ -145,7 +145,7 @@ public function testGetAuthenticationStatus(){ $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); - $auth_request = $toopher->getAuthenticationStatus('2'); + $auth_request = $toopher->advanced->authenticationRequests->getById('2'); $this->assertTrue($auth_request->id == '2', 'wrong auth id'); $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); @@ -217,7 +217,7 @@ public function testToopherRequestException(){ $toopher = new ToopherAPI('key', 'secret', '', $mock); - $auth = $toopher->getAuthenticationStatus('1'); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } public function testToopherVersionStringExists() { @@ -236,7 +236,7 @@ public function test400WithEmptyBodyRaisesToopherRequestException(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); $mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $mock); - $auth = $toopher->getAuthenticationStatus('1'); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } /** @@ -248,7 +248,7 @@ public function test400WithUnprintableBodyRaisesToopherRequestException(){ $resp1->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); $mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $mock); - $auth = $toopher->getAuthenticationStatus('1'); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } } From 70652471f36ff6a8739a512b02515b04cc3c3194 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 13:29:05 -0600 Subject: [PATCH 008/114] Add Pairing.refreshFromServer() --- lib/toopher_api.php | 27 ++++++++++++++++++++++----- test/test_toopher_api.php | 23 +++++++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index b345f20..d6622b2 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -74,7 +74,7 @@ public function pair($username, $phrase_or_num = '', $kwargs = array()) $url = 'pairings/create/qr'; } $result = $this->advanced->raw->post($url, $params); - return new Pairing($result); + return new Pairing($result, $this); } public function authenticate($id_or_username, $terminal, $actionName = '', $kwargs = array()) @@ -243,14 +243,30 @@ function __construct($api) public function getById($pairingId) { - $result = $this->api->advanced->raw->get('pairings/' . $pairingId); - return new Pairing($result); + $url = 'pairings/' . $pairingId; + $result = $this->api->advanced->raw->get($url); + return new Pairing($result, $this->api); } } class Pairing { - function __construct($json_response) + protected $api; + + function __construct($json_response, $api) + { + $this->api = $api; + $this->update($json_response); + } + + public function refreshFromServer() + { + $url = 'pairings/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + + private function update($json_response) { $this->id = $json_response['id']; $this->enabled = $json_response['enabled']; @@ -272,7 +288,8 @@ function __construct($api) public function getById($authenticationRequestId) { - $result = $this->api->advanced->raw->get('authentication_requests/' . $authenticationRequestId); + $url = 'authentication_requests/' . $authenticationRequestId; + $result = $this->api->advanced->raw->get($url); return new AuthenticationRequest($result); } } diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 4e1e3be..4204552 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -108,6 +108,29 @@ public function testGetPairingStatus(){ $this->assertTrue($pairing->userName == 'unpaired user', 'bad user name'); } + public function testPairingRefreshFromServer(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); + $resp1->appendBody('{"id":"1","enabled":false,"user":{"id":"1","name":"user"}}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp2->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"user name changed"}}'); + $mock->addResponse($resp1); + $mock->addResponse($resp2); + $toopher = new ToopherAPI('key', 'secret', '', $mock); + + $pairing = $toopher->pair('user', 'pairing phrase'); + $this->assertTrue($pairing->id == '1', 'bad pairing id'); + $this->assertTrue($pairing->enabled == false, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '1', 'bad user id'); + $this->assertTrue($pairing->userName == 'user', 'bad user name'); + + $pairing->refreshFromServer(); + $this->assertTrue($pairing->id == '1', 'bad pairing id'); + $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '1', 'bad user id'); + $this->assertTrue($pairing->userName == 'user name changed', 'bad user name'); + } + public function testCreateAuthenticationWithNoAction(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); From 61a01570dfee36601641bb995477460907e628c3 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 13:36:27 -0600 Subject: [PATCH 009/114] Add AuthenticationRequest.refreshFromServer() --- lib/toopher_api.php | 21 ++++++++++++++++++--- test/test_toopher_api.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index d6622b2..b682160 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -102,7 +102,7 @@ public function authenticate($id_or_username, $terminal, $actionName = '', $kwar } $params = array_merge($params, $kwargs); $result = $this->advanced->raw->post($url, $params); - return new AuthenticationRequest($result); + return new AuthenticationRequest($result, $this); } } @@ -290,13 +290,28 @@ public function getById($authenticationRequestId) { $url = 'authentication_requests/' . $authenticationRequestId; $result = $this->api->advanced->raw->get($url); - return new AuthenticationRequest($result); + return new AuthenticationRequest($result, $this->api); } } class AuthenticationRequest { - function __construct($json_response) + protected $api; + + function __construct($json_response, $api) + { + $this->api = $api; + $this->update($json_response); + } + + public function refreshFromServer() + { + $url = 'authentication_requests/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + + private function update($json_response) { $this->id = $json_response['id']; $this->pending = $json_response['pending']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 4204552..d3aea1d 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -178,6 +178,35 @@ public function testGetAuthenticationStatus(){ $this->assertTrue($auth_request->terminalName == 'another term name', 'wrong auth terminal name'); } + public function testAuthenticationRequestRefreshFromServer(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp1->appendBody('{"id":"1","pending":true,"granted":false,"automated":false,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp2->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason":"some other reason","terminal":{"id":"1","name":"term name changed"}}'); + $mock->addResponse($resp1); + $mock->addResponse($resp2); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $auth_request = $toopher->authenticate('user', 'term name extra'); + $this->assertTrue($auth_request->id == '1', 'wrong auth id'); + $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); + $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); + $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); + $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); + $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + + $auth_request->refreshFromServer(); + $this->assertTrue($auth_request->id == '1', 'wrong auth id'); + $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); + $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); + $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); + $this->assertTrue($auth_request->reason == 'some other reason', 'wrong auth reason'); + $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminalName == 'term name changed', 'wrong auth terminal name'); + } + public function testRawPost(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); From 4c63b398cb03b0a893de1b5b53b23e132bcd9d03 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 13:53:00 -0600 Subject: [PATCH 010/114] Add Pairing->getResetLink() --- lib/toopher_api.php | 16 ++++++++++++++++ test/test_toopher_api.php | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index b682160..c5a85f6 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -266,6 +266,22 @@ public function refreshFromServer() $this->update($result); } + public function getResetLink($kwargs = array()) + { + if(!array_key_exists('security_question', $kwargs)) + { + $kwargs['security_question'] = NULL; + } + if(!array_key_exists('security_answer', $kwargs)) + { + $kwargs['security_answer'] = NULL; + } + + $url = 'pairings/' . $this->id . '/generate_reset_link'; + $result = $this->api->advanced->raw->post($url, $kwargs); + return $result['url']; + } + private function update($json_response) { $this->id = $json_response['id']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index d3aea1d..2a23647 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -131,6 +131,25 @@ public function testPairingRefreshFromServer(){ $this->assertTrue($pairing->userName == 'user name changed', 'bad user name'); } + public function testGetPairingResetLink(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); + $resp1->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"user"}}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); + $resp2->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); + $mock->addResponse($resp1); + $mock->addResponse($resp2); + $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $pairing = $toopher->pair('user', 'immediate_pair'); + $this->assertTrue($pairing->id == '1', 'bad pairing id'); + $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '1', 'bad user id'); + $this->assertTrue($pairing->userName == 'user', 'bad user name'); + + $resetLink = $pairing->getResetLink(); + $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"); + } + public function testCreateAuthenticationWithNoAction(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); From a7ae0f0eefac8c39502dde86633d8c20fba27002 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Mon, 2 Feb 2015 14:01:00 -0600 Subject: [PATCH 011/114] Add Pairing->emailResetLink() --- lib/toopher_api.php | 8 ++++++++ test/test_toopher_api.php | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index c5a85f6..2d9cbf3 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -282,6 +282,14 @@ public function getResetLink($kwargs = array()) return $result['url']; } + public function emailResetLink($email, $kwargs = array()) + { + $params = array('reset_email' => $email); + $params = array_merge($params, $kwargs); + $url = 'pairings/' . $this->id . '/send_reset_link'; + $this->api->advanced->raw->post($url, $params); + } + private function update($json_response) { $this->id = $json_response['id']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 2a23647..531761d 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -150,6 +150,28 @@ public function testGetPairingResetLink(){ $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"); } + public function testEmailPairingResetLink(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); + $resp1->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"user"}}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); + $mock->addResponse($resp1); + $mock->addResponse($resp2); + $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $pairing = $toopher->pair('user', 'immediate_pair'); + $this->assertTrue($pairing->id == '1', 'bad pairing id'); + $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); + $this->assertTrue($pairing->userId == '1', 'bad user id'); + $this->assertTrue($pairing->userName == 'user', 'bad user name'); + + try { + $pairing->emailResetLink('email@domain.com'); + } + catch(Exception $e) { + $this->fail('Unexpected exception has been raised: ' . $e); + } + } + public function testCreateAuthenticationWithNoAction(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); From fb7d1cd6d5033232d4564b69b60b6e4f6ddc7474 Mon Sep 17 00:00:00 2001 From: Amanda Steinwedel Date: Wed, 11 Feb 2015 09:34:53 -0600 Subject: [PATCH 012/114] Add AuthenticationRequest->grantWithOtp() --- lib/toopher_api.php | 9 +++++++++ test/test_toopher_api.php | 30 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 2d9cbf3..ad495ea 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -335,6 +335,15 @@ public function refreshFromServer() $this->update($result); } + public function grant_with_otp($otp, $kwargs = array()) + { + $url = 'authentication_requests/' . $this->id . '/otp_auth'; + $params = array('otp' => $otp); + $params = array_merge($params, $kwargs); + $result = $this->api->advanced->raw->post($url, $params); + $this->update($result); + } + private function update($json_response) { $this->id = $json_response['id']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 531761d..b5bee15 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -248,6 +248,36 @@ public function testAuthenticationRequestRefreshFromServer(){ $this->assertTrue($auth_request->terminalName == 'term name changed', 'wrong auth terminal name'); } + public function testGrantAuthenticationRequestWithOtp(){ + $id = Uuid::uuid4()->toString(); + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp1->appendBody('{"id":"' . $id . '","pending":true,"granted":false,"automated":false,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp2->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $mock->addResponse($resp1); + $mock->addResponse($resp2); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $auth_request = $toopher->authenticate($id, 'term name'); + $this->assertTrue($auth_request->id == $id, 'wrong auth id'); + $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); + $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); + $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); + $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); + $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + + $auth_request->grant_with_otp('otp'); + $this->assertTrue($auth_request->id == $id, 'wrong auth id'); + $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); + $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); + $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); + $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); + $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + } + public function testRawPost(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); From 89e1732c384ff859957cefeaaea08fd9b57b6259 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 10:38:10 -0600 Subject: [PATCH 013/114] Update composer.lock for new packages --- composer.lock | 319 +++++++++++++++++++++++++++++++------------------- 1 file changed, 196 insertions(+), 123 deletions(-) diff --git a/composer.lock b/composer.lock index 6f1821c..032f89e 100644 --- a/composer.lock +++ b/composer.lock @@ -1,16 +1,17 @@ { "_readme": [ "This file locks the dependencies of your project to a known state", - "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" + "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "This file is @generated automatically" ], - "hash": "53b461e8bceb01a377f1e35459f3e770", + "hash": "ccc2dbcabdeb2ff88e43419588500b12", "packages": [ { "name": "pear-pear.php.net/Archive_Tar", - "version": "1.3.11", + "version": "1.3.13", "dist": { "type": "file", - "url": "http://pear.php.net/get/Archive_Tar-1.3.11.tgz", + "url": "http://pear.php.net/get/Archive_Tar-1.3.13.tgz", "reference": null, "shasum": null }, @@ -18,7 +19,7 @@ "php": ">=4.3.0.0" }, "replace": { - "pear-pear/archive_tar": "== 1.3.11.0" + "pear-pear/archive_tar": "== 1.3.13.0" }, "type": "pear-library", "autoload": { @@ -29,6 +30,9 @@ "include-path": [ "/" ], + "license": [ + "New BSD\n License" + ], "description": "This class provides handling of tar files in PHP.\nIt supports creating, listing, extracting and adding to tar files.\nGzip support is available if PHP has the zlib extension built-in or\nloaded. Bz2 compression is also supported with the bz2 extension loaded." }, { @@ -118,10 +122,10 @@ }, { "name": "pear-pear.php.net/Net_URL2", - "version": "2.0.5", + "version": "2.1.1", "dist": { "type": "file", - "url": "http://pear.php.net/get/Net_URL2-2.0.5.tgz", + "url": "http://pear.php.net/get/Net_URL2-2.1.1.tgz", "reference": null, "shasum": null }, @@ -129,7 +133,7 @@ "php": ">=5.1.4.0" }, "replace": { - "pear-pear/net_url2": "== 2.0.5.0" + "pear-pear/net_url2": "== 2.1.1.0" }, "type": "pear-library", "autoload": { @@ -140,21 +144,24 @@ "include-path": [ "/" ], + "license": [ + "BSD-3-Clause" + ], "description": "Provides parsing of URLs into their constituent parts (scheme, host, path etc.), URL generation, and resolving of\n relative URLs." }, { "name": "pear-pear.php.net/PEAR", - "version": "1.9.4", + "version": "1.9.5", "dist": { "type": "file", - "url": "http://pear.php.net/get/PEAR-1.9.4.tgz", + "url": "http://pear.php.net/get/PEAR-1.9.5.tgz", "reference": null, "shasum": null }, "require": { "ext-pcre": "*", "ext-xml": "*", - "pear-pear.php.net/archive_tar": ">=1.3.7.0", + "pear-pear.php.net/archive_tar": ">=1.3.11.0", "pear-pear.php.net/console_getopt": ">=1.2.0.0", "pear-pear.php.net/structures_graph": ">=1.0.2.0", "pear-pear.php.net/xml_util": ">=1.2.0.0", @@ -165,7 +172,7 @@ "pear-pear.php.net/pear_frontend_web": "<=0.4.0.0" }, "replace": { - "pear-pear/pear": "== 1.9.4.0" + "pear-pear/pear": "== 1.9.5.0" }, "type": "pear-library", "autoload": { @@ -176,6 +183,9 @@ "include-path": [ "/" ], + "license": [ + "New BSD License" + ], "description": "The PEAR package contains:\n * the PEAR installer, for creating, distributing\n and installing packages\n * the PEAR_Exception PHP5 error handling mechanism\n * the PEAR_ErrorStack advanced error handling mechanism\n * the PEAR_Error error handling mechanism\n * the OS_Guess class for retrieving info about the OS\n where PHP is running on\n * the System class for quick handling of common operations\n with files and directories\n * the PEAR base class\n Features in a nutshell:\n * full support for channels\n * pre-download dependency validation\n * new package.xml 2.0 format allows tremendous flexibility while maintaining BC\n * support for optional dependency groups and limited support for sub-packaging\n * robust dependency support\n * full dependency validation on uninstall\n * remote install for hosts with only ftp access - no more problems with\n restricted host installation\n * full support for mirroring\n * support for bundling several packages into a single tarball\n * support for static dependencies on a url-based package\n * support for custom file roles and installation tasks" }, { @@ -206,10 +216,10 @@ }, { "name": "pear-pear.php.net/XML_Util", - "version": "1.2.1", + "version": "1.2.3", "dist": { "type": "file", - "url": "http://pear.php.net/get/XML_Util-1.2.1.tgz", + "url": "http://pear.php.net/get/XML_Util-1.2.3.tgz", "reference": null, "shasum": null }, @@ -218,7 +228,7 @@ "php": ">=4.3.0.0" }, "replace": { - "pear-pear/xml_util": "== 1.2.1.0" + "pear-pear/xml_util": "== 1.2.3.0" }, "type": "pear-library", "autoload": { @@ -229,22 +239,25 @@ "include-path": [ "/" ], + "license": [ + "BSD License" + ], "description": "Selection of methods that are often needed when working with XML documents. Functionality includes creating of attribute lists from arrays, creation of tags, validation of XML names and more." } ], "packages-dev": [ { "name": "guzzle/guzzle", - "version": "v3.9.1", + "version": "v3.9.2", "source": { "type": "git", "url": "https://github.com/guzzle/guzzle3.git", - "reference": "92d9934f2fca1da15178c91239576ae26e505e60" + "reference": "54991459675c1a2924122afbb0e5609ade581155" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle3/zipball/92d9934f2fca1da15178c91239576ae26e505e60", - "reference": "92d9934f2fca1da15178c91239576ae26e505e60", + "url": "https://api.github.com/repos/guzzle/guzzle3/zipball/54991459675c1a2924122afbb0e5609ade581155", + "reference": "54991459675c1a2924122afbb0e5609ade581155", "shasum": "" }, "require": { @@ -288,7 +301,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "3.8-dev" + "dev-master": "3.9-dev" } }, "autoload": { @@ -323,27 +336,27 @@ "rest", "web service" ], - "time": "2014-05-07 17:04:22" + "time": "2014-08-11 04:32:36" }, { "name": "phpunit/php-code-coverage", - "version": "1.2.17", + "version": "1.2.18", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "6ef2bf3a1c47eca07ea95f0d8a902a6340390b34" + "reference": "fe2466802556d3fe4e4d1d58ffd3ccfd0a19be0b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/6ef2bf3a1c47eca07ea95f0d8a902a6340390b34", - "reference": "6ef2bf3a1c47eca07ea95f0d8a902a6340390b34", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/fe2466802556d3fe4e4d1d58ffd3ccfd0a19be0b", + "reference": "fe2466802556d3fe4e4d1d58ffd3ccfd0a19be0b", "shasum": "" }, "require": { "php": ">=5.3.3", "phpunit/php-file-iterator": ">=1.3.0@stable", "phpunit/php-text-template": ">=1.2.0@stable", - "phpunit/php-token-stream": ">=1.1.3@stable" + "phpunit/php-token-stream": ">=1.1.3,<1.3.0" }, "require-dev": { "phpunit/phpunit": "3.7.*@dev" @@ -384,7 +397,7 @@ "testing", "xunit" ], - "time": "2014-03-28 10:53:45" + "time": "2014-09-02 10:13:14" }, { "name": "phpunit/php-file-iterator", @@ -571,16 +584,16 @@ }, { "name": "phpunit/phpunit", - "version": "3.7.37", + "version": "3.7.38", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "ae6cefd7cc84586a5ef27e04bae11ee940ec63dc" + "reference": "38709dc22d519a3d1be46849868aa2ddf822bcf6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/ae6cefd7cc84586a5ef27e04bae11ee940ec63dc", - "reference": "ae6cefd7cc84586a5ef27e04bae11ee940ec63dc", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/38709dc22d519a3d1be46849868aa2ddf822bcf6", + "reference": "38709dc22d519a3d1be46849868aa2ddf822bcf6", "shasum": "" }, "require": { @@ -640,20 +653,20 @@ "testing", "xunit" ], - "time": "2014-04-30 12:24:19" + "time": "2014-10-17 09:04:17" }, { "name": "phpunit/phpunit-mock-objects", "version": "1.2.3", "source": { "type": "git", - "url": "git://github.com/sebastianbergmann/phpunit-mock-objects.git", - "reference": "1.2.3" + "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git", + "reference": "5794e3c5c5ba0fb037b11d8151add2a07fa82875" }, "dist": { "type": "zip", - "url": "https://github.com/sebastianbergmann/phpunit-mock-objects/archive/1.2.3.zip", - "reference": "1.2.3", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/5794e3c5c5ba0fb037b11d8151add2a07fa82875", + "reference": "5794e3c5c5ba0fb037b11d8151add2a07fa82875", "shasum": "" }, "require": { @@ -729,24 +742,90 @@ ], "time": "2012-12-21 11:40:51" }, + { + "name": "rhumsaa/uuid", + "version": "2.8.0", + "source": { + "type": "git", + "url": "https://github.com/ramsey/uuid.git", + "reference": "cca98c652cac412c9c2f109c69e5532f313435fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/cca98c652cac412c9c2f109c69e5532f313435fc", + "reference": "cca98c652cac412c9c2f109c69e5532f313435fc", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "doctrine/dbal": ">=2.3", + "moontoast/math": "~1.1", + "phpunit/phpunit": "~4.1", + "satooshi/php-coveralls": "~0.6", + "symfony/console": "~2.3" + }, + "suggest": { + "doctrine/dbal": "Allow the use of a UUID as doctrine field type.", + "moontoast/math": "Support for converting UUID to 128-bit integer (in string form).", + "symfony/console": "Support for use of the bin/uuid command line tool." + }, + "bin": [ + "bin/uuid" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8.x-dev" + } + }, + "autoload": { + "psr-4": { + "Rhumsaa\\Uuid\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Marijn Huizendveld", + "email": "marijn.huizendveld@gmail.com" + }, + { + "name": "Ben Ramsey", + "homepage": "http://benramsey.com" + } + ], + "description": "A PHP 5.3+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID).", + "homepage": "https://github.com/ramsey/uuid", + "keywords": [ + "guid", + "identifier", + "uuid" + ], + "time": "2014-11-09 18:42:56" + }, { "name": "satooshi/php-coveralls", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/satooshi/php-coveralls.git", - "reference": "b7271847c84d160f5b0aae83e45c225e8ffc96f4" + "reference": "2fbf803803d179ab1082807308a67bbd5a760c70" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/satooshi/php-coveralls/zipball/b7271847c84d160f5b0aae83e45c225e8ffc96f4", - "reference": "b7271847c84d160f5b0aae83e45c225e8ffc96f4", + "url": "https://api.github.com/repos/satooshi/php-coveralls/zipball/2fbf803803d179ab1082807308a67bbd5a760c70", + "reference": "2fbf803803d179ab1082807308a67bbd5a760c70", "shasum": "" }, "require": { "ext-json": "*", "ext-simplexml": "*", - "guzzle/guzzle": ">=3.0", + "guzzle/guzzle": ">=2.7", "php": ">=5.3", "psr/log": "1.0.0", "symfony/config": ">=2.0", @@ -756,7 +835,7 @@ }, "require-dev": { "apigen/apigen": "2.8.*@stable", - "pdepend/pdepend": "dev-master", + "pdepend/pdepend": "dev-master as 2.0.0", "phpmd/phpmd": "dev-master", "phpunit/php-invoker": ">=1.1.0,<1.2.0", "phpunit/phpunit": "3.7.*@stable", @@ -802,21 +881,21 @@ "github", "test" ], - "time": "2014-05-14 13:09:37" + "time": "2014-11-11 15:35:34" }, { "name": "symfony/config", - "version": "v2.4.5", + "version": "v2.6.4", "target-dir": "Symfony/Component/Config", "source": { "type": "git", "url": "https://github.com/symfony/Config.git", - "reference": "2effc67af6f21a0d267210b72d0b0b691d113528" + "reference": "a9f781ba1221067d1f07c8cec0bc50f81b8d7408" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/Config/zipball/2effc67af6f21a0d267210b72d0b0b691d113528", - "reference": "2effc67af6f21a0d267210b72d0b0b691d113528", + "url": "https://api.github.com/repos/symfony/Config/zipball/a9f781ba1221067d1f07c8cec0bc50f81b8d7408", + "reference": "a9f781ba1221067d1f07c8cec0bc50f81b8d7408", "shasum": "" }, "require": { @@ -826,7 +905,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.4-dev" + "dev-master": "2.6-dev" } }, "autoload": { @@ -839,49 +918,51 @@ "MIT" ], "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com", - "homepage": "http://fabien.potencier.org", - "role": "Lead Developer" - }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" } ], "description": "Symfony Config Component", "homepage": "http://symfony.com", - "time": "2014-04-22 08:11:06" + "time": "2015-01-21 20:57:55" }, { "name": "symfony/console", - "version": "v2.4.5", + "version": "v2.6.4", "target-dir": "Symfony/Component/Console", "source": { "type": "git", "url": "https://github.com/symfony/Console.git", - "reference": "24f723436e62598c9dddee2a8573d6992504dc5d" + "reference": "e44154bfe3e41e8267d7a3794cd9da9a51cfac34" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/Console/zipball/24f723436e62598c9dddee2a8573d6992504dc5d", - "reference": "24f723436e62598c9dddee2a8573d6992504dc5d", + "url": "https://api.github.com/repos/symfony/Console/zipball/e44154bfe3e41e8267d7a3794cd9da9a51cfac34", + "reference": "e44154bfe3e41e8267d7a3794cd9da9a51cfac34", "shasum": "" }, "require": { "php": ">=5.3.3" }, "require-dev": { - "symfony/event-dispatcher": "~2.1" + "psr/log": "~1.0", + "symfony/event-dispatcher": "~2.1", + "symfony/process": "~2.1" }, "suggest": { - "symfony/event-dispatcher": "" + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/process": "" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.4-dev" + "dev-master": "2.6-dev" } }, "autoload": { @@ -894,41 +975,43 @@ "MIT" ], "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com", - "homepage": "http://fabien.potencier.org", - "role": "Lead Developer" - }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" } ], "description": "Symfony Console Component", "homepage": "http://symfony.com", - "time": "2014-05-14 21:48:29" + "time": "2015-01-25 04:39:26" }, { "name": "symfony/event-dispatcher", - "version": "v2.4.5", + "version": "v2.6.4", "target-dir": "Symfony/Component/EventDispatcher", "source": { "type": "git", "url": "https://github.com/symfony/EventDispatcher.git", - "reference": "e539602e5455aa086c0e81e604745af7789e4d8a" + "reference": "f75989f3ab2743a82fe0b03ded2598a2b1546813" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/e539602e5455aa086c0e81e604745af7789e4d8a", - "reference": "e539602e5455aa086c0e81e604745af7789e4d8a", + "url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/f75989f3ab2743a82fe0b03ded2598a2b1546813", + "reference": "f75989f3ab2743a82fe0b03ded2598a2b1546813", "shasum": "" }, "require": { "php": ">=5.3.3" }, "require-dev": { - "symfony/dependency-injection": "~2.0" + "psr/log": "~1.0", + "symfony/config": "~2.0,>=2.0.5", + "symfony/dependency-injection": "~2.6", + "symfony/expression-language": "~2.6", + "symfony/stopwatch": "~2.3" }, "suggest": { "symfony/dependency-injection": "", @@ -937,7 +1020,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.4-dev" + "dev-master": "2.6-dev" } }, "autoload": { @@ -950,34 +1033,32 @@ "MIT" ], "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com", - "homepage": "http://fabien.potencier.org", - "role": "Lead Developer" - }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" } ], "description": "Symfony EventDispatcher Component", "homepage": "http://symfony.com", - "time": "2014-04-16 10:34:31" + "time": "2015-02-01 16:10:57" }, { "name": "symfony/filesystem", - "version": "v2.4.5", + "version": "v2.6.4", "target-dir": "Symfony/Component/Filesystem", "source": { "type": "git", "url": "https://github.com/symfony/Filesystem.git", - "reference": "a3af8294bcce4a7c1b2892363b0c9d8109affad4" + "reference": "a1f566d1f92e142fa1593f4555d6d89e3044a9b7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/Filesystem/zipball/a3af8294bcce4a7c1b2892363b0c9d8109affad4", - "reference": "a3af8294bcce4a7c1b2892363b0c9d8109affad4", + "url": "https://api.github.com/repos/symfony/Filesystem/zipball/a1f566d1f92e142fa1593f4555d6d89e3044a9b7", + "reference": "a1f566d1f92e142fa1593f4555d6d89e3044a9b7", "shasum": "" }, "require": { @@ -986,7 +1067,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.4-dev" + "dev-master": "2.6-dev" } }, "autoload": { @@ -999,34 +1080,32 @@ "MIT" ], "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com", - "homepage": "http://fabien.potencier.org", - "role": "Lead Developer" - }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" } ], "description": "Symfony Filesystem Component", "homepage": "http://symfony.com", - "time": "2014-04-16 10:34:31" + "time": "2015-01-03 21:13:09" }, { "name": "symfony/stopwatch", - "version": "v2.4.5", + "version": "v2.6.4", "target-dir": "Symfony/Component/Stopwatch", "source": { "type": "git", "url": "https://github.com/symfony/Stopwatch.git", - "reference": "343bcc0360f2c22f371884b8f6a9fee8d1aa431a" + "reference": "e8da5286132ba75ce4b4275fbf0f4cd369bfd71c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/Stopwatch/zipball/343bcc0360f2c22f371884b8f6a9fee8d1aa431a", - "reference": "343bcc0360f2c22f371884b8f6a9fee8d1aa431a", + "url": "https://api.github.com/repos/symfony/Stopwatch/zipball/e8da5286132ba75ce4b4275fbf0f4cd369bfd71c", + "reference": "e8da5286132ba75ce4b4275fbf0f4cd369bfd71c", "shasum": "" }, "require": { @@ -1035,7 +1114,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.4-dev" + "dev-master": "2.6-dev" } }, "autoload": { @@ -1048,34 +1127,32 @@ "MIT" ], "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com", - "homepage": "http://fabien.potencier.org", - "role": "Lead Developer" - }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" } ], "description": "Symfony Stopwatch Component", "homepage": "http://symfony.com", - "time": "2014-04-18 20:37:09" + "time": "2015-01-03 08:01:59" }, { "name": "symfony/yaml", - "version": "v2.4.5", + "version": "v2.6.4", "target-dir": "Symfony/Component/Yaml", "source": { "type": "git", "url": "https://github.com/symfony/Yaml.git", - "reference": "fd22bb88c3a6f73c898b39bec185a9e211b06265" + "reference": "60ed7751671113cf1ee7d7778e691642c2e9acd8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/Yaml/zipball/fd22bb88c3a6f73c898b39bec185a9e211b06265", - "reference": "fd22bb88c3a6f73c898b39bec185a9e211b06265", + "url": "https://api.github.com/repos/symfony/Yaml/zipball/60ed7751671113cf1ee7d7778e691642c2e9acd8", + "reference": "60ed7751671113cf1ee7d7778e691642c2e9acd8", "shasum": "" }, "require": { @@ -1084,7 +1161,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.4-dev" + "dev-master": "2.6-dev" } }, "autoload": { @@ -1097,34 +1174,30 @@ "MIT" ], "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com", - "homepage": "http://fabien.potencier.org", - "role": "Lead Developer" - }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" } ], "description": "Symfony Yaml Component", "homepage": "http://symfony.com", - "time": "2014-05-12 09:27:48" + "time": "2015-01-25 04:39:26" } ], - "aliases": [ - - ], + "aliases": [], "minimum-stability": "stable", "stability-flags": { "satooshi/php-coveralls": 20 }, + "prefer-stable": false, + "prefer-lowest": false, "platform": { "php": ">=5.3.0", "ext-json": "*" }, - "platform-dev": [ - - ] + "platform-dev": [] } From 189528dfe4fd5641b42d53b329c5f26f7dc58cc8 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 10:42:07 -0600 Subject: [PATCH 014/114] Rename terminal_name_extra to requester_specified_terminal_id --- lib/toopher_api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index ad495ea..78e2951 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -92,7 +92,7 @@ public function authenticate($id_or_username, $terminal, $actionName = '', $kwar { $params = array( 'user_name' => $id_or_username, - 'terminal_name_extra' => $terminal + 'requester_specified_terminal_id' => $terminal ); } From f2c0b34ad177755809d549d9b5f869cdff16552d Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 11:12:18 -0600 Subject: [PATCH 015/114] Add User and update --- lib/toopher_api.php | 21 +++++++++++++++++++++ test/test_toopher_api.php | 8 ++++++++ 2 files changed, 29 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 78e2951..6e0a6a8 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -357,4 +357,25 @@ private function update($json_response) } } +class User +{ + protected $api; + + function __construct($json_response, $api) + { + $this->api = $api; + $this->id = $json_response['id']; + $this->name = $json_response['name']; + $this->toopher_authentication_enabled = $json_response['toopher_authentication_enabled']; + $this->raw_response = $json_response; + } + + public function update($json_response) + { + $this->name = $json_response['name']; + $this->toopher_authentication_enabled = $json_response['toopher_authentication_enabled']; + $this->raw_response = $json_response; + } +} + ?> diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index b5bee15..5689003 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -329,6 +329,14 @@ public function testRawGet(){ $this->assertTrue($auth_request['terminal']['name'] == 'another term name', 'wrong auth terminal name'); } + public function testUser(){ + $toopher = new ToopherAPI('key', 'secret'); + $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); + $this->assertTrue($user->id == '1', 'bad user id'); + $this->assertTrue($user->name == 'user', 'bad user name'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + } + /** * @expectedException ToopherRequestException */ From 051ddc67ecf7b6ad636fc75f51efb1713c3379a4 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 11:16:28 -0600 Subject: [PATCH 016/114] Update Pairing.__construct and update() --- lib/toopher_api.php | 13 ++++++---- test/test_toopher_api.php | 54 +++++++++++++++++++-------------------- 2 files changed, 35 insertions(+), 32 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 6e0a6a8..2d531bb 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -256,7 +256,11 @@ class Pairing function __construct($json_response, $api) { $this->api = $api; - $this->update($json_response); + $this->id = $json_response['id']; + $this->enabled = $json_response['enabled']; + $this->pending = $json_response['pending']; + $this->user = new User($json_response['user'], $api); + $this->raw_response = $json_response; } public function refreshFromServer() @@ -292,11 +296,10 @@ public function emailResetLink($email, $kwargs = array()) private function update($json_response) { - $this->id = $json_response['id']; $this->enabled = $json_response['enabled']; - $this->userId = $json_response['user']['id']; - $this->userName = $json_response['user']['name']; - $this->raw = $json_response; + $this->pending = $json_response['pending']; + $this->user->update($json_response['user']); + $this->raw_response = $json_response; } } diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 5689003..cddd4c3 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -49,48 +49,48 @@ public function testCanCreateToopherApiWithArguments() { public function testCreatePair(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"user"}}'); + $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp); $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '1', 'bad user id'); - $this->assertTrue($pairing->userName == 'user', 'bad user name'); + $this->assertTrue($pairing->user->id == '1', 'bad user id'); + $this->assertTrue($pairing->user->name == 'user', 'bad user name'); } public function testCreateSmsPair(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); - $resp->appendBody('{"id":"1", "enabled":true, "user":{"id":"1", "name":"user"}}'); + $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp); $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); $pairing = $toopher->pair('user', '555-555-5555'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '1', 'bad user id'); - $this->assertTrue($pairing->userName == 'user', 'bad user name'); + $this->assertTrue($pairing->user->id == '1', 'bad user id'); + $this->assertTrue($pairing->user->name == 'user', 'bad user name'); } public function testCreateQrPair(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); - $resp->appendBody('{"id":"1", "enabled":true, "user":{"id":"1", "name":"user"}}'); + $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp); $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); $pairing = $toopher->pair('user'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '1', 'bad user id'); - $this->assertTrue($pairing->userName == 'user', 'bad user name'); + $this->assertTrue($pairing->user->id == '1', 'bad user id'); + $this->assertTrue($pairing->user->name == 'user', 'bad user name'); } public function testGetPairingStatus(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); - $resp1->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"paired user"}}'); + $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"paired user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); - $resp2->appendBody('{"id":"2","enabled":false,"user":{"id":"2","name":"unpaired user"}}'); + $resp2->appendBody('{"id":"2","enabled":false, "pending":false, "user":{"id":"2","name":"unpaired user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); $toopher = new ToopherAPI('key', 'secret', '', $mock); @@ -98,22 +98,22 @@ public function testGetPairingStatus(){ $pairing = $toopher->advanced->pairings->getById('1'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '1', 'bad user id'); - $this->assertTrue($pairing->userName == 'paired user', 'bad user name'); + $this->assertTrue($pairing->user->id == '1', 'bad user id'); + $this->assertTrue($pairing->user->name == 'paired user', 'bad user name'); $pairing = $toopher->advanced->pairings->getById('2'); $this->assertTrue($pairing->id == '2', 'bad pairing id'); $this->assertTrue($pairing->enabled == false, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '2', 'bad user id'); - $this->assertTrue($pairing->userName == 'unpaired user', 'bad user name'); + $this->assertTrue($pairing->user->id == '2', 'bad user id'); + $this->assertTrue($pairing->user->name == 'unpaired user', 'bad user name'); } public function testPairingRefreshFromServer(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp1->appendBody('{"id":"1","enabled":false,"user":{"id":"1","name":"user"}}'); + $resp1->appendBody('{"id":"1","enabled":false, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); - $resp2->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"user name changed"}}'); + $resp2->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); $toopher = new ToopherAPI('key', 'secret', '', $mock); @@ -121,20 +121,20 @@ public function testPairingRefreshFromServer(){ $pairing = $toopher->pair('user', 'pairing phrase'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == false, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '1', 'bad user id'); - $this->assertTrue($pairing->userName == 'user', 'bad user name'); + $this->assertTrue($pairing->user->id == '1', 'bad user id'); + $this->assertTrue($pairing->user->name == 'user', 'bad user name'); $pairing->refreshFromServer(); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '1', 'bad user id'); - $this->assertTrue($pairing->userName == 'user name changed', 'bad user name'); + $this->assertTrue($pairing->user->id == '1', 'bad user id'); + $this->assertTrue($pairing->user->name == 'user name changed', 'bad user name'); } public function testGetPairingResetLink(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp1->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"user"}}'); + $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); $resp2->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); $mock->addResponse($resp1); @@ -143,8 +143,8 @@ public function testGetPairingResetLink(){ $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '1', 'bad user id'); - $this->assertTrue($pairing->userName == 'user', 'bad user name'); + $this->assertTrue($pairing->user->id == '1', 'bad user id'); + $this->assertTrue($pairing->user->name == 'user', 'bad user name'); $resetLink = $pairing->getResetLink(); $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"); @@ -153,7 +153,7 @@ public function testGetPairingResetLink(){ public function testEmailPairingResetLink(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp1->appendBody('{"id":"1","enabled":true,"user":{"id":"1","name":"user"}}'); + $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); $mock->addResponse($resp1); $mock->addResponse($resp2); @@ -161,8 +161,8 @@ public function testEmailPairingResetLink(){ $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->userId == '1', 'bad user id'); - $this->assertTrue($pairing->userName == 'user', 'bad user name'); + $this->assertTrue($pairing->user->id == '1', 'bad user id'); + $this->assertTrue($pairing->user->name == 'user', 'bad user name'); try { $pairing->emailResetLink('email@domain.com'); From 5b181bb68c50c86e4923db779aa3c3328147f11f Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 11:39:18 -0600 Subject: [PATCH 017/114] Add UserTerminal and update --- lib/toopher_api.php | 22 ++++++++++++++++++++++ test/test_toopher_api.php | 12 ++++++++++++ 2 files changed, 34 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 2d531bb..260032c 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -381,4 +381,26 @@ public function update($json_response) } } +class UserTerminal +{ + protected $api; + + function __construct($json_response, $api) + { + $this->id = $json_response['id']; + $this->name = $json_response['name']; + $this->requester_specified_id = $json_response['requester_specified_id']; + $this->user = new User($json_response['user'], $api); + $this->raw_response = $json_response; + } + + public function update($json_response) + { + $this->name = $json_response['name']; + $this->requester_specified_id = $json_response['requester_specified_id']; + $this->user->update($json_response['user']); + $this->raw_response = $json_response; + } +} + ?> diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index cddd4c3..64bc8fd 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -337,6 +337,18 @@ public function testUser(){ $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); } + public function testUserTerminal(){ + $toopher = new ToopherAPI('key', 'secret'); + $user_terminal = new UserTerminal(["id" => "1", "name" => "user", "requester_specified_id" => "1", "user" => ["id" => "1","name" => "user", "toopher_authentication_enabled" => true]], $toopher); + $this->assertTrue($user_terminal->id == '1', 'bad user terminal id'); + $this->assertTrue($user_terminal->name == 'user', 'bad user terminal name'); + $this->assertTrue($user_terminal->requester_specified_id == '1', 'bad user terminal requester specified is'); + $this->assertTrue($user_terminal->user->id == '1', 'bad user id'); + $this->assertTrue($user_terminal->user->name == 'user', 'bad user name'); + $this->assertTrue($user_terminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + } + + /** * @expectedException ToopherRequestException */ From 5735f4a16ba24b2fcaf69273a6789489bc5eeb52 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 11:40:01 -0600 Subject: [PATCH 018/114] Update AuthenticationRequest.__construct and update() --- lib/toopher_api.php | 18 +++++++++++---- test/test_toopher_api.php | 48 +++++++++++++++++++-------------------- 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 260032c..934a477 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -328,7 +328,15 @@ class AuthenticationRequest function __construct($json_response, $api) { $this->api = $api; - $this->update($json_response); + $this->id = $json_response['id']; + $this->pending = $json_response['pending']; + $this->granted = $json_response['granted']; + $this->automated = $json_response['automated']; + $this->reason_code = $json_response['reason_code']; + $this->reason = $json_response['reason']; + $this->terminal = new UserTerminal($json_response['terminal'], $api); + $this->user = new User($json_response['user'], $api); + $this->raw_response = $json_response; } public function refreshFromServer() @@ -349,14 +357,14 @@ public function grant_with_otp($otp, $kwargs = array()) private function update($json_response) { - $this->id = $json_response['id']; $this->pending = $json_response['pending']; $this->granted = $json_response['granted']; $this->automated = $json_response['automated']; + $this->reason_code = $json_response['reason_code']; $this->reason = $json_response['reason']; - $this->terminalId = $json_response['terminal']['id']; - $this->terminalName = $json_response['terminal']['name']; - $this->raw = $json_response; + $this->terminal->update($json_response['terminal']); + $this->user->update($json_response['user']); + $this->raw_respones = $json_response; } } diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 64bc8fd..b367b4f 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -176,7 +176,7 @@ public function testCreateAuthenticationWithNoAction(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $mock); @@ -186,16 +186,16 @@ public function testCreateAuthenticationWithNoAction(){ $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); } public function testGetAuthenticationStatus(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp1->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp1->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/2'); - $resp2->appendBody('{"id":"2","pending":true,"granted":false,"automated":false,"reason":"some other reason","terminal":{"id":"2","name":"another term name"}}'); + $resp2->appendBody('{"id":"2","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); @@ -206,8 +206,8 @@ public function testGetAuthenticationStatus(){ $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); $auth_request = $toopher->advanced->authenticationRequests->getById('2'); $this->assertTrue($auth_request->id == '2', 'wrong auth id'); @@ -215,16 +215,16 @@ public function testGetAuthenticationStatus(){ $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); $this->assertTrue($auth_request->reason == 'some other reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminalId == '2', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminalName == 'another term name', 'wrong auth terminal name'); + $this->assertTrue($auth_request->terminal->id == '2', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminal->name == 'another term name', 'wrong auth terminal name'); } public function testAuthenticationRequestRefreshFromServer(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"1","pending":true,"granted":false,"automated":false,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp1->appendBody('{"id":"1","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp2->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason":"some other reason","terminal":{"id":"1","name":"term name changed"}}'); + $resp2->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); @@ -235,8 +235,8 @@ public function testAuthenticationRequestRefreshFromServer(){ $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); $auth_request->refreshFromServer(); $this->assertTrue($auth_request->id == '1', 'wrong auth id'); @@ -244,17 +244,17 @@ public function testAuthenticationRequestRefreshFromServer(){ $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); $this->assertTrue($auth_request->reason == 'some other reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminalName == 'term name changed', 'wrong auth terminal name'); + $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminal->name == 'term name changed', 'wrong auth terminal name'); } public function testGrantAuthenticationRequestWithOtp(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":true,"granted":false,"automated":false,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp1->appendBody('{"id":"' . $id . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp2->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp2->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); @@ -265,8 +265,8 @@ public function testGrantAuthenticationRequestWithOtp(){ $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); $auth_request->grant_with_otp('otp'); $this->assertTrue($auth_request->id == $id, 'wrong auth id'); @@ -274,15 +274,15 @@ public function testGrantAuthenticationRequestWithOtp(){ $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminalId == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminalName == 'term name', 'wrong auth terminal name'); + $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); + $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); } public function testRawPost(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $mock); @@ -303,9 +303,9 @@ public function testRawGet(){ $id2 = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id1); - $resp1->appendBody('{"id":"' . $id1 . '","pending":false,"granted":true,"automated":true,"reason":"some reason","terminal":{"id":"1","name":"term name"}}'); + $resp1->appendBody('{"id":"' . $id1 . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id2); - $resp2->appendBody('{"id":"' . $id2 . '","pending":true,"granted":false,"automated":false,"reason":"some other reason","terminal":{"id":"2","name":"another term name"}}'); + $resp2->appendBody('{"id":"' . $id2 . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); From 283a53c8d5b6e9af4e761e5365fb0e2857ad4eb3 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 11:52:21 -0600 Subject: [PATCH 019/114] Add Action and update --- lib/toopher_api.php | 18 ++++++++++++++++++ test/test_toopher_api.php | 27 +++++++++++++++++---------- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 934a477..7dfd1fb 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -336,6 +336,7 @@ function __construct($json_response, $api) $this->reason = $json_response['reason']; $this->terminal = new UserTerminal($json_response['terminal'], $api); $this->user = new User($json_response['user'], $api); + $this->action = new Action($json_response['action']); $this->raw_response = $json_response; } @@ -364,6 +365,7 @@ private function update($json_response) $this->reason = $json_response['reason']; $this->terminal->update($json_response['terminal']); $this->user->update($json_response['user']); + $this->action->update($json_response['action']); $this->raw_respones = $json_response; } } @@ -411,4 +413,20 @@ public function update($json_response) } } +class Action +{ + function __construct($json_response) + { + $this->id = $json_response['id']; + $this->name = $json_response['name']; + $this->raw_response = $json_response; + } + + public function update($json_response) + { + $this->name = $json_response['name']; + $this->raw_response = $json_response; + } +} + ?> diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index b367b4f..a2028b3 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -176,7 +176,7 @@ public function testCreateAuthenticationWithNoAction(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $mock); @@ -193,9 +193,9 @@ public function testCreateAuthenticationWithNoAction(){ public function testGetAuthenticationStatus(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp1->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp1->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/2'); - $resp2->appendBody('{"id":"2","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp2->appendBody('{"id":"2","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); @@ -222,9 +222,9 @@ public function testGetAuthenticationStatus(){ public function testAuthenticationRequestRefreshFromServer(){ $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"1","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp1->appendBody('{"id":"1","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp2->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp2->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); @@ -252,9 +252,9 @@ public function testGrantAuthenticationRequestWithOtp(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp1->appendBody('{"id":"' . $id . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp2->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp2->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); @@ -282,7 +282,7 @@ public function testRawPost(){ $id = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $mock); @@ -303,9 +303,9 @@ public function testRawGet(){ $id2 = Uuid::uuid4()->toString(); $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id1); - $resp1->appendBody('{"id":"' . $id1 . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp1->appendBody('{"id":"' . $id1 . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id2); - $resp2->appendBody('{"id":"' . $id2 . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp2->appendBody('{"id":"' . $id2 . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $mock->addResponse($resp1); $mock->addResponse($resp2); @@ -348,6 +348,13 @@ public function testUserTerminal(){ $this->assertTrue($user_terminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); } + public function testAction(){ + $toopher = new ToopherAPI('key', 'secret'); + $action = new Action(["id" => "1", "name" => "action"]); + $this->assertTrue($action->id == '1', 'bad action id'); + $this->assertTrue($action->name == 'action', 'bad action name'); + } + /** * @expectedException ToopherRequestException From e55e164fbb05c3921471c0dc4e2c2ea9d54f7004 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 14:07:02 -0600 Subject: [PATCH 020/114] Rename grant_with_otp to grantWithOtp to be consistent with other function names --- lib/toopher_api.php | 2 +- test/test_toopher_api.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 7dfd1fb..9766974 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -347,7 +347,7 @@ public function refreshFromServer() $this->update($result); } - public function grant_with_otp($otp, $kwargs = array()) + public function grantWithOtp($otp, $kwargs = array()) { $url = 'authentication_requests/' . $this->id . '/otp_auth'; $params = array('otp' => $otp); diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index a2028b3..9b8a22b 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -268,7 +268,7 @@ public function testGrantAuthenticationRequestWithOtp(){ $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); - $auth_request->grant_with_otp('otp'); + $auth_request->grantWithOtp('otp'); $this->assertTrue($auth_request->id == $id, 'wrong auth id'); $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); From 48c19dee57f85e071153669f28fd001f90f26074 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 14:55:21 -0600 Subject: [PATCH 021/114] Add Users.getById --- lib/toopher_api.php | 17 +++++++++++++++++ test/test_toopher_api.php | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 9766974..68ced52 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -370,6 +370,23 @@ private function update($json_response) } } +class Users +{ + protected $api; + + function __construct($api) + { + $this->api = $api; + } + + public function getById($userId) + { + $url = 'users/' . $userId; + $result = $this->api->advanced->raw->get($url); + return new User($result, $this->api); + } +} + class User { protected $api; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 9b8a22b..92b52a9 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -329,6 +329,27 @@ public function testRawGet(){ $this->assertTrue($auth_request['terminal']['name'] == 'another term name', 'wrong auth terminal name'); } + public function testUsersGetById(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp1->appendBody('{"id":"1","name":"paired user one","toopher_authentication_enabled":true}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/2'); + $resp2->appendBody('{"id":"2","name":"paired user two","toopher_authentication_enabled":false}'); + $mock->addResponse($resp1); + $mock->addResponse($resp2); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $user = $toopher->advanced->users->getById('1'); + $this->assertTrue($user->id == '1', 'wrong user id'); + $this->assertTrue($user->name == 'paired user one', 'wrong user name'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + + $user = $toopher->advanced->users->getById('2'); + $this->assertTrue($user->id == '2', 'wrong user id'); + $this->assertTrue($user->name == 'paired user two', 'wrong user name'); + $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication not enabled'); + } + public function testUser(){ $toopher = new ToopherAPI('key', 'secret'); $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); From 07a9bbe630dfabfed5b9457f2029a41b1c2ad4a4 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 15:29:17 -0600 Subject: [PATCH 022/114] Add Users.getByName --- lib/toopher_api.php | 14 ++++++++++++++ test/test_toopher_api.php | 13 +++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 68ced52..7538b45 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -113,6 +113,7 @@ function __construct($key, $secret, $baseUrl, $httpAdapter, $api) $this->raw = new ApiRawRequester($key, $secret, $baseUrl, $httpAdapter); $this->pairings = new Pairings($api); $this->authenticationRequests = new AuthenticationRequests($api); + $this->users = new Users($api); } } @@ -385,6 +386,19 @@ public function getById($userId) $result = $this->api->advanced->raw->get($url); return new User($result, $this->api); } + + public function getByName($username) + { + $url = 'users'; + $params = array('user_name' => $username); + $users = $this->api->advanced->raw->get($url, $params); + if (sizeof($users) > 1) { + throw new ToopherRequestException(sprintf("Multiple users with name = %s", $username)); + } elseif (empty ($users)) { + throw new ToopherRequestException(sprintf("No users with name = %s", $username)); + } + return new User(array_shift($users), $this->api); + } } class User diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 92b52a9..f667aa2 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -350,6 +350,19 @@ public function testUsersGetById(){ $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication not enabled'); } + public function testUsersGetByName(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); + $resp1->appendBody('[{"id":"1","name":"paired user","toopher_authentication_enabled":true}]'); + $mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $user = $toopher->advanced->users->getByName('paired user'); + $this->assertTrue($user->id == '1', 'wrong user id'); + $this->assertTrue($user->name == 'paired user', 'wrong user name'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + } + public function testUser(){ $toopher = new ToopherAPI('key', 'secret'); $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); From 325590bad900259d91faccca8aec6399d80418d1 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 15:38:10 -0600 Subject: [PATCH 023/114] Fix spacing --- lib/toopher_api.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 7538b45..73df3f3 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -24,7 +24,7 @@ class ToopherRequestException extends Exception { - + } class ToopherAPI @@ -185,7 +185,7 @@ private function request($method, $endpoint, $parameters = array()) $err = json_decode($resultBody, true); if ($err === NULL) { - $json_error = $this->json_error_to_string(json_last_error()); + $json_error = $this->json_error_to_string(json_last_error()); if (!empty($json_error)) { error_log(sprintf("Error parsing response body JSON: %s", $json_error)); error_log(sprintf("response body: %s", $result->getBody())); @@ -202,14 +202,14 @@ private function request($method, $endpoint, $parameters = array()) $decoded = json_decode($result->getBody(), true); if ($decoded === NULL) { - $json_error = $this->json_error_to_string(json_last_error()); + $json_error = $this->json_error_to_string(json_last_error()); if (!empty($json_error)) { error_log(sprintf("Error parsing response body JSON: %s", $json_error)); error_log(sprintf("response body: %s", $result->getBody())); throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $json_error)); } } - return $decoded; + return $decoded; } private function json_error_to_string($json_error_code) { From 3b73d343c9286483d98ec42fe128e05ba95f4ebc Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 17:05:04 -0600 Subject: [PATCH 024/114] Add Users.create --- lib/toopher_api.php | 9 +++++++++ test/test_toopher_api.php | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 73df3f3..a3f0125 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -399,6 +399,15 @@ public function getByName($username) } return new User(array_shift($users), $this->api); } + + public function create($username, $kwargs = array()) + { + $url = 'users/create'; + $params = array('name' => $username); + $params = array_merge($params, $kwargs); + $result = $this->api->advanced->raw->post($url, $params); + return new User($result, $this->api); + } } class User diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index f667aa2..6d28f3b 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -363,6 +363,32 @@ public function testUsersGetByName(){ $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); } + public function testUsersCreate(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); + $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); + $mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $user = $toopher->advanced->users->create('paired user'); + $this->assertTrue($user->id == '1', 'wrong user id'); + $this->assertTrue($user->name == 'paired user', 'wrong user name'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + } + + public function testUsersCreateWithExtras(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); + $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); + $mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $user = $toopher->advanced->users->create('paired user', array('foo'=>'bar')); + $this->assertTrue($user->id == '1', 'wrong user id'); + $this->assertTrue($user->name == 'paired user', 'wrong user name'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + } + public function testUser(){ $toopher = new ToopherAPI('key', 'secret'); $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); From 6e2fc44abaddda62f9f38218490d032723b0f09b Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 17:14:11 -0600 Subject: [PATCH 025/114] Add ToopherApi.AdvancedApiUsageFactory.UserTerminals --- lib/toopher_api.php | 18 ++++++++++++++++++ test/test_toopher_api.php | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index a3f0125..bf7e8da 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -114,6 +114,7 @@ function __construct($key, $secret, $baseUrl, $httpAdapter, $api) $this->pairings = new Pairings($api); $this->authenticationRequests = new AuthenticationRequests($api); $this->users = new Users($api); + $this->userTerminals = new UserTerminals($api); } } @@ -431,6 +432,23 @@ public function update($json_response) } } +class UserTerminals +{ + protected $api; + + function __construct($api) + { + $this->api = $api; + } + + public function getById($userTerminalId) + { + $url = 'user_terminals/' . $userTerminalId; + $result = $this->api->advanced->raw->get($url); + return new UserTerminal($result, $this->api); + } +} + class UserTerminal { protected $api; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 6d28f3b..f885bef 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -397,6 +397,33 @@ public function testUser(){ $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); } + public function testUserTerminalsGetById(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/2'); + $resp2->appendBody('{"id":"2", "name":"terminal two", "requester_specified_id": "requester specified id", "user":{"id":"2","name":"paired user two","toopher_authentication_enabled":true}}'); + $mock->addResponse($resp1); + $mock->addResponse($resp2); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $userTerminal = $toopher->advanced->userTerminals->getById('1'); + $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); + $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); + $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); + $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + + $userTerminal = $toopher->advanced->userTerminals->getById('2'); + $this->assertTrue($userTerminal->id == '2', 'wrong terminal id'); + $this->assertTrue($userTerminal->name == 'terminal two', 'wrong terminal name'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); + $this->assertTrue($userTerminal->user->id == '2', 'bad user id'); + $this->assertTrue($userTerminal->user->name == 'paired user two', 'bad user name'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + } + public function testUserTerminal(){ $toopher = new ToopherAPI('key', 'secret'); $user_terminal = new UserTerminal(["id" => "1", "name" => "user", "requester_specified_id" => "1", "user" => ["id" => "1","name" => "user", "toopher_authentication_enabled" => true]], $toopher); From f585e37924b3b4a1d144de271c5ae9743ebaf96a Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Feb 2015 17:24:04 -0600 Subject: [PATCH 026/114] Add UserTerminals.create --- lib/toopher_api.php | 13 +++++++++++++ test/test_toopher_api.php | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index bf7e8da..e86e4d7 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -447,6 +447,19 @@ public function getById($userTerminalId) $result = $this->api->advanced->raw->get($url); return new UserTerminal($result, $this->api); } + + public function create($username, $terminalName, $requesterSpecifiedId, $kwargs = array()) + { + $url = 'user_terminals/create'; + $params = array( + 'user_name' => $username, + 'name' => $terminalName, + 'name_extra' => $requesterSpecifiedId + ); + $params = array_merge($params, $kwargs); + $result = $this->api->advanced->raw->post($url, $params); + return new UserTerminal($result, $this->api); + } } class UserTerminal diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index f885bef..2869fa5 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -424,6 +424,39 @@ public function testUserTerminalsGetById(){ $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); } + public function testUserTerminalCreate(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); + $mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id'); + $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); + $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); + $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); + $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + } + + public function testUserTerminalCreateWithExtras(){ + $mock = new HTTP_Request2_Adapter_Mock(); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); + $mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $mock); + $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id', array('foo'=>'bar')); + $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); + $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); + $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); + $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + } + + public function testUserTerminal(){ $toopher = new ToopherAPI('key', 'secret'); $user_terminal = new UserTerminal(["id" => "1", "name" => "user", "requester_specified_id" => "1", "user" => ["id" => "1","name" => "user", "toopher_authentication_enabled" => true]], $toopher); From b900d00ef3dd07f55bbccef530851ef0fafb15ac Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 09:55:20 -0600 Subject: [PATCH 027/114] Add setUp to tests to create HTTP_Request2_Adapter_Mock --- test/test_toopher_api.php | 140 +++++++++++++++++--------------------- 1 file changed, 61 insertions(+), 79 deletions(-) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 2869fa5..cfec2f1 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -28,6 +28,11 @@ class ToopherAPITests extends PHPUnit_Framework_TestCase { protected $oauthParams = array('oauth_nonce' => 'nonce', 'oauth_timestamp' => '0'); + protected function setUp() + { + $this->mock = new HTTP_Request2_Adapter_Mock(); + } + /** * @expectedException InvalidArgumentException */ @@ -47,11 +52,10 @@ public function testCanCreateToopherApiWithArguments() { } public function testCreatePair(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); - $mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $this->mock->addResponse($resp); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -60,11 +64,10 @@ public function testCreatePair(){ } public function testCreateSmsPair(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); - $mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $this->mock->addResponse($resp); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); $pairing = $toopher->pair('user', '555-555-5555'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -73,11 +76,10 @@ public function testCreateSmsPair(){ } public function testCreateQrPair(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); - $mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $this->mock->addResponse($resp); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); $pairing = $toopher->pair('user'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -86,14 +88,13 @@ public function testCreateQrPair(){ } public function testGetPairingStatus(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"paired user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); $resp2->appendBody('{"id":"2","enabled":false, "pending":false, "user":{"id":"2","name":"unpaired user", "toopher_authentication_enabled":"true"}}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $pairing = $toopher->advanced->pairings->getById('1'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); @@ -109,14 +110,13 @@ public function testGetPairingStatus(){ } public function testPairingRefreshFromServer(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); $resp1->appendBody('{"id":"1","enabled":false, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); $resp2->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":"true"}}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', 'pairing phrase'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); @@ -132,14 +132,13 @@ public function testPairingRefreshFromServer(){ } public function testGetPairingResetLink(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); $resp2->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -151,13 +150,12 @@ public function testGetPairingResetLink(){ } public function testEmailPairingResetLink(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock, $this->oauthParams); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -174,12 +172,11 @@ public function testEmailPairingResetLink(){ public function testCreateAuthenticationWithNoAction(){ $id = Uuid::uuid4()->toString(); - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $mock->addResponse($resp1); + $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $auth_request = $toopher->authenticate($id, 'term name'); $this->assertTrue($auth_request->id == $id, 'wrong auth id'); $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); @@ -191,15 +188,14 @@ public function testCreateAuthenticationWithNoAction(){ } public function testGetAuthenticationStatus(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp1->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/2'); $resp2->appendBody('{"id":"2","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $auth_request = $toopher->advanced->authenticationRequests->getById('1'); $this->assertTrue($auth_request->id == '1', 'wrong auth id'); $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); @@ -220,15 +216,14 @@ public function testGetAuthenticationStatus(){ } public function testAuthenticationRequestRefreshFromServer(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp1->appendBody('{"id":"1","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp2->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $auth_request = $toopher->authenticate('user', 'term name extra'); $this->assertTrue($auth_request->id == '1', 'wrong auth id'); $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); @@ -250,15 +245,14 @@ public function testAuthenticationRequestRefreshFromServer(){ public function testGrantAuthenticationRequestWithOtp(){ $id = Uuid::uuid4()->toString(); - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp1->appendBody('{"id":"' . $id . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp2->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $auth_request = $toopher->authenticate($id, 'term name'); $this->assertTrue($auth_request->id == $id, 'wrong auth id'); $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); @@ -280,12 +274,11 @@ public function testGrantAuthenticationRequestWithOtp(){ public function testRawPost(){ $id = Uuid::uuid4()->toString(); - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $mock->addResponse($resp1); + $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $params = array('pairing_id' => $id, 'terminal_name' => 'term name'); $auth_request = $toopher->advanced->raw->post('authentication_requests/initiate', $params); $this->assertTrue($auth_request['id'] == $id, 'wrong auth id'); @@ -301,15 +294,14 @@ public function testRawPost(){ public function testRawGet(){ $id1 = Uuid::uuid4()->toString(); $id2 = Uuid::uuid4()->toString(); - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id1); $resp1->appendBody('{"id":"' . $id1 . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id2); $resp2->appendBody('{"id":"' . $id2 . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $auth_request = $toopher->advanced->raw->get('authentication_requests/' . $id1); $this->assertTrue($auth_request['id'] == $id1, 'wrong auth id'); $this->assertTrue($auth_request['pending'] == false, 'wrong auth pending'); @@ -330,15 +322,14 @@ public function testRawGet(){ } public function testUsersGetById(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); $resp1->appendBody('{"id":"1","name":"paired user one","toopher_authentication_enabled":true}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/2'); $resp2->appendBody('{"id":"2","name":"paired user two","toopher_authentication_enabled":false}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $user = $toopher->advanced->users->getById('1'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user one', 'wrong user name'); @@ -351,12 +342,11 @@ public function testUsersGetById(){ } public function testUsersGetByName(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); $resp1->appendBody('[{"id":"1","name":"paired user","toopher_authentication_enabled":true}]'); - $mock->addResponse($resp1); + $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $user = $toopher->advanced->users->getByName('paired user'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); @@ -364,12 +354,11 @@ public function testUsersGetByName(){ } public function testUsersCreate(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); - $mock->addResponse($resp1); + $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $user = $toopher->advanced->users->create('paired user'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); @@ -377,12 +366,11 @@ public function testUsersCreate(){ } public function testUsersCreateWithExtras(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); - $mock->addResponse($resp1); + $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $user = $toopher->advanced->users->create('paired user', array('foo'=>'bar')); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); @@ -398,15 +386,14 @@ public function testUser(){ } public function testUserTerminalsGetById(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/2'); $resp2->appendBody('{"id":"2", "name":"terminal two", "requester_specified_id": "requester specified id", "user":{"id":"2","name":"paired user two","toopher_authentication_enabled":true}}'); - $mock->addResponse($resp1); - $mock->addResponse($resp2); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->getById('1'); $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); @@ -425,12 +412,11 @@ public function testUserTerminalsGetById(){ } public function testUserTerminalCreate(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); - $mock->addResponse($resp1); + $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id'); $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); @@ -441,12 +427,11 @@ public function testUserTerminalCreate(){ } public function testUserTerminalCreateWithExtras(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); - $mock->addResponse($resp1); + $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id', array('foo'=>'bar')); $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); @@ -480,13 +465,12 @@ public function testAction(){ * @expectedException ToopherRequestException */ public function testToopherRequestException(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 401 Unauthorized", false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp1->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); - $mock->addResponse($resp1); + $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } @@ -502,10 +486,9 @@ public function testToopherVersionStringExists() { * @expectedException ToopherRequestException */ public function test400WithEmptyBodyRaisesToopherRequestException(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $this->mock->addResponse($resp1); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } @@ -513,11 +496,10 @@ public function test400WithEmptyBodyRaisesToopherRequestException(){ * @expectedException ToopherRequestException */ public function test400WithUnprintableBodyRaisesToopherRequestException(){ - $mock = new HTTP_Request2_Adapter_Mock(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp1->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); - $mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $mock); + $this->mock->addResponse($resp1); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } } From a85265ed066cc6456c130e827b581badea5976dd Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 11:03:13 -0600 Subject: [PATCH 028/114] Cleanup tests --- test/test_toopher_api.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index cfec2f1..3294807 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -55,7 +55,7 @@ public function testCreatePair(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -67,7 +67,7 @@ public function testCreateSmsPair(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', '555-555-5555'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -79,7 +79,7 @@ public function testCreateQrPair(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -138,7 +138,7 @@ public function testGetPairingResetLink(){ $resp2->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -155,7 +155,7 @@ public function testEmailPairingResetLink(){ $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock, $this->oauthParams); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); From a5760925f860bfa10867c1cce863e10d55df1679 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 11:56:29 -0600 Subject: [PATCH 029/114] Add Pairing.getQrCodeImage --- lib/toopher_api.php | 41 +++++++++++++++++++++++++++++---------- test/test_toopher_api.php | 13 +++++++++++++ 2 files changed, 44 insertions(+), 10 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index e86e4d7..4f79ce1 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -140,6 +140,11 @@ function __construct($key, $secret, $baseUrl, $httpAdapter) $this->httpAdapter = (!is_null($httpAdapter)) ? $httpAdapter : new HTTP_Request2_Adapter_Curl(); } + public function getOauthConsumer() + { + return $this->oauthConsumer; + } + public function post($endpoint, $parameters) { return $this->request('POST', $endpoint, $parameters); @@ -150,7 +155,12 @@ public function get($endpoint) return $this->request('GET', $endpoint); } - private function request($method, $endpoint, $parameters = array()) + public function get_raw($endpoint) + { + return $this->request('GET', $endpoint, array(), true); + } + + private function request($method, $endpoint, $parameters = array(), $raw_request = false) { $req = new HTTP_Request2(); $req->setAdapter($this->httpAdapter); @@ -201,16 +211,21 @@ private function request($method, $endpoint, $parameters = array()) } } - $decoded = json_decode($result->getBody(), true); - if ($decoded === NULL) { - $json_error = $this->json_error_to_string(json_last_error()); - if (!empty($json_error)) { - error_log(sprintf("Error parsing response body JSON: %s", $json_error)); - error_log(sprintf("response body: %s", $result->getBody())); - throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $json_error)); - } + if ($raw_request) + { + return $result->getBody(); + } else { + $decoded = json_decode($result->getBody(), true); + if ($decoded === NULL) { + $json_error = $this->json_error_to_string(json_last_error()); + if (!empty($json_error)) { + error_log(sprintf("Error parsing response body JSON: %s", $json_error)); + error_log(sprintf("response body: %s", $result->getBody())); + throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $json_error)); + } + } + return $decoded; } - return $decoded; } private function json_error_to_string($json_error_code) { @@ -296,6 +311,12 @@ public function emailResetLink($email, $kwargs = array()) $this->api->advanced->raw->post($url, $params); } + public function getQrCodeImage() + { + $url = 'qr/pairings/' . $this->id; + return $this->api->advanced->raw->get_raw($url); + } + private function update($json_response) { $this->enabled = $json_response['enabled']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 3294807..7cca4a7 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -170,6 +170,19 @@ public function testEmailPairingResetLink(){ } } + public function testPairingGetQrCodeImage(){ + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); + $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/qr/pairings/1'); + $resp2->appendBody('{}'); + $this->mock->addResponse($resp1); + $this->mock->addResponse($resp2); + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $pairing = $toopher->pair('user'); + $qr_image = $pairing->getQrCodeImage(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "last called method should be 'GET'"); + } + public function testCreateAuthenticationWithNoAction(){ $id = Uuid::uuid4()->toString(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); From 19b630478ea84bcedec43af88e06db4a64635543 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 12:57:50 -0600 Subject: [PATCH 030/114] Add ToopherObjectFactory for Users, UserTerminals, AuthenticationRequests and Pairings --- lib/toopher_api.php | 48 +++++++++++++-------------------------------- 1 file changed, 14 insertions(+), 34 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 4f79ce1..7f98ef0 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -106,6 +106,16 @@ public function authenticate($id_or_username, $terminal, $actionName = '', $kwar } } +abstract class ToopherObjectFactory +{ + protected $api; + + function __construct($api) + { + $this->api = $api; + } +} + class AdvancedApiUsageFactory { function __construct($key, $secret, $baseUrl, $httpAdapter, $api) @@ -248,16 +258,8 @@ private function json_error_to_string($json_error_code) { } } -class Pairings +class Pairings extends ToopherObjectFactory { - protected $api; - - function __construct($api) - { - $this->api = $api; - } - - public function getById($pairingId) { $url = 'pairings/' . $pairingId; @@ -326,16 +328,8 @@ private function update($json_response) } } -class AuthenticationRequests +class AuthenticationRequests extends ToopherObjectFactory { - protected $api; - - function __construct($api) - { - $this->api = $api; - } - - public function getById($authenticationRequestId) { $url = 'authentication_requests/' . $authenticationRequestId; @@ -393,15 +387,8 @@ private function update($json_response) } } -class Users +class Users extends ToopherObjectFactory { - protected $api; - - function __construct($api) - { - $this->api = $api; - } - public function getById($userId) { $url = 'users/' . $userId; @@ -453,15 +440,8 @@ public function update($json_response) } } -class UserTerminals +class UserTerminals extends ToopherObjectFactory { - protected $api; - - function __construct($api) - { - $this->api = $api; - } - public function getById($userTerminalId) { $url = 'user_terminals/' . $userTerminalId; From 3b7b365fa4666b095c0b8c7376b41aaa6216997f Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 12:59:25 -0600 Subject: [PATCH 031/114] Reorder classes --- lib/toopher_api.php | 130 ++++++++++++++++++++++---------------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 7f98ef0..cab6f80 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -268,6 +268,71 @@ public function getById($pairingId) } } +class AuthenticationRequests extends ToopherObjectFactory +{ + public function getById($authenticationRequestId) + { + $url = 'authentication_requests/' . $authenticationRequestId; + $result = $this->api->advanced->raw->get($url); + return new AuthenticationRequest($result, $this->api); + } +} + +class Users extends ToopherObjectFactory +{ + public function getById($userId) + { + $url = 'users/' . $userId; + $result = $this->api->advanced->raw->get($url); + return new User($result, $this->api); + } + + public function getByName($username) + { + $url = 'users'; + $params = array('user_name' => $username); + $users = $this->api->advanced->raw->get($url, $params); + if (sizeof($users) > 1) { + throw new ToopherRequestException(sprintf("Multiple users with name = %s", $username)); + } elseif (empty ($users)) { + throw new ToopherRequestException(sprintf("No users with name = %s", $username)); + } + return new User(array_shift($users), $this->api); + } + + public function create($username, $kwargs = array()) + { + $url = 'users/create'; + $params = array('name' => $username); + $params = array_merge($params, $kwargs); + $result = $this->api->advanced->raw->post($url, $params); + return new User($result, $this->api); + } +} + +class UserTerminals extends ToopherObjectFactory +{ + public function getById($userTerminalId) + { + $url = 'user_terminals/' . $userTerminalId; + $result = $this->api->advanced->raw->get($url); + return new UserTerminal($result, $this->api); + } + + public function create($username, $terminalName, $requesterSpecifiedId, $kwargs = array()) + { + $url = 'user_terminals/create'; + $params = array( + 'user_name' => $username, + 'name' => $terminalName, + 'name_extra' => $requesterSpecifiedId + ); + $params = array_merge($params, $kwargs); + $result = $this->api->advanced->raw->post($url, $params); + return new UserTerminal($result, $this->api); + } +} + class Pairing { protected $api; @@ -328,16 +393,6 @@ private function update($json_response) } } -class AuthenticationRequests extends ToopherObjectFactory -{ - public function getById($authenticationRequestId) - { - $url = 'authentication_requests/' . $authenticationRequestId; - $result = $this->api->advanced->raw->get($url); - return new AuthenticationRequest($result, $this->api); - } -} - class AuthenticationRequest { protected $api; @@ -387,38 +442,6 @@ private function update($json_response) } } -class Users extends ToopherObjectFactory -{ - public function getById($userId) - { - $url = 'users/' . $userId; - $result = $this->api->advanced->raw->get($url); - return new User($result, $this->api); - } - - public function getByName($username) - { - $url = 'users'; - $params = array('user_name' => $username); - $users = $this->api->advanced->raw->get($url, $params); - if (sizeof($users) > 1) { - throw new ToopherRequestException(sprintf("Multiple users with name = %s", $username)); - } elseif (empty ($users)) { - throw new ToopherRequestException(sprintf("No users with name = %s", $username)); - } - return new User(array_shift($users), $this->api); - } - - public function create($username, $kwargs = array()) - { - $url = 'users/create'; - $params = array('name' => $username); - $params = array_merge($params, $kwargs); - $result = $this->api->advanced->raw->post($url, $params); - return new User($result, $this->api); - } -} - class User { protected $api; @@ -440,29 +463,6 @@ public function update($json_response) } } -class UserTerminals extends ToopherObjectFactory -{ - public function getById($userTerminalId) - { - $url = 'user_terminals/' . $userTerminalId; - $result = $this->api->advanced->raw->get($url); - return new UserTerminal($result, $this->api); - } - - public function create($username, $terminalName, $requesterSpecifiedId, $kwargs = array()) - { - $url = 'user_terminals/create'; - $params = array( - 'user_name' => $username, - 'name' => $terminalName, - 'name_extra' => $requesterSpecifiedId - ); - $params = array_merge($params, $kwargs); - $result = $this->api->advanced->raw->post($url, $params); - return new UserTerminal($result, $this->api); - } -} - class UserTerminal { protected $api; From 8652e313a871d537a38248245f3f1dca1c9ad391 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 13:54:28 -0600 Subject: [PATCH 032/114] Add User.refreshFromServer --- lib/toopher_api.php | 7 +++++++ test/test_toopher_api.php | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index cab6f80..18dc829 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -455,6 +455,13 @@ function __construct($json_response, $api) $this->raw_response = $json_response; } + public function refreshFromServer() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + public function update($json_response) { $this->name = $json_response['name']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 7cca4a7..a835296 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -398,6 +398,23 @@ public function testUser(){ $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); } + public function testUserRefreshFromServer(){ + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp1->appendBody('{"id":"1","name":"user changed","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => false], $toopher); + $this->assertTrue($user->id == '1', 'bad user id'); + $this->assertTrue($user->name == 'user', 'bad user name'); + $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); + + $user->refreshFromServer(); + $this->assertTrue($user->id == '1', 'bad user id'); + $this->assertTrue($user->name == 'user changed', 'bad user name'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + } + public function testUserTerminalsGetById(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); From b8a5826734b2fe42c8f86f36ba00aff661e8013d Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 13:54:51 -0600 Subject: [PATCH 033/114] Add User.enableToopherAuthentication --- lib/toopher_api.php | 7 +++++++ test/test_toopher_api.php | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 18dc829..fdfbc1a 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -462,6 +462,13 @@ public function refreshFromServer() $this->update($result); } + public function enableToopherAuthentication() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "true")); + $this->update($result); + } + public function update($json_response) { $this->name = $json_response['name']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index a835296..e97c34c 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -415,6 +415,21 @@ public function testUserRefreshFromServer(){ $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } + public function testUserEnableToopherAuthentication(){ + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => false], $toopher); + $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); + + $user->enableToopherAuthentication(); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == "toopher_authentication_enabled=true", 'post params were incorrect'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "last called method should be 'POST'"); + } + public function testUserTerminalsGetById(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); From 338c484117c0ae32988b54c712bf0c88eb8cb0cb Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 13:55:10 -0600 Subject: [PATCH 034/114] Cleanup test assertion messages --- test/test_toopher_api.php | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index e97c34c..31ecf71 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -346,12 +346,12 @@ public function testUsersGetById(){ $user = $toopher->advanced->users->getById('1'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user one', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); $user = $toopher->advanced->users->getById('2'); $this->assertTrue($user->id == '2', 'wrong user id'); $this->assertTrue($user->name == 'paired user two', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication not enabled'); + $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); } public function testUsersGetByName(){ @@ -363,7 +363,7 @@ public function testUsersGetByName(){ $user = $toopher->advanced->users->getByName('paired user'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testUsersCreate(){ @@ -375,7 +375,7 @@ public function testUsersCreate(){ $user = $toopher->advanced->users->create('paired user'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testUsersCreateWithExtras(){ @@ -387,7 +387,7 @@ public function testUsersCreateWithExtras(){ $user = $toopher->advanced->users->create('paired user', array('foo'=>'bar')); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testUser(){ @@ -395,7 +395,7 @@ public function testUser(){ $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); $this->assertTrue($user->id == '1', 'bad user id'); $this->assertTrue($user->name == 'user', 'bad user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testUserRefreshFromServer(){ @@ -445,7 +445,7 @@ public function testUserTerminalsGetById(){ $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); $userTerminal = $toopher->advanced->userTerminals->getById('2'); $this->assertTrue($userTerminal->id == '2', 'wrong terminal id'); @@ -453,7 +453,7 @@ public function testUserTerminalsGetById(){ $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); $this->assertTrue($userTerminal->user->id == '2', 'bad user id'); $this->assertTrue($userTerminal->user->name == 'paired user two', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testUserTerminalCreate(){ @@ -468,7 +468,7 @@ public function testUserTerminalCreate(){ $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testUserTerminalCreateWithExtras(){ @@ -483,7 +483,7 @@ public function testUserTerminalCreateWithExtras(){ $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } @@ -495,7 +495,7 @@ public function testUserTerminal(){ $this->assertTrue($user_terminal->requester_specified_id == '1', 'bad user terminal requester specified is'); $this->assertTrue($user_terminal->user->id == '1', 'bad user id'); $this->assertTrue($user_terminal->user->name == 'user', 'bad user name'); - $this->assertTrue($user_terminal->user->toopher_authentication_enabled == true, 'toopher authentication not enabled'); + $this->assertTrue($user_terminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testAction(){ From af9c1a3318f19f4e3e11ffb15123296a7d6e02ee Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 14:01:54 -0600 Subject: [PATCH 035/114] Add User.disableToopherAuthentication --- lib/toopher_api.php | 7 +++++++ test/test_toopher_api.php | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index fdfbc1a..67e12f1 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -469,6 +469,13 @@ public function enableToopherAuthentication() $this->update($result); } + public function disableToopherAuthentication() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "false")); + $this->update($result); + } + public function update($json_response) { $this->name = $json_response['name']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 31ecf71..09a5e07 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -430,6 +430,21 @@ public function testUserEnableToopherAuthentication(){ $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "last called method should be 'POST'"); } + public function testUserDisableToopherAuthentication(){ + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":false}'); + $this->mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + + $user->disableToopherAuthentication(); + $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == "toopher_authentication_enabled=false", 'post params were incorrect'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "last called method should be 'POST'"); + } + public function testUserTerminalsGetById(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); From 3cd8aac7da102d1c02505bb3c790d8693b66b191 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 15:43:29 -0600 Subject: [PATCH 036/114] Add ToopherAPITests.compareToDefaultUserTerminal --- test/test_toopher_api.php | 51 +++++++++++++++------------------------ 1 file changed, 20 insertions(+), 31 deletions(-) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 09a5e07..fd310df 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -33,6 +33,16 @@ protected function setUp() $this->mock = new HTTP_Request2_Adapter_Mock(); } + public function compareToDefaultUserTerminal($userTerminal) + { + $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); + $this->assertTrue($userTerminal->name == 'terminal name', 'wrong terminal name'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); + $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); + $this->assertTrue($userTerminal->user->name == 'user name', 'bad user name'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + } + /** * @expectedException InvalidArgumentException */ @@ -447,7 +457,7 @@ public function testUserDisableToopherAuthentication(){ public function testUserTerminalsGetById(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); - $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); + $resp1->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/2'); $resp2->appendBody('{"id":"2", "name":"terminal two", "requester_specified_id": "requester specified id", "user":{"id":"2","name":"paired user two","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp1); @@ -455,12 +465,7 @@ public function testUserTerminalsGetById(){ $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->getById('1'); - $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); - $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); - $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); - $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); - $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->compareToDefaultUserTerminal($userTerminal); $userTerminal = $toopher->advanced->userTerminals->getById('2'); $this->assertTrue($userTerminal->id == '2', 'wrong terminal id'); @@ -472,45 +477,29 @@ public function testUserTerminalsGetById(){ } public function testUserTerminalCreate(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); - $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); + $resp1->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id'); - $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); - $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); - $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); - $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); - $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->compareToDefaultUserTerminal($userTerminal); } public function testUserTerminalCreateWithExtras(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); - $resp1->appendBody('{"id":"1", "name":"terminal one", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"paired user one","toopher_authentication_enabled":true}}'); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); + $resp1->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp1); $toopher = new ToopherAPI('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id', array('foo'=>'bar')); - $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); - $this->assertTrue($userTerminal->name == 'terminal one', 'wrong terminal name'); - $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); - $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); - $this->assertTrue($userTerminal->user->name == 'paired user one', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->compareToDefaultUserTerminal($userTerminal); } - public function testUserTerminal(){ $toopher = new ToopherAPI('key', 'secret'); - $user_terminal = new UserTerminal(["id" => "1", "name" => "user", "requester_specified_id" => "1", "user" => ["id" => "1","name" => "user", "toopher_authentication_enabled" => true]], $toopher); - $this->assertTrue($user_terminal->id == '1', 'bad user terminal id'); - $this->assertTrue($user_terminal->name == 'user', 'bad user terminal name'); - $this->assertTrue($user_terminal->requester_specified_id == '1', 'bad user terminal requester specified is'); - $this->assertTrue($user_terminal->user->id == '1', 'bad user id'); - $this->assertTrue($user_terminal->user->name == 'user', 'bad user name'); - $this->assertTrue($user_terminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $userTerminal = new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name", "toopher_authentication_enabled" => true]], $toopher); + $this->compareToDefaultUserTerminal($userTerminal); } public function testAction(){ From 46474963e8e74960bb8d5fc854401aa4a9d3ee80 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 15:49:44 -0600 Subject: [PATCH 037/114] Cleanup HTTP_Request2_Response URLs --- test/test_toopher_api.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index fd310df..5051ef4 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -100,7 +100,7 @@ public function testCreateQrPair(){ public function testGetPairingStatus(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"paired user", "toopher_authentication_enabled":"true"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/2'); $resp2->appendBody('{"id":"2","enabled":false, "pending":false, "user":{"id":"2","name":"unpaired user", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); @@ -270,7 +270,7 @@ public function testGrantAuthenticationRequestWithOtp(){ $id = Uuid::uuid4()->toString(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp1->appendBody('{"id":"' . $id . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id . '/otp_auth'); $resp2->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); @@ -377,7 +377,7 @@ public function testUsersGetByName(){ } public function testUsersCreate(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp1); @@ -389,7 +389,7 @@ public function testUsersCreate(){ } public function testUsersCreateWithExtras(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp1); From c5d4566e0fe0113fba598df916662f2c56c859a5 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 15:53:09 -0600 Subject: [PATCH 038/114] Refactor ApiRawRequester.request --- lib/toopher_api.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 67e12f1..98d1673 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -195,10 +195,10 @@ private function request($method, $endpoint, $parameters = array(), $raw_request throw new ToopherRequestException("Error making Toopher API request", $e->getCode(), $e); } + $resultBody = $result->getBody(); if ($result->getStatus() != 200) { error_log(sprintf("Toopher API call returned unexpected HTTP response: %d - %s", $result->getStatus(), $result->getReasonPhrase())); - $resultBody = $result->getBody(); if (empty($resultBody)) { error_log("empty response body"); throw new ToopherRequestException($result->getReasonPhrase(), $result->getStatus()); @@ -223,9 +223,9 @@ private function request($method, $endpoint, $parameters = array(), $raw_request if ($raw_request) { - return $result->getBody(); + return $resultBody; } else { - $decoded = json_decode($result->getBody(), true); + $decoded = json_decode($resultBody, true); if ($decoded === NULL) { $json_error = $this->json_error_to_string(json_last_error()); if (!empty($json_error)) { From f8bafe1fef746fdf04e1cb2f434fbb69e5b78c74 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 15:53:26 -0600 Subject: [PATCH 039/114] Add UserTerminal.refreshFromServer --- lib/toopher_api.php | 7 +++++++ test/test_toopher_api.php | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 98d1673..8ce629c 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -497,6 +497,13 @@ function __construct($json_response, $api) $this->raw_response = $json_response; } + public function refreshFromServer() + { + $url = 'user_terminals/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + public function update($json_response) { $this->name = $json_response['name']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 5051ef4..cca9caa 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -496,6 +496,24 @@ public function testUserTerminalCreateWithExtras(){ $this->compareToDefaultUserTerminal($userTerminal); } + public function testUserTerminalRefreshFromServer(){ + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp1->appendBody('{"id":"1", "name":"terminal name changed", "requester_specified_id":"requester specified id changed", "user":{"id":"1", "name":"user name changed", "toopher_authentication_enabled":false}}'); + $this->mock->addResponse($resp1); + + $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $userTerminal = new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name","toopher_authentication_enabled" => true]], $toopher); + $this->compareToDefaultUserTerminal($userTerminal); + + // $userTerminal->refreshFromServer(); + // $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); + // $this->assertTrue($userTerminal->name == 'terminal name changed', 'wrong terminal name'); + // $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id changed', 'wrong requester specified id'); + // $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); + // $this->assertTrue($userTerminal->user->name == 'user name changed', 'bad user name'); + // $this->assertTrue($userTerminal->user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); + } + public function testUserTerminal(){ $toopher = new ToopherAPI('key', 'secret'); $userTerminal = new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name", "toopher_authentication_enabled" => true]], $toopher); From 1090187c0e445af1a61bf9c70623741dc793981f Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Feb 2015 15:57:07 -0600 Subject: [PATCH 040/114] Rename ToopherAPI to ToopherApi --- README.md | 6 ++-- demo/toopher_demo.php | 2 +- lib/toopher_api.php | 4 +-- test/test_toopher_api.php | 74 +++++++++++++++++++-------------------- 4 files changed, 43 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 0e13260..e551220 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# ToopherAPI PHP Client +# ToopherApi PHP Client [![Build Status](https://travis-ci.org/toopher/toopher-php.png?branch=master)](https://travis-ci.org/toopher/toopher-php) #### Introduction -ToopherAPI PHP Client simplifies the task of interfacing with the Toopher API from PHP code. This project includes all the dependency libraries and handles the required OAuth and JSON functionality so you can focus on just using the API. +ToopherApi PHP Client simplifies the task of interfacing with the Toopher API from PHP code. This project includes all the dependency libraries and handles the required OAuth and JSON functionality so you can focus on just using the API. #### Learn the Toopher API Make sure you visit [http://dev.toopher.com](http://dev.toopher.com) to get acquainted with the Toopher API fundamentals. The documentation there will tell you the details about the operations this API wrapper library provides. @@ -29,7 +29,7 @@ This library makes it super simple to do the Toopher two-step. Check it out: require_once("toopher_api.php"); // Create an API object using your credentials -$toopherApi = new ToopherAPI($key, $secret); +$toopherApi = new ToopherApi($key, $secret); // Step 1 - Pair with their phone's Toopher app $pairing = $toopherApi->pair("pairing phrase", "username@yourservice.com"); diff --git a/demo/toopher_demo.php b/demo/toopher_demo.php index 367c5a4..bbccc5e 100644 --- a/demo/toopher_demo.php +++ b/demo/toopher_demo.php @@ -37,7 +37,7 @@ } echo ("using key=$key, secret=$secret\n"); -$toopher = new ToopherAPI($key, $secret); +$toopher = new ToopherApi($key, $secret); echo("\nSTEP 1: Pair device\n"); echo("enter pairing phrase:"); diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 8ce629c..8ca96f8 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -27,7 +27,7 @@ class ToopherRequestException extends Exception } -class ToopherAPI +class ToopherApi { const VERSION = '1.0.6'; @@ -175,7 +175,7 @@ private function request($method, $endpoint, $parameters = array(), $raw_request $req = new HTTP_Request2(); $req->setAdapter($this->httpAdapter); $req->setHeader(array('User-Agent' => - sprintf('Toopher-PHP/%s (PHP %s)', ToopherAPI::VERSION, phpversion()))); + sprintf('Toopher-PHP/%s (PHP %s)', ToopherApi::VERSION, phpversion()))); $req->setMethod($method); $req->setUrl($this->baseUrl . $endpoint); if(!is_null($parameters)) diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index cca9caa..960e445 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -24,7 +24,7 @@ require_once("bootstrap.php"); use Rhumsaa\Uuid\Uuid; -class ToopherAPITests extends PHPUnit_Framework_TestCase { +class ToopherApiTests extends PHPUnit_Framework_TestCase { protected $oauthParams = array('oauth_nonce' => 'nonce', 'oauth_timestamp' => '0'); @@ -47,25 +47,25 @@ public function compareToDefaultUserTerminal($userTerminal) * @expectedException InvalidArgumentException */ public function testEmptyKeyThrowsException() { - $toopher = new ToopherAPI('', 'secret'); + $toopher = new ToopherApi('', 'secret'); } /** * @expectedException InvalidArgumentException */ public function testEmptySecretThrowsException() { - $toopher = new ToopherAPI('key', ''); + $toopher = new ToopherApi('key', ''); } public function testCanCreateToopherApiWithArguments() { - $toopher = new ToopherAPI('key', 'secret'); + $toopher = new ToopherApi('key', 'secret'); } public function testCreatePair(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -77,7 +77,7 @@ public function testCreateSmsPair(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', '555-555-5555'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -89,7 +89,7 @@ public function testCreateQrPair(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -104,7 +104,7 @@ public function testGetPairingStatus(){ $resp2->appendBody('{"id":"2","enabled":false, "pending":false, "user":{"id":"2","name":"unpaired user", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $pairing = $toopher->advanced->pairings->getById('1'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); @@ -126,7 +126,7 @@ public function testPairingRefreshFromServer(){ $resp2->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":"true"}}'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', 'pairing phrase'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); @@ -148,7 +148,7 @@ public function testGetPairingResetLink(){ $resp2->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -165,7 +165,7 @@ public function testEmailPairingResetLink(){ $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user', 'immediate_pair'); $this->assertTrue($pairing->id == '1', 'bad pairing id'); $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); @@ -187,7 +187,7 @@ public function testPairingGetQrCodeImage(){ $resp2->appendBody('{}'); $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $pairing = $toopher->pair('user'); $qr_image = $pairing->getQrCodeImage(); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "last called method should be 'GET'"); @@ -199,7 +199,7 @@ public function testCreateAuthenticationWithNoAction(){ $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $auth_request = $toopher->authenticate($id, 'term name'); $this->assertTrue($auth_request->id == $id, 'wrong auth id'); $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); @@ -218,7 +218,7 @@ public function testGetAuthenticationStatus(){ $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $auth_request = $toopher->advanced->authenticationRequests->getById('1'); $this->assertTrue($auth_request->id == '1', 'wrong auth id'); $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); @@ -246,7 +246,7 @@ public function testAuthenticationRequestRefreshFromServer(){ $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $auth_request = $toopher->authenticate('user', 'term name extra'); $this->assertTrue($auth_request->id == '1', 'wrong auth id'); $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); @@ -275,7 +275,7 @@ public function testGrantAuthenticationRequestWithOtp(){ $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $auth_request = $toopher->authenticate($id, 'term name'); $this->assertTrue($auth_request->id == $id, 'wrong auth id'); $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); @@ -301,7 +301,7 @@ public function testRawPost(){ $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $params = array('pairing_id' => $id, 'terminal_name' => 'term name'); $auth_request = $toopher->advanced->raw->post('authentication_requests/initiate', $params); $this->assertTrue($auth_request['id'] == $id, 'wrong auth id'); @@ -324,7 +324,7 @@ public function testRawGet(){ $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $auth_request = $toopher->advanced->raw->get('authentication_requests/' . $id1); $this->assertTrue($auth_request['id'] == $id1, 'wrong auth id'); $this->assertTrue($auth_request['pending'] == false, 'wrong auth pending'); @@ -352,7 +352,7 @@ public function testUsersGetById(){ $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $user = $toopher->advanced->users->getById('1'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user one', 'wrong user name'); @@ -369,7 +369,7 @@ public function testUsersGetByName(){ $resp1->appendBody('[{"id":"1","name":"paired user","toopher_authentication_enabled":true}]'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $user = $toopher->advanced->users->getByName('paired user'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); @@ -381,7 +381,7 @@ public function testUsersCreate(){ $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $user = $toopher->advanced->users->create('paired user'); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); @@ -393,7 +393,7 @@ public function testUsersCreateWithExtras(){ $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $user = $toopher->advanced->users->create('paired user', array('foo'=>'bar')); $this->assertTrue($user->id == '1', 'wrong user id'); $this->assertTrue($user->name == 'paired user', 'wrong user name'); @@ -401,7 +401,7 @@ public function testUsersCreateWithExtras(){ } public function testUser(){ - $toopher = new ToopherAPI('key', 'secret'); + $toopher = new ToopherApi('key', 'secret'); $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); $this->assertTrue($user->id == '1', 'bad user id'); $this->assertTrue($user->name == 'user', 'bad user name'); @@ -413,7 +413,7 @@ public function testUserRefreshFromServer(){ $resp1->appendBody('{"id":"1","name":"user changed","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => false], $toopher); $this->assertTrue($user->id == '1', 'bad user id'); $this->assertTrue($user->name == 'user', 'bad user name'); @@ -430,7 +430,7 @@ public function testUserEnableToopherAuthentication(){ $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => false], $toopher); $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); @@ -445,7 +445,7 @@ public function testUserDisableToopherAuthentication(){ $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":false}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); @@ -463,7 +463,7 @@ public function testUserTerminalsGetById(){ $this->mock->addResponse($resp1); $this->mock->addResponse($resp2); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->getById('1'); $this->compareToDefaultUserTerminal($userTerminal); @@ -481,7 +481,7 @@ public function testUserTerminalCreate(){ $resp1->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id'); $this->compareToDefaultUserTerminal($userTerminal); } @@ -491,7 +491,7 @@ public function testUserTerminalCreateWithExtras(){ $resp1->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id', array('foo'=>'bar')); $this->compareToDefaultUserTerminal($userTerminal); } @@ -501,7 +501,7 @@ public function testUserTerminalRefreshFromServer(){ $resp1->appendBody('{"id":"1", "name":"terminal name changed", "requester_specified_id":"requester specified id changed", "user":{"id":"1", "name":"user name changed", "toopher_authentication_enabled":false}}'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $userTerminal = new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name","toopher_authentication_enabled" => true]], $toopher); $this->compareToDefaultUserTerminal($userTerminal); @@ -515,13 +515,13 @@ public function testUserTerminalRefreshFromServer(){ } public function testUserTerminal(){ - $toopher = new ToopherAPI('key', 'secret'); + $toopher = new ToopherApi('key', 'secret'); $userTerminal = new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name", "toopher_authentication_enabled" => true]], $toopher); $this->compareToDefaultUserTerminal($userTerminal); } public function testAction(){ - $toopher = new ToopherAPI('key', 'secret'); + $toopher = new ToopherApi('key', 'secret'); $action = new Action(["id" => "1", "name" => "action"]); $this->assertTrue($action->id == '1', 'bad action id'); $this->assertTrue($action->name == 'action', 'bad action name'); @@ -537,13 +537,13 @@ public function testToopherRequestException(){ $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } public function testToopherVersionStringExists() { - $this->assertNotEmpty(ToopherAPI::VERSION, 'no version string'); - list($major, $minor, $patch) = explode('.', ToopherAPI::VERSION); + $this->assertNotEmpty(ToopherApi::VERSION, 'no version string'); + list($major, $minor, $patch) = explode('.', ToopherApi::VERSION); $this->assertGreaterThanOrEqual(1, (int)$major); $this->assertGreaterThanOrEqual(0, (int)$minor); $this->assertGreaterThanOrEqual(0, (int)$patch); @@ -555,7 +555,7 @@ public function testToopherVersionStringExists() { public function test400WithEmptyBodyRaisesToopherRequestException(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } @@ -566,7 +566,7 @@ public function test400WithUnprintableBodyRaisesToopherRequestException(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp1->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); $this->mock->addResponse($resp1); - $toopher = new ToopherAPI('key', 'secret', '', $this->mock); + $toopher = new ToopherApi('key', 'secret', '', $this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } } From c347ec521a03891e812b86b41d6c0b6114bdbabf Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Feb 2015 13:39:35 -0600 Subject: [PATCH 041/114] Add ToopherIframe.validatePostback --- lib/toopher_api.php | 90 +++++++++++++++++++++++++++++ test/test_toopher_api.php | 116 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 206 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 8ca96f8..55b892c 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -24,7 +24,97 @@ class ToopherRequestException extends Exception { +} + +class SignatureValidationError extends Exception +{ +} + +class ToopherIframe +{ + function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') + { + $this->consumerSecret = $secret; + $this->consumerKey = $key; + $this->oauthConsumer = new HTTP_OAuth_Consumer($key, $secret); + $this->baseUrl = $baseUrl; + $this->timestampOverride = NULL; + } + + public function setTimestampOverride($timestampOverride) + { + $this->timestampOverride = $timestampOverride; + } + + private function getUnixTimestamp() + { + if (!is_null($this->timestampOverride)) { + return $this->timestampOverride; + } else { + return time(); + } + } + + public function validatePostback($parameters, $sessionToken, $ttl) + { + try { + $data = array(); + + foreach ($parameters as $key => $value) { + $data[$key] = $value[0]; + } + $missingKeys = array(); + if (!array_key_exists('toopher_sig', $data)) { + $missingKeys[] = 'toopher_sig'; + } + if (!array_key_exists('timestamp', $data)) { + $missingKeys[] = 'timestamp'; + } + if (!array_key_exists('session_token', $data)) { + $missingKeys[] = 'session_token'; + } + if (count($missingKeys) > 0) { + $keys = implode(',', $missingKeys); + throw new SignatureValidationError('Missing required keys: ' . $keys); + } + + if ($data['session_token'] != $sessionToken) { + throw new SignatureValidationError('Session token does not match expected value'); + } + + $maybeSignature = $data['toopher_sig']; + unset($data['toopher_sig']); + $signatureValid = false; + try { + $computedSignature = $this->signature($this->consumerSecret, $data); + $signatureValid = $maybeSignature == $computedSignature; + } catch (Exception $e) { + throw new SignatureValidationError('Error while calculating signature: ' . $e); + } + + if (!$signatureValid) { + throw new SignatureValidationError('Computed signature does not match'); + } + + $ttlValid = ($this->getUnixTimestamp() - $ttl) < $data['timestamp']; + if (!$ttlValid) { + throw new SignatureValidationError('TTL Expired'); + } + + return $data; + } catch (Exception $e) { + throw new SignatureValidationError ('Exception while validating toopher signature: ' . $e); + } + } + + private function signature($secret, $parameters) + { + $params = $this->oauthConsumer->buildHttpQuery($parameters); + $key = mb_convert_encoding($secret, "UTF-8"); + $sig = hash_hmac('sha1', $params, $secret, true); + return base64_encode($sig); + } } class ToopherApi diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 960e445..35f5bf8 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -30,6 +30,7 @@ class ToopherApiTests extends PHPUnit_Framework_TestCase { protected function setUp() { + date_default_timezone_set('UTC'); $this->mock = new HTTP_Request2_Adapter_Mock(); } @@ -527,6 +528,121 @@ public function testAction(){ $this->assertTrue($action->name == 'action', 'bad action name'); } + public function testToopherIframeValidatePostbackWithGoodSignatureIsSuccessful() + { + $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); + $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'session_token' => array('s9s7vsb'), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + try { + $toopherIframe->validatePostback($data, 's9s7vsb', 5); + } catch (Exception $e) { + $this->fail('Valid signature, timestamp, and session token did not return validated data'); + } + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Computed signature does not match + */ + public function testToopherIframeValidatePostbackWithBadSignatureFails() + { + $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); + $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'session_token' => array('s9s7vsb'), + 'toopher_sig' => array('invalid') + ); + $toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage TTL Expired + */ + public function testToopherIframeValidatePostbackWithExpiredSignatureFails() + { + $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); + $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 2, 1, 1970)); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'session_token' => array('s9s7vsb'), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + $toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Session token does not match expected value + */ + public function testToopherIframeValidatePostbackWithInvalidSessionTokenFails() + { + $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); + $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'session_token' => array('invalid token'), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + $toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Missing required keys: timestamp + */ + public function testToopherIframeValidatePostbackMissingTimestampFails() + { + $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); + $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $data = array( + 'foo' => array('bar'), + 'session_token' => array('s9s7vsb'), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + $toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Missing required keys: toopher_sig + */ + public function testToopherIframeValidatePostbackMissingSignatureFails() + { + $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); + $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $data = array( + 'foo' => array('bar'), + 'session_token' => array('s9s7vsb'), + 'timestamp' => mktime(0, 16, 40, 1, 1, 1970) + ); + $toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Missing required keys: session_token + */ + public function testToopherIframeValidatePostbackMissingSessionTokenFails() + { + $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); + $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + $toopherIframe->validatePostback($data, 's9s7vsb', 5); + } /** * @expectedException ToopherRequestException From 482092a57c942f1bc2f1db8280639c5d4798831b Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Feb 2015 13:58:26 -0600 Subject: [PATCH 042/114] Add test for UserTerminal.refreshFromServer --- lib/toopher_api.php | 1 + test/test_toopher_api.php | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 55b892c..c3b6f98 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -580,6 +580,7 @@ class UserTerminal function __construct($json_response, $api) { + $this->api = $api; $this->id = $json_response['id']; $this->name = $json_response['name']; $this->requester_specified_id = $json_response['requester_specified_id']; diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 35f5bf8..731087d 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -506,13 +506,13 @@ public function testUserTerminalRefreshFromServer(){ $userTerminal = new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name","toopher_authentication_enabled" => true]], $toopher); $this->compareToDefaultUserTerminal($userTerminal); - // $userTerminal->refreshFromServer(); - // $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); - // $this->assertTrue($userTerminal->name == 'terminal name changed', 'wrong terminal name'); - // $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id changed', 'wrong requester specified id'); - // $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); - // $this->assertTrue($userTerminal->user->name == 'user name changed', 'bad user name'); - // $this->assertTrue($userTerminal->user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); + $userTerminal->refreshFromServer(); + $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); + $this->assertTrue($userTerminal->name == 'terminal name changed', 'wrong terminal name'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id changed', 'wrong requester specified id'); + $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); + $this->assertTrue($userTerminal->user->name == 'user name changed', 'bad user name'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); } public function testUserTerminal(){ From 33d7c2d06a81cf7c120dbdfebf0bdac351fbcbb3 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Feb 2015 16:31:50 -0600 Subject: [PATCH 043/114] Add constants and cleanup tests --- lib/toopher_api.php | 6 +++++ test/test_toopher_api.php | 47 ++++++++++++++++++++++++++++++--------- 2 files changed, 43 insertions(+), 10 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index c3b6f98..da5bdcb 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -39,6 +39,7 @@ function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') $this->oauthConsumer = new HTTP_OAuth_Consumer($key, $secret); $this->baseUrl = $baseUrl; $this->timestampOverride = NULL; + $this->nonceOverride = NULL; } public function setTimestampOverride($timestampOverride) @@ -46,6 +47,11 @@ public function setTimestampOverride($timestampOverride) $this->timestampOverride = $timestampOverride; } + public function setNonceOverride($nonceOverride) + { + $this->nonceOverride = $nonceOverride; + } + private function getUnixTimestamp() { if (!is_null($this->timestampOverride)) { diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 731087d..3789da6 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -26,7 +26,29 @@ class ToopherApiTests extends PHPUnit_Framework_TestCase { - protected $oauthParams = array('oauth_nonce' => 'nonce', 'oauth_timestamp' => '0'); + const OAUTH_NONCE = '12345678'; + const IFRAME_KEY = 'abcdefg'; + const IFRAME_SECRET = 'hijklmnop'; + + public static function getOauthTimestamp() + { + return mktime(0, 16, 40, 1, 1, 1970); + } + + public static function getOauthNonce() + { + return self::OAUTH_NONCE; + } + + public static function getIframeKey() + { + return self::IFRAME_KEY; + } + + public static function getIframeSecret() + { + return self::IFRAME_SECRET; + } protected function setUp() { @@ -34,6 +56,11 @@ protected function setUp() $this->mock = new HTTP_Request2_Adapter_Mock(); } + public function getToopherIframe() + { + return new ToopherIframe($this->getIframeKey(), $this->getIframeSecret(), 'https://api.toopher.test/v1/'); + } + public function compareToDefaultUserTerminal($userTerminal) { $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); @@ -531,10 +558,10 @@ public function testAction(){ public function testToopherIframeValidatePostbackWithGoodSignatureIsSuccessful() { $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $data = array( 'foo' => array('bar'), - 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'timestamp' => array($this->getOauthTimestamp()), 'session_token' => array('s9s7vsb'), 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') ); @@ -552,7 +579,7 @@ public function testToopherIframeValidatePostbackWithGoodSignatureIsSuccessful() public function testToopherIframeValidatePostbackWithBadSignatureFails() { $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $data = array( 'foo' => array('bar'), 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), @@ -572,7 +599,7 @@ public function testToopherIframeValidatePostbackWithExpiredSignatureFails() $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 2, 1, 1970)); $data = array( 'foo' => array('bar'), - 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'timestamp' => array($this->getOauthTimestamp()), 'session_token' => array('s9s7vsb'), 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') ); @@ -586,7 +613,7 @@ public function testToopherIframeValidatePostbackWithExpiredSignatureFails() public function testToopherIframeValidatePostbackWithInvalidSessionTokenFails() { $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); $data = array( 'foo' => array('bar'), 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), @@ -603,7 +630,7 @@ public function testToopherIframeValidatePostbackWithInvalidSessionTokenFails() public function testToopherIframeValidatePostbackMissingTimestampFails() { $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); $data = array( 'foo' => array('bar'), 'session_token' => array('s9s7vsb'), @@ -619,7 +646,7 @@ public function testToopherIframeValidatePostbackMissingTimestampFails() public function testToopherIframeValidatePostbackMissingSignatureFails() { $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); $data = array( 'foo' => array('bar'), 'session_token' => array('s9s7vsb'), @@ -635,10 +662,10 @@ public function testToopherIframeValidatePostbackMissingSignatureFails() public function testToopherIframeValidatePostbackMissingSessionTokenFails() { $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 1, 1, 1970)); + $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); $data = array( 'foo' => array('bar'), - 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'timestamp' => array($this->getOauthTimestamp()), 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') ); $toopherIframe->validatePostback($data, 's9s7vsb', 5); From eded3312325faaa2da4aa93857dfcf10ba8cb362 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Feb 2015 16:53:49 -0600 Subject: [PATCH 044/114] Add PHP OAuth to create oauth signed urls for ToopherIframe --- composer.json | 3 ++- composer.lock | 16 ++++++++++------ lib/toopher_api.php | 5 +++-- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/composer.json b/composer.json index b496c1f..a99dc74 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,8 @@ "php": ">=5.3.0", "ext-json": "*", "pear-pear.php.net/HTTP_Request2": ">=2.1.1", - "pear-pear.php.net/HTTP_OAuth": ">=0.2.3" + "pear-pear.php.net/HTTP_OAuth": ">=0.2.3", + "ext-oauth": "*" }, "require-dev" : { "phpunit/phpunit": "3.7.*", diff --git a/composer.lock b/composer.lock index 032f89e..a1e2b80 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "ccc2dbcabdeb2ff88e43419588500b12", + "hash": "2c3bc139cd3c8e3a096ed8c14f2b50c3", "packages": [ { "name": "pear-pear.php.net/Archive_Tar", @@ -37,18 +37,18 @@ }, { "name": "pear-pear.php.net/Console_Getopt", - "version": "1.3.1", + "version": "1.4.0", "dist": { "type": "file", - "url": "http://pear.php.net/get/Console_Getopt-1.3.1.tgz", + "url": "http://pear.php.net/get/Console_Getopt-1.4.0.tgz", "reference": null, "shasum": null }, "require": { - "php": ">=4.3.0.0" + "php": ">=5.4.0.0" }, "replace": { - "pear-pear/console_getopt": "== 1.3.1.0" + "pear-pear/console_getopt": "== 1.4.0.0" }, "type": "pear-library", "autoload": { @@ -59,6 +59,9 @@ "include-path": [ "/" ], + "license": [ + "PHP License" + ], "description": "This is a PHP implementation of "getopt" supporting both\nshort and long options." }, { @@ -1197,7 +1200,8 @@ "prefer-lowest": false, "platform": { "php": ">=5.3.0", - "ext-json": "*" + "ext-json": "*", + "ext-oauth": "*" }, "platform-dev": [] } diff --git a/lib/toopher_api.php b/lib/toopher_api.php index da5bdcb..7d28ca1 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -36,7 +36,7 @@ function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') { $this->consumerSecret = $secret; $this->consumerKey = $key; - $this->oauthConsumer = new HTTP_OAuth_Consumer($key, $secret); + $this->oauthConsumer = new OAuth($key, $secret); $this->baseUrl = $baseUrl; $this->timestampOverride = NULL; $this->nonceOverride = NULL; @@ -116,7 +116,8 @@ public function validatePostback($parameters, $sessionToken, $ttl) private function signature($secret, $parameters) { - $params = $this->oauthConsumer->buildHttpQuery($parameters); + $oauthConsumer = new HTTP_OAuth_Consumer($this->consumerKey, $this->consumerSecret); + $params = $oauthConsumer->buildHttpQuery($parameters); $key = mb_convert_encoding($secret, "UTF-8"); $sig = hash_hmac('sha1', $params, $secret, true); return base64_encode($sig); From a7312c72563ed038312cfbb6fca6f8b69cfccc53 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Feb 2015 16:54:31 -0600 Subject: [PATCH 045/114] Add ToopherIframe.getAuthenticationUrl and getUserManagementUrl --- lib/toopher_api.php | 62 +++++++++++++++++++++++++++++++++++++++ test/test_toopher_api.php | 48 ++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index 7d28ca1..e3cc1d3 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -61,6 +61,48 @@ private function getUnixTimestamp() } } + public function getAuthenticationUrl($username, $resetEmail, $requestToken, $actionName = 'Log In', $requesterMetadata = 'None', $kwargs = array()) + { + if (array_key_exists('ttl', $kwargs)) { + $ttl = $kwargs['ttl']; + unset($kwargs['ttl']); + } else { + $ttl = 300; + } + + $params = array( + 'v' => '2', + 'username' => $username, + 'reset_email' => $resetEmail, + 'action_name' => $actionName, + 'session_token' => $requestToken, + 'requester_metadata' => $requesterMetadata, + 'expires' => $this->getUnixTimestamp() + $ttl + ); + $params = array_merge($params, $kwargs); + + return $this->getOauthSignedUrl($this->baseUrl . 'web/authenticate', $params); + } + + public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) + { + if (array_key_exists('ttl', $kwargs)) { + $ttl = $kwargs['ttl']; + unset($kwargs['ttl']); + } else { + $ttl = 300; + } + + $params = array( + 'v' => '2', + 'username' => $username, + 'reset_email' => $resetEmail, + 'expires' => $this->getUnixTimestamp() + $ttl + ); + $params = array_merge($params, $kwargs); + return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $params); + } + public function validatePostback($parameters, $sessionToken, $ttl) { try { @@ -122,6 +164,26 @@ private function signature($secret, $parameters) $sig = hash_hmac('sha1', $params, $secret, true); return base64_encode($sig); } + + private function getOauthSignedUrl($url, $params) + { + if (!is_null($this->timestampOverride)) { + $this->oauthConsumer->setTimestamp($this->timestampOverride); + } + if (!is_null($this->nonceOverride)) { + $this->oauthConsumer->setNonce($this->nonceOverride); + } + + $oauthHeaderString = $this->oauthConsumer->getRequestHeader('GET', $url, $params); + $oauthHeaderArray = explode(",", str_replace("OAuth ", "", $oauthHeaderString)); + $oauthParams = array(); + foreach ($oauthHeaderArray as $value) { + $oauthParams[] = str_replace("\"", "", $value); + } + $oauthParams = implode("&", $oauthParams); + $queryParams = http_build_query($params); + return $url . '?' . $queryParams . '&' . $oauthParams; + } } class ToopherApi diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index 3789da6..c7c89de 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -29,6 +29,7 @@ class ToopherApiTests extends PHPUnit_Framework_TestCase { const OAUTH_NONCE = '12345678'; const IFRAME_KEY = 'abcdefg'; const IFRAME_SECRET = 'hijklmnop'; + const REQUEST_TOKEN = 's9s7vsb'; public static function getOauthTimestamp() { @@ -50,6 +51,11 @@ public static function getIframeSecret() return self::IFRAME_SECRET; } + public static function getRequestToken() + { + return self::REQUEST_TOKEN; + } + protected function setUp() { date_default_timezone_set('UTC'); @@ -555,6 +561,48 @@ public function testAction(){ $this->assertTrue($action->name == 'action', 'bad action name'); } + public function testToopherIframeGetAuthenticationUrl() + { + $toopherIframe = $this->getToopherIframe(); + $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D"; + $authenticationUrl = $toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); + $this->assertTrue($authenticationUrl == $expectedUrl, 'authentication url is incorrect'); + } + + public function testToopherIframeGetAuthenticationUrlWithExtras() + { + $extras = array("allow_inline_pairing" => "false"); + $toopherIframe = $this->getToopherIframe(); + $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D"; + $authenticationUrl = $toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'None', $extras); + $this->assertTrue($authenticationUrl == $expectedUrl, 'authentication url is incorrect'); + } + + public function testToopherIframeGetUserManagementUrl() + { + $toopherIframe = $this->getToopherIframe(); + $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D"; + $userManagementUrl = $toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com'); + $this->assertTrue($userManagementUrl == $expectedUrl, 'user management url is incorrect'); + } + + public function testToopherIframeGetUserManagementUrlWithExtras() + { + $extras = array("ttl" => "100"); + $toopherIframe = $this->getToopherIframe(); + $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D"; + $userManagementUrl = $toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com', $extras); + $this->assertTrue($userManagementUrl == $expectedUrl, 'user management url is incorrect'); + } + public function testToopherIframeValidatePostbackWithGoodSignatureIsSuccessful() { $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); From 47fc57ee0b932546411f53be797f3e43c725395d Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Feb 2015 16:54:45 -0600 Subject: [PATCH 046/114] Bump ToopherApi version to 2.0.0 --- lib/toopher_api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index e3cc1d3..ece0511 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -188,7 +188,7 @@ private function getOauthSignedUrl($url, $params) class ToopherApi { - const VERSION = '1.0.6'; + const VERSION = '2.0.0'; protected $baseUrl; protected $oauthConsumer; From 0876115759aec21631f8ab1df65fe0f3bfeb7b48 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Feb 2015 17:10:58 -0600 Subject: [PATCH 047/114] Move ToopherIframe tests into own file and cleanup --- test/ToopherIframeTest.php | 211 +++++++++++++++++++++++++++++++++++++ test/test_toopher_api.php | 193 --------------------------------- 2 files changed, 211 insertions(+), 193 deletions(-) create mode 100644 test/ToopherIframeTest.php diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php new file mode 100644 index 0000000..13e2f12 --- /dev/null +++ b/test/ToopherIframeTest.php @@ -0,0 +1,211 @@ +toopherIframe = new ToopherIframe($this->getIframeKey(), $this->getIframeSecret(), 'https://api.toopher.test/v1/'); + } + + public function testToopherIframeGetAuthenticationUrl() + { + $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $this->toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D"; + $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); + $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); + } + + public function testToopherIframeGetAuthenticationUrlWithExtras() + { + $extras = array("allow_inline_pairing" => "false"); + $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $this->toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D"; + $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'None', $extras); + $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); + } + + public function testToopherIframeGetUserManagementUrl() + { + $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $this->toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D"; + $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com'); + $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); + } + + public function testToopherIframeGetUserManagementUrlWithExtras() + { + $extras = array("ttl" => "100"); + $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $this->toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D"; + $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com', $extras); + $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); + } + + public function testToopherIframeValidatePostbackWithGoodSignatureIsSuccessful() + { + $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array($this->getOauthTimestamp()), + 'session_token' => array('s9s7vsb'), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + try { + $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + } catch (Exception $e) { + $this->fail('Valid signature, timestamp, and session token did not return validated data'); + } + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Computed signature does not match + */ + public function testToopherIframeValidatePostbackWithBadSignatureFails() + { + $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'session_token' => array('s9s7vsb'), + 'toopher_sig' => array('invalid') + ); + $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage TTL Expired + */ + public function testToopherIframeValidatePostbackWithExpiredSignatureFails() + { + $this->toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 2, 1, 1970)); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array($this->getOauthTimestamp()), + 'session_token' => array('s9s7vsb'), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Session token does not match expected value + */ + public function testToopherIframeValidatePostbackWithInvalidSessionTokenFails() + { + $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), + 'session_token' => array('invalid token'), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Missing required keys: timestamp + */ + public function testToopherIframeValidatePostbackMissingTimestampFails() + { + $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); + $data = array( + 'foo' => array('bar'), + 'session_token' => array('s9s7vsb'), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Missing required keys: toopher_sig + */ + public function testToopherIframeValidatePostbackMissingSignatureFails() + { + $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); + $data = array( + 'foo' => array('bar'), + 'session_token' => array('s9s7vsb'), + 'timestamp' => mktime(0, 16, 40, 1, 1, 1970) + ); + $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + } + + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Missing required keys: session_token + */ + public function testToopherIframeValidatePostbackMissingSessionTokenFails() + { + $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); + $data = array( + 'foo' => array('bar'), + 'timestamp' => array($this->getOauthTimestamp()), + 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + ); + $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + } +} diff --git a/test/test_toopher_api.php b/test/test_toopher_api.php index c7c89de..b5f46b9 100644 --- a/test/test_toopher_api.php +++ b/test/test_toopher_api.php @@ -26,47 +26,12 @@ class ToopherApiTests extends PHPUnit_Framework_TestCase { - const OAUTH_NONCE = '12345678'; - const IFRAME_KEY = 'abcdefg'; - const IFRAME_SECRET = 'hijklmnop'; - const REQUEST_TOKEN = 's9s7vsb'; - - public static function getOauthTimestamp() - { - return mktime(0, 16, 40, 1, 1, 1970); - } - - public static function getOauthNonce() - { - return self::OAUTH_NONCE; - } - - public static function getIframeKey() - { - return self::IFRAME_KEY; - } - - public static function getIframeSecret() - { - return self::IFRAME_SECRET; - } - - public static function getRequestToken() - { - return self::REQUEST_TOKEN; - } - protected function setUp() { date_default_timezone_set('UTC'); $this->mock = new HTTP_Request2_Adapter_Mock(); } - public function getToopherIframe() - { - return new ToopherIframe($this->getIframeKey(), $this->getIframeSecret(), 'https://api.toopher.test/v1/'); - } - public function compareToDefaultUserTerminal($userTerminal) { $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); @@ -561,164 +526,6 @@ public function testAction(){ $this->assertTrue($action->name == 'action', 'bad action name'); } - public function testToopherIframeGetAuthenticationUrl() - { - $toopherIframe = $this->getToopherIframe(); - $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D"; - $authenticationUrl = $toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); - $this->assertTrue($authenticationUrl == $expectedUrl, 'authentication url is incorrect'); - } - - public function testToopherIframeGetAuthenticationUrlWithExtras() - { - $extras = array("allow_inline_pairing" => "false"); - $toopherIframe = $this->getToopherIframe(); - $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D"; - $authenticationUrl = $toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'None', $extras); - $this->assertTrue($authenticationUrl == $expectedUrl, 'authentication url is incorrect'); - } - - public function testToopherIframeGetUserManagementUrl() - { - $toopherIframe = $this->getToopherIframe(); - $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D"; - $userManagementUrl = $toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com'); - $this->assertTrue($userManagementUrl == $expectedUrl, 'user management url is incorrect'); - } - - public function testToopherIframeGetUserManagementUrlWithExtras() - { - $extras = array("ttl" => "100"); - $toopherIframe = $this->getToopherIframe(); - $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D"; - $userManagementUrl = $toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com', $extras); - $this->assertTrue($userManagementUrl == $expectedUrl, 'user management url is incorrect'); - } - - public function testToopherIframeValidatePostbackWithGoodSignatureIsSuccessful() - { - $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => array('bar'), - 'timestamp' => array($this->getOauthTimestamp()), - 'session_token' => array('s9s7vsb'), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') - ); - try { - $toopherIframe->validatePostback($data, 's9s7vsb', 5); - } catch (Exception $e) { - $this->fail('Valid signature, timestamp, and session token did not return validated data'); - } - } - - /** - * @expectedException SignatureValidationError - * @expectedExceptionMessage Computed signature does not match - */ - public function testToopherIframeValidatePostbackWithBadSignatureFails() - { - $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => array('bar'), - 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), - 'session_token' => array('s9s7vsb'), - 'toopher_sig' => array('invalid') - ); - $toopherIframe->validatePostback($data, 's9s7vsb', 5); - } - - /** - * @expectedException SignatureValidationError - * @expectedExceptionMessage TTL Expired - */ - public function testToopherIframeValidatePostbackWithExpiredSignatureFails() - { - $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 2, 1, 1970)); - $data = array( - 'foo' => array('bar'), - 'timestamp' => array($this->getOauthTimestamp()), - 'session_token' => array('s9s7vsb'), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') - ); - $toopherIframe->validatePostback($data, 's9s7vsb', 5); - } - - /** - * @expectedException SignatureValidationError - * @expectedExceptionMessage Session token does not match expected value - */ - public function testToopherIframeValidatePostbackWithInvalidSessionTokenFails() - { - $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => array('bar'), - 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), - 'session_token' => array('invalid token'), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') - ); - $toopherIframe->validatePostback($data, 's9s7vsb', 5); - } - - /** - * @expectedException SignatureValidationError - * @expectedExceptionMessage Missing required keys: timestamp - */ - public function testToopherIframeValidatePostbackMissingTimestampFails() - { - $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => array('bar'), - 'session_token' => array('s9s7vsb'), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') - ); - $toopherIframe->validatePostback($data, 's9s7vsb', 5); - } - - /** - * @expectedException SignatureValidationError - * @expectedExceptionMessage Missing required keys: toopher_sig - */ - public function testToopherIframeValidatePostbackMissingSignatureFails() - { - $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => array('bar'), - 'session_token' => array('s9s7vsb'), - 'timestamp' => mktime(0, 16, 40, 1, 1, 1970) - ); - $toopherIframe->validatePostback($data, 's9s7vsb', 5); - } - - /** - * @expectedException SignatureValidationError - * @expectedExceptionMessage Missing required keys: session_token - */ - public function testToopherIframeValidatePostbackMissingSessionTokenFails() - { - $toopherIframe = new ToopherIframe('abcdefg', 'hijklmnop', 'https://api.toopher.test/v1/'); - $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => array('bar'), - 'timestamp' => array($this->getOauthTimestamp()), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') - ); - $toopherIframe->validatePostback($data, 's9s7vsb', 5); - } - /** * @expectedException ToopherRequestException */ From 3de88659cc08a85b802d1b248630c2b39d5e76a0 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Feb 2015 17:12:30 -0600 Subject: [PATCH 048/114] Rename ToopherApi test file to ToopherApiTest --- test/{test_toopher_api.php => ToopherApiTest.php} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test/{test_toopher_api.php => ToopherApiTest.php} (100%) diff --git a/test/test_toopher_api.php b/test/ToopherApiTest.php similarity index 100% rename from test/test_toopher_api.php rename to test/ToopherApiTest.php From 51d7111a932db9613fcf571f34846c1e74d686e9 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 11:12:31 -0600 Subject: [PATCH 049/114] Move Pairing tests into own file and cleanup --- test/PairingTest.php | 109 ++++++++++++++++++++++++++++++++++++++++ test/ToopherApiTest.php | 75 --------------------------- 2 files changed, 109 insertions(+), 75 deletions(-) create mode 100644 test/PairingTest.php diff --git a/test/PairingTest.php b/test/PairingTest.php new file mode 100644 index 0000000..fdc22ef --- /dev/null +++ b/test/PairingTest.php @@ -0,0 +1,109 @@ +mock = new HTTP_Request2_Adapter_Mock(); + } + + protected function getToopherApi($mock = NULL) + { + return new ToopherApi('key', 'secret', '', $mock); + } + + protected function getPairing($api) + { + return new Pairing(["id" => "1","enabled" => true, "pending" => false, "user" => ["id" => "1","name" => "user", "toopher_authentication_enabled" => "true"]], $api); + } + + public function testPairing(){ + $pairing = $this->getPairing($this->getToopherApi()); + $this->assertTrue($pairing->id == '1', 'Pairing id was incorrect'); + $this->assertTrue($pairing->enabled == true, 'Pairing should be enabled'); + $this->assertTrue($pairing->pending == false, 'Pairing should not be pending'); + $this->assertTrue($pairing->user->id == '1', 'User id was incorrect'); + $this->assertTrue($pairing->user->name == 'user', 'User name was incorrect'); + $this->assertTrue($pairing->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + } + + + public function testPairingRefreshFromServer(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp->appendBody('{"id":"1","enabled":false,"pending":true,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":false}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); + + $pairing->refreshFromServer(); + $this->assertTrue($pairing->enabled == false, 'Pairing should not be enabled'); + $this->assertTrue($pairing->pending == true, 'Pairing should be pending'); + $this->assertTrue($pairing->user->name == 'user name changed', 'User name was incorrect'); + $this->assertTrue($pairing->user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); + } + + public function testGetPairingResetLink(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); + $resp->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); + + $resetLink = $pairing->getResetLink(); + $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde", 'Pairing reset link was incorrect'); + } + + public function testEmailPairingResetLink(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); + + try { + $pairing->emailResetLink('jdoe@example.com'); + } + catch(Exception $e) { + $this->fail('Unexpected exception has been raised: ' . $e); + } + } + + public function testPairingGetQrCodeImage(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/qr/pairings/1'); + $resp->appendBody('{}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); + + $qr_image = $pairing->getQrCodeImage(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/qr/pairings/1', "Last called url should be 'https://api.toopher.com/v1/qr/pairings/1'"); + } +} + +?> diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index b5f46b9..e4904f3 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -28,7 +28,6 @@ class ToopherApiTests extends PHPUnit_Framework_TestCase { protected function setUp() { - date_default_timezone_set('UTC'); $this->mock = new HTTP_Request2_Adapter_Mock(); } @@ -118,80 +117,6 @@ public function testGetPairingStatus(){ $this->assertTrue($pairing->user->name == 'unpaired user', 'bad user name'); } - public function testPairingRefreshFromServer(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp1->appendBody('{"id":"1","enabled":false, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); - $resp2->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":"true"}}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - - $pairing = $toopher->pair('user', 'pairing phrase'); - $this->assertTrue($pairing->id == '1', 'bad pairing id'); - $this->assertTrue($pairing->enabled == false, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '1', 'bad user id'); - $this->assertTrue($pairing->user->name == 'user', 'bad user name'); - - $pairing->refreshFromServer(); - $this->assertTrue($pairing->id == '1', 'bad pairing id'); - $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '1', 'bad user id'); - $this->assertTrue($pairing->user->name == 'user name changed', 'bad user name'); - } - - public function testGetPairingResetLink(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); - $resp2->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $pairing = $toopher->pair('user', 'immediate_pair'); - $this->assertTrue($pairing->id == '1', 'bad pairing id'); - $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '1', 'bad user id'); - $this->assertTrue($pairing->user->name == 'user', 'bad user name'); - - $resetLink = $pairing->getResetLink(); - $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"); - } - - public function testEmailPairingResetLink(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $pairing = $toopher->pair('user', 'immediate_pair'); - $this->assertTrue($pairing->id == '1', 'bad pairing id'); - $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '1', 'bad user id'); - $this->assertTrue($pairing->user->name == 'user', 'bad user name'); - - try { - $pairing->emailResetLink('email@domain.com'); - } - catch(Exception $e) { - $this->fail('Unexpected exception has been raised: ' . $e); - } - } - - public function testPairingGetQrCodeImage(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/qr/pairings/1'); - $resp2->appendBody('{}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $pairing = $toopher->pair('user'); - $qr_image = $pairing->getQrCodeImage(); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "last called method should be 'GET'"); - } - public function testCreateAuthenticationWithNoAction(){ $id = Uuid::uuid4()->toString(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); From 7d14edd2aa86044f2f933b3c04d44af343684fbf Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 11:56:25 -0600 Subject: [PATCH 050/114] Move AuthenticationRequest tests into own file and cleanup --- test/AuthenticationRequestTest.php | 92 ++++++++++++++++++++++++++++++ test/ToopherApiTest.php | 57 ------------------ 2 files changed, 92 insertions(+), 57 deletions(-) create mode 100644 test/AuthenticationRequestTest.php diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php new file mode 100644 index 0000000..824a3bf --- /dev/null +++ b/test/AuthenticationRequestTest.php @@ -0,0 +1,92 @@ +mock = new HTTP_Request2_Adapter_Mock(); + } + + protected function getToopherApi($mock = NULL) + { + return new ToopherApi('key', 'secret', '', $mock); + } + + protected function getAuthenticationRequest($api) + { + return new AuthenticationRequest(["id"=>"1","pending"=>true,"granted"=>false,"automated"=>false,"reason_code"=>"1","reason"=>"some reason","terminal"=>["id"=>"1","name"=>"term name","requester_specified_id"=>"1","user"=>["id"=>"1","name"=>"user","toopher_authentication_enabled"=>"true"]],"user"=>["id"=>"1","name"=>"user", "toopher_authentication_enabled"=>"true"],"action"=>["id"=>"1","name"=>"test"]], $api); + } + + public function testAuthenticationRequest() + { + $auth_request = $this->getAuthenticationRequest($this->getToopherApi()); + $this->assertTrue($auth_request->id == '1', 'Authentication request id was incorrect'); + $this->assertTrue($auth_request->pending == true, 'Authentication request should be pending'); + $this->assertTrue($auth_request->granted == false, 'Authentication request should not be granted'); + $this->assertTrue($auth_request->automated == false, 'Authentication request should not be automated'); + $this->assertTrue($auth_request->reason_code == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($auth_request->reason == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($auth_request->terminal->id == '1', 'Terminal id was incorrect'); + $this->assertTrue($auth_request->terminal->name == 'term name', 'Terminal name was incorrect'); + $this->assertTrue($auth_request->terminal->requester_specified_id == '1', 'Terminal requester_specified_id was incorrect'); + $this->assertTrue($auth_request->user->id == '1', 'User id was incorrect'); + $this->assertTrue($auth_request->user->name == 'user', 'User name was incorrect'); + $this->assertTrue($auth_request->action->id == '1', 'Action id was incorrect'); + $this->assertTrue($auth_request->action->name == 'test', 'Action name was incorrect'); + } + + public function testAuthenticationRequestRefreshFromServer(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user changed", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user changed", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test changed"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $auth_request = $this->getAuthenticationRequest($toopher); + + $auth_request->refreshFromServer(); + $this->assertTrue($auth_request->pending == false, 'Authentication request should not be pending'); + $this->assertTrue($auth_request->granted == true, 'Authentication request should be granted'); + $this->assertTrue($auth_request->automated == true, 'Authentication request should be automated'); + $this->assertTrue($auth_request->reason == 'some other reason', 'Authentication request reason was incorrect'); + $this->assertTrue($auth_request->terminal->name == 'term name changed', 'Terminal name was incorrect'); + $this->assertTrue($auth_request->user->name == 'user changed', 'User name was incorrect'); + $this->assertTrue($auth_request->action->name == 'test changed', 'Action name was incorrect'); + } + + public function testGrantAuthenticationRequestWithOtp(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1/otp_auth'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $auth_request = $this->getAuthenticationRequest($toopher); + + $auth_request->grantWithOtp('otp'); + $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); + $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); + $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); + } +} + +?> diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index e4904f3..927398d 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -162,63 +162,6 @@ public function testGetAuthenticationStatus(){ $this->assertTrue($auth_request->terminal->name == 'another term name', 'wrong auth terminal name'); } - public function testAuthenticationRequestRefreshFromServer(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"1","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp2->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $auth_request = $toopher->authenticate('user', 'term name extra'); - $this->assertTrue($auth_request->id == '1', 'wrong auth id'); - $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); - $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); - $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); - $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); - - $auth_request->refreshFromServer(); - $this->assertTrue($auth_request->id == '1', 'wrong auth id'); - $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); - $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); - $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); - $this->assertTrue($auth_request->reason == 'some other reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminal->name == 'term name changed', 'wrong auth terminal name'); - } - - public function testGrantAuthenticationRequestWithOtp(){ - $id = Uuid::uuid4()->toString(); - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id . '/otp_auth'); - $resp2->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $auth_request = $toopher->authenticate($id, 'term name'); - $this->assertTrue($auth_request->id == $id, 'wrong auth id'); - $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); - $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); - $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); - $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); - - $auth_request->grantWithOtp('otp'); - $this->assertTrue($auth_request->id == $id, 'wrong auth id'); - $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); - $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); - $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); - $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); - } - public function testRawPost(){ $id = Uuid::uuid4()->toString(); $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); From c2b1a4e0499d1a3fed62147b30a1f511780169d8 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 13:18:59 -0600 Subject: [PATCH 051/114] Move UserTerminal tests into own file and cleanup --- test/ToopherApiTest.php | 24 ------------- test/UserTerminalTest.php | 75 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 24 deletions(-) create mode 100644 test/UserTerminalTest.php diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 927398d..c42b559 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -363,30 +363,6 @@ public function testUserTerminalCreateWithExtras(){ $this->compareToDefaultUserTerminal($userTerminal); } - public function testUserTerminalRefreshFromServer(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); - $resp1->appendBody('{"id":"1", "name":"terminal name changed", "requester_specified_id":"requester specified id changed", "user":{"id":"1", "name":"user name changed", "toopher_authentication_enabled":false}}'); - $this->mock->addResponse($resp1); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $userTerminal = new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name","toopher_authentication_enabled" => true]], $toopher); - $this->compareToDefaultUserTerminal($userTerminal); - - $userTerminal->refreshFromServer(); - $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); - $this->assertTrue($userTerminal->name == 'terminal name changed', 'wrong terminal name'); - $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id changed', 'wrong requester specified id'); - $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); - $this->assertTrue($userTerminal->user->name == 'user name changed', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); - } - - public function testUserTerminal(){ - $toopher = new ToopherApi('key', 'secret'); - $userTerminal = new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name", "toopher_authentication_enabled" => true]], $toopher); - $this->compareToDefaultUserTerminal($userTerminal); - } - public function testAction(){ $toopher = new ToopherApi('key', 'secret'); $action = new Action(["id" => "1", "name" => "action"]); diff --git a/test/UserTerminalTest.php b/test/UserTerminalTest.php new file mode 100644 index 0000000..0ecb8e9 --- /dev/null +++ b/test/UserTerminalTest.php @@ -0,0 +1,75 @@ +mock = new HTTP_Request2_Adapter_Mock(); + } + + protected function getToopherApi($mock = NULL) + { + return new ToopherApi('key', 'secret', '', $mock); + } + + protected function getUserTerminal($api) + { + return new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name", "toopher_authentication_enabled" => true]], $api); + } + + public function testUserTerminal(){ + $userTerminal = $this->getUserTerminal($this->getToopherApi()); + $this->assertTrue($userTerminal->id == '1', 'Terminal id was incorrect'); + $this->assertTrue($userTerminal->name == 'terminal name', 'Terminal name was incorrect'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'Terminal requester_specified_id was incorrect'); + $this->assertTrue($userTerminal->user->id == '1', 'User id was incorrect'); + $this->assertTrue($userTerminal->user->name == 'user name', 'User name was incorrect'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + } + + public function testUserTerminalRefreshFromServer(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp->appendBody('{"id":"1", "name":"terminal name changed", "requester_specified_id":"requester specified id changed", "user":{"id":"1", "name":"user name changed", "toopher_authentication_enabled":false}}'); + $this->mock->addResponse($resp); + + $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $userTerminal = $this->getUserTerminal($toopher); + + $userTerminal->refreshFromServer(); + $this->assertTrue($userTerminal->name == 'terminal name changed', 'Terminal name was wrong'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id changed', 'Terminal requester_specified_id was incorrect'); + $this->assertTrue($userTerminal->user->name == 'user name changed', 'User name was incorrect'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); + } + + public function testUserTerminalUpdate(){ + $userTerminal = $this->getUserTerminal($this->getToopherApi()); + $userTerminal->update(["id"=>"1", "name"=>"terminal name changed", "requester_specified_id"=>"requester specified id changed", "user"=>["id"=>"1", "name"=>"user name changed", "toopher_authentication_enabled"=>false]]); + $this->assertTrue($userTerminal->name == 'terminal name changed', 'Terminal name was wrong'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id changed', 'Terminal requester_specified_id was incorrect'); + $this->assertTrue($userTerminal->user->name == 'user name changed', 'User name was incorrect'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); + } +} + +?> From b0a04add5be4d4b03bdededf3bc94eb5c0a903c6 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 13:36:42 -0600 Subject: [PATCH 052/114] Move User tests into own file and cleanup --- test/ToopherApiTest.php | 53 -------------------- test/UserTest.php | 106 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 53 deletions(-) create mode 100644 test/UserTest.php diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index c42b559..545bc82 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -267,60 +267,7 @@ public function testUsersCreateWithExtras(){ $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } - public function testUser(){ - $toopher = new ToopherApi('key', 'secret'); - $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); - $this->assertTrue($user->id == '1', 'bad user id'); - $this->assertTrue($user->name == 'user', 'bad user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); - } - - public function testUserRefreshFromServer(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); - $resp1->appendBody('{"id":"1","name":"user changed","toopher_authentication_enabled":true}'); - $this->mock->addResponse($resp1); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => false], $toopher); - $this->assertTrue($user->id == '1', 'bad user id'); - $this->assertTrue($user->name == 'user', 'bad user name'); - $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); - - $user->refreshFromServer(); - $this->assertTrue($user->id == '1', 'bad user id'); - $this->assertTrue($user->name == 'user changed', 'bad user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); - } - - public function testUserEnableToopherAuthentication(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); - $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); - $this->mock->addResponse($resp1); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => false], $toopher); - $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); - - $user->enableToopherAuthentication(); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == "toopher_authentication_enabled=true", 'post params were incorrect'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "last called method should be 'POST'"); - } - - public function testUserDisableToopherAuthentication(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); - $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":false}'); - $this->mock->addResponse($resp1); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $toopher); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); - - $user->disableToopherAuthentication(); - $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == "toopher_authentication_enabled=false", 'post params were incorrect'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "last called method should be 'POST'"); - } public function testUserTerminalsGetById(){ $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); diff --git a/test/UserTest.php b/test/UserTest.php new file mode 100644 index 0000000..631e0ad --- /dev/null +++ b/test/UserTest.php @@ -0,0 +1,106 @@ +mock = new HTTP_Request2_Adapter_Mock(); + } + + protected function getToopherApi($mock = NULL) + { + return new ToopherApi('key', 'secret', '', $mock); + } + + protected function getUser($api) + { + return new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $api); + } + + public function testUser() + { + $user = $this->getUser($this->getToopherApi()); + $this->assertTrue($user->id == '1', 'User id was incorrect'); + $this->assertTrue($user->name == 'user', 'User name was incorrect'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + } + + public function testUserRefreshFromServer() + { + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp->appendBody('{"id":"1","name":"user changed","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $user = $this->getUser($toopher); + + $user->refreshFromServer(); + $this->assertTrue($user->id == '1', 'bad user id'); + $this->assertTrue($user->name == 'user changed', 'bad user name'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + } + + public function testUserEnableToopherAuthentication() + { + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => false], $toopher); + $this->assertTrue($user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); + + $user->enableToopherAuthentication(); + $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == "toopher_authentication_enabled=true", "Post params should include 'toopher_authentication_enabled=true'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + } + + public function testUserDisableToopherAuthentication() + { + $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":false}'); + $this->mock->addResponse($resp1); + + $toopher = $this->getToopherApi($this->mock); + $user = $this->getUser($toopher); + $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + + $user->disableToopherAuthentication(); + $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == "toopher_authentication_enabled=false", "Post params should include'toopher_authentication_enabled=false"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + } + + public function testUserUpdate() + { + $toopher = $this->getToopherApi($this->mock); + $user = $this->getUser($toopher); + $user->update(["id" => "1", "name" => "user changed", "toopher_authentication_enabled" => false]); + $this->assertTrue($user->name == 'user changed', 'User name was incorrect'); + $this->assertTrue($user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); + } +} + +?> From 079c0ed67abaa46b2ee7330ceb8ad7e764d02cac Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 13:41:48 -0600 Subject: [PATCH 053/114] Add test assertions for last called method --- test/AuthenticationRequestTest.php | 2 ++ test/PairingTest.php | 7 +++++-- test/UserTerminalTest.php | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php index 824a3bf..449fc3d 100644 --- a/test/AuthenticationRequestTest.php +++ b/test/AuthenticationRequestTest.php @@ -65,6 +65,7 @@ public function testAuthenticationRequestRefreshFromServer(){ $auth_request = $this->getAuthenticationRequest($toopher); $auth_request->refreshFromServer(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->assertTrue($auth_request->pending == false, 'Authentication request should not be pending'); $this->assertTrue($auth_request->granted == true, 'Authentication request should be granted'); $this->assertTrue($auth_request->automated == true, 'Authentication request should be automated'); @@ -83,6 +84,7 @@ public function testGrantAuthenticationRequestWithOtp(){ $auth_request = $this->getAuthenticationRequest($toopher); $auth_request->grantWithOtp('otp'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); diff --git a/test/PairingTest.php b/test/PairingTest.php index fdc22ef..a07ee5b 100644 --- a/test/PairingTest.php +++ b/test/PairingTest.php @@ -59,6 +59,7 @@ public function testPairingRefreshFromServer(){ $pairing = $this->getPairing($toopher); $pairing->refreshFromServer(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->assertTrue($pairing->enabled == false, 'Pairing should not be enabled'); $this->assertTrue($pairing->pending == true, 'Pairing should be pending'); $this->assertTrue($pairing->user->name == 'user name changed', 'User name was incorrect'); @@ -74,6 +75,7 @@ public function testGetPairingResetLink(){ $pairing = $this->getPairing($toopher); $resetLink = $pairing->getResetLink(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde", 'Pairing reset link was incorrect'); } @@ -85,10 +87,11 @@ public function testEmailPairingResetLink(){ $pairing = $this->getPairing($toopher); try { - $pairing->emailResetLink('jdoe@example.com'); + $pairing->emailResetLink('jdoe@example.com'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); } catch(Exception $e) { - $this->fail('Unexpected exception has been raised: ' . $e); + $this->fail('Unexpected exception has been raised: ' . $e); } } diff --git a/test/UserTerminalTest.php b/test/UserTerminalTest.php index 0ecb8e9..411d9e6 100644 --- a/test/UserTerminalTest.php +++ b/test/UserTerminalTest.php @@ -56,6 +56,7 @@ public function testUserTerminalRefreshFromServer(){ $userTerminal = $this->getUserTerminal($toopher); $userTerminal->refreshFromServer(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->assertTrue($userTerminal->name == 'terminal name changed', 'Terminal name was wrong'); $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id changed', 'Terminal requester_specified_id was incorrect'); $this->assertTrue($userTerminal->user->name == 'user name changed', 'User name was incorrect'); From 955303299642ddbf177b725d5a8131ebf5d9c18d Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 15:25:47 -0600 Subject: [PATCH 054/114] Move Action tests into own file --- test/ActionTest.php | 45 +++++++++++++++++++++++++++++++++++++++++ test/ToopherApiTest.php | 5 ----- 2 files changed, 45 insertions(+), 5 deletions(-) create mode 100644 test/ActionTest.php diff --git a/test/ActionTest.php b/test/ActionTest.php new file mode 100644 index 0000000..69a41c5 --- /dev/null +++ b/test/ActionTest.php @@ -0,0 +1,45 @@ + "1", "name" => "action"]); + $this->assertTrue($action->id == '1', 'Action id was incorrect'); + $this->assertTrue($action->name == 'action', 'Action name was incorrect'); + } + + public function testActionUpdate() + { + $toopher = new ToopherApi('key', 'secret'); + $action = new Action(["id" => "1", "name" => "action changed"]); + $action->update(['id'=>'1', 'name'=>'action changed']); + $this->assertTrue($action->id == '1', 'Action id was incorrect'); + $this->assertTrue($action->name == 'action changed', 'Action name was incorrect'); + } +} + +?> diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 545bc82..e229ac6 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -310,11 +310,6 @@ public function testUserTerminalCreateWithExtras(){ $this->compareToDefaultUserTerminal($userTerminal); } - public function testAction(){ - $toopher = new ToopherApi('key', 'secret'); - $action = new Action(["id" => "1", "name" => "action"]); - $this->assertTrue($action->id == '1', 'bad action id'); - $this->assertTrue($action->name == 'action', 'bad action name'); } /** From a431fab71ca7ecb8a1459d761ab21d537466ce73 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 15:55:09 -0600 Subject: [PATCH 055/114] Add and cleanup tests --- test/AuthenticationRequestTest.php | 1 + test/ToopherApiTest.php | 412 ++++++++++++++--------------- test/UserTerminalTest.php | 2 +- 3 files changed, 196 insertions(+), 219 deletions(-) diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php index 449fc3d..6d5f32d 100644 --- a/test/AuthenticationRequestTest.php +++ b/test/AuthenticationRequestTest.php @@ -52,6 +52,7 @@ public function testAuthenticationRequest() $this->assertTrue($auth_request->terminal->requester_specified_id == '1', 'Terminal requester_specified_id was incorrect'); $this->assertTrue($auth_request->user->id == '1', 'User id was incorrect'); $this->assertTrue($auth_request->user->name == 'user', 'User name was incorrect'); + $this->assertTrue($auth_request->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); $this->assertTrue($auth_request->action->id == '1', 'Action id was incorrect'); $this->assertTrue($auth_request->action->name == 'test', 'Action name was incorrect'); } diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index e229ac6..f77ea90 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -31,6 +31,46 @@ protected function setUp() $this->mock = new HTTP_Request2_Adapter_Mock(); } + protected function getToopherApi($mock) + { + return new ToopherApi('key', 'secret', '', $mock); + } + + public function compareToDefaultPairing($pairing) + { + $this->assertTrue($pairing->id == '1', 'Pairing id was incorrect'); + $this->assertTrue($pairing->enabled == true, 'Pairing should be enabled'); + $this->assertTrue($pairing->pending == false, 'Pairing should not be pending'); + $this->assertTrue($pairing->user->id == '1', 'User id was incorrect'); + $this->assertTrue($pairing->user->name == 'user', 'User name was wrong'); + $this->assertTrue($pairing->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + } + + public function compareToDefaultAuthenticationRequest($authRequest, $id = '1') + { + $this->assertTrue($authRequest->id == $id, 'Authentiation request id was incorrect'); + $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest->automated == true, 'Authentiation request should be automated'); + $this->assertTrue($authRequest->reason_code == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest->reason == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest->terminal->id == '1', 'Terminal id was incorrect'); + $this->assertTrue($authRequest->terminal->name == 'term name', 'Terminal name was incorrect'); + $this->assertTrue($authRequest->terminal->requester_specified_id == '1', 'Terminal requester_specified_id was incorrect'); + $this->assertTrue($authRequest->user->id == '1', 'User id was incorrect'); + $this->assertTrue($authRequest->user->name == 'user', 'User name was incorrect'); + $this->assertTrue($authRequest->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + $this->assertTrue($authRequest->action->id == '1', 'Action id was incorrect'); + $this->assertTrue($authRequest->action->name == 'test', 'Action name was incorrect'); + } + + public function compareToDefaultUser($user) + { + $this->assertTrue($user->id == '1', 'User id was incorrect'); + $this->assertTrue($user->name == 'user', 'User name was incorrect'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + } + public function compareToDefaultUserTerminal($userTerminal) { $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); @@ -41,305 +81,241 @@ public function compareToDefaultUserTerminal($userTerminal) $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } - /** - * @expectedException InvalidArgumentException - */ - public function testEmptyKeyThrowsException() { - $toopher = new ToopherApi('', 'secret'); - } - - /** - * @expectedException InvalidArgumentException - */ - public function testEmptySecretThrowsException() { - $toopher = new ToopherApi('key', ''); - } - public function testCanCreateToopherApiWithArguments() { $toopher = new ToopherApi('key', 'secret'); } - public function testCreatePair(){ + public function testToopherVersionStringExists() { + $this->assertNotEmpty(ToopherApi::VERSION, 'no version string'); + list($major, $minor, $patch) = explode('.', ToopherApi::VERSION); + $this->assertGreaterThanOrEqual(1, (int)$major); + $this->assertGreaterThanOrEqual(0, (int)$minor); + $this->assertGreaterThanOrEqual(0, (int)$patch); + } + + public function testPair(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}}'); + $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $pairing = $toopher->pair('user', 'immediate_pair'); - $this->assertTrue($pairing->id == '1', 'bad pairing id'); - $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '1', 'bad user id'); - $this->assertTrue($pairing->user->name == 'user', 'bad user name'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } - public function testCreateSmsPair(){ + public function testPairSms(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); - $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); + $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $pairing = $toopher->pair('user', '555-555-5555'); - $this->assertTrue($pairing->id == '1', 'bad pairing id'); - $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '1', 'bad user id'); - $this->assertTrue($pairing->user->name == 'user', 'bad user name'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } - public function testCreateQrPair(){ + public function testPairQr(){ $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); - $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":"true"}}'); + $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $pairing = $toopher->pair('user'); - $this->assertTrue($pairing->id == '1', 'bad pairing id'); - $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '1', 'bad user id'); - $this->assertTrue($pairing->user->name == 'user', 'bad user name'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } - public function testGetPairingStatus(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); - $resp1->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"paired user", "toopher_authentication_enabled":"true"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/2'); - $resp2->appendBody('{"id":"2","enabled":false, "pending":false, "user":{"id":"2","name":"unpaired user", "toopher_authentication_enabled":"true"}}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + public function testAuthenticateWithPairingId(){ + $id = Uuid::uuid4()->toString(); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); - $pairing = $toopher->advanced->pairings->getById('1'); - $this->assertTrue($pairing->id == '1', 'bad pairing id'); - $this->assertTrue($pairing->enabled == true, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '1', 'bad user id'); - $this->assertTrue($pairing->user->name == 'paired user', 'bad user name'); - - $pairing = $toopher->advanced->pairings->getById('2'); - $this->assertTrue($pairing->id == '2', 'bad pairing id'); - $this->assertTrue($pairing->enabled == false, 'pairing not enabled'); - $this->assertTrue($pairing->user->id == '2', 'bad user id'); - $this->assertTrue($pairing->user->name == 'unpaired user', 'bad user name'); + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->authenticate($id, 'term name'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultAuthenticationRequest($authRequest, $id); } - public function testCreateAuthenticationWithNoAction(){ - $id = Uuid::uuid4()->toString(); - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp1); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $auth_request = $toopher->authenticate($id, 'term name'); - $this->assertTrue($auth_request->id == $id, 'wrong auth id'); - $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); - $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); - $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); - $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); - } + public function testAuthenticateWithUsername(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); - public function testGetAuthenticationStatus(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp1->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/2'); - $resp2->appendBody('{"id":"2","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $auth_request = $toopher->advanced->authenticationRequests->getById('1'); - $this->assertTrue($auth_request->id == '1', 'wrong auth id'); - $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); - $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); - $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); - $this->assertTrue($auth_request->reason == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminal->id == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminal->name == 'term name', 'wrong auth terminal name'); - - $auth_request = $toopher->advanced->authenticationRequests->getById('2'); - $this->assertTrue($auth_request->id == '2', 'wrong auth id'); - $this->assertTrue($auth_request->pending == true, 'wrong auth pending'); - $this->assertTrue($auth_request->granted == false, 'wrong auth granted'); - $this->assertTrue($auth_request->automated == false, 'wrong auth automated'); - $this->assertTrue($auth_request->reason == 'some other reason', 'wrong auth reason'); - $this->assertTrue($auth_request->terminal->id == '2', 'wrong auth terminal id'); - $this->assertTrue($auth_request->terminal->name == 'another term name', 'wrong auth terminal name'); + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->authenticate('user', '1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultAuthenticationRequest($authRequest); } public function testRawPost(){ - $id = Uuid::uuid4()->toString(); - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp1->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp1); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $params = array('pairing_id' => $id, 'terminal_name' => 'term name'); - $auth_request = $toopher->advanced->raw->post('authentication_requests/initiate', $params); - $this->assertTrue($auth_request['id'] == $id, 'wrong auth id'); - $this->assertTrue($auth_request['pending'] == false, 'wrong auth pending'); - $this->assertTrue($auth_request['granted'] == true, 'wrong auth granted'); - $this->assertTrue($auth_request['automated'] == true, 'wrong auth automated'); - $this->assertTrue($auth_request['reason'] == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request['terminal']['id'] == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request['terminal']['name'] == 'term name', 'wrong auth terminal name'); - } + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $params = array('pairing_id' => '1', 'terminal_name' => 'term name'); + $authRequest = $toopher->advanced->raw->post('authentication_requests/initiate', $params); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); + $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); + $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); + $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); + $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); + } public function testRawGet(){ - $id1 = Uuid::uuid4()->toString(); - $id2 = Uuid::uuid4()->toString(); - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id1); - $resp1->appendBody('{"id":"' . $id1 . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/' . $id2); - $resp2->appendBody('{"id":"' . $id2 . '","pending":true,"granted":false,"automated":false,"reason_code":"1","reason":"some other reason","terminal":{"id":"2","name":"another term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $auth_request = $toopher->advanced->raw->get('authentication_requests/' . $id1); - $this->assertTrue($auth_request['id'] == $id1, 'wrong auth id'); - $this->assertTrue($auth_request['pending'] == false, 'wrong auth pending'); - $this->assertTrue($auth_request['granted'] == true, 'wrong auth granted'); - $this->assertTrue($auth_request['automated'] == true, 'wrong auth automated'); - $this->assertTrue($auth_request['reason'] == 'some reason', 'wrong auth reason'); - $this->assertTrue($auth_request['terminal']['id'] == '1', 'wrong auth terminal id'); - $this->assertTrue($auth_request['terminal']['name'] == 'term name', 'wrong auth terminal name'); - - $auth_request = $toopher->advanced->raw->get('authentication_requests/' . $id2); - $this->assertTrue($auth_request['id'] == $id2, 'wrong auth id'); - $this->assertTrue($auth_request['pending'] == true, 'wrong auth pending'); - $this->assertTrue($auth_request['granted'] == false, 'wrong auth granted'); - $this->assertTrue($auth_request['automated'] == false, 'wrong auth automated'); - $this->assertTrue($auth_request['reason'] == 'some other reason', 'wrong auth reason'); - $this->assertTrue($auth_request['terminal']['id'] == '2', 'wrong auth terminal id'); - $this->assertTrue($auth_request['terminal']['name'] == 'another term name', 'wrong auth terminal name'); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->advanced->raw->get('authentication_requests/1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); + $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); + $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); + $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); + $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); + } + + public function testPairingsGetById(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->advanced->pairings->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultPairing($pairing); + } + + public function testAuthenticationRequestsGetById(){ + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->advanced->authenticationRequests->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultAuthenticationRequest($authRequest); } public function testUsersGetById(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); - $resp1->appendBody('{"id":"1","name":"paired user one","toopher_authentication_enabled":true}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/2'); - $resp2->appendBody('{"id":"2","name":"paired user two","toopher_authentication_enabled":false}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->getById('1'); - $this->assertTrue($user->id == '1', 'wrong user id'); - $this->assertTrue($user->name == 'paired user one', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); - - $user = $toopher->advanced->users->getById('2'); - $this->assertTrue($user->id == '2', 'wrong user id'); - $this->assertTrue($user->name == 'paired user two', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultUser($user); } public function testUsersGetByName(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); - $resp1->appendBody('[{"id":"1","name":"paired user","toopher_authentication_enabled":true}]'); - $this->mock->addResponse($resp1); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); + $resp->appendBody('[{"id":"1","name":"user","toopher_authentication_enabled":true}]'); + $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->getByName('paired user'); - $this->assertTrue($user->id == '1', 'wrong user id'); - $this->assertTrue($user->name == 'paired user', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultUser($user); } public function testUsersCreate(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); - $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); - $this->mock->addResponse($resp1); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); + $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->create('paired user'); - $this->assertTrue($user->id == '1', 'wrong user id'); - $this->assertTrue($user->name == 'paired user', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultUser($user); } public function testUsersCreateWithExtras(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); - $resp1->appendBody('{"id":"1","name":"paired user","toopher_authentication_enabled":true}'); - $this->mock->addResponse($resp1); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); + $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->create('paired user', array('foo'=>'bar')); - $this->assertTrue($user->id == '1', 'wrong user id'); - $this->assertTrue($user->name == 'paired user', 'wrong user name'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultUser($user); } - - public function testUserTerminalsGetById(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); - $resp1->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); - $resp2 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/2'); - $resp2->appendBody('{"id":"2", "name":"terminal two", "requester_specified_id": "requester specified id", "user":{"id":"2","name":"paired user two","toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp1); - $this->mock->addResponse($resp2); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); $toopher = new ToopherApi('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->compareToDefaultUserTerminal($userTerminal); - - $userTerminal = $toopher->advanced->userTerminals->getById('2'); - $this->assertTrue($userTerminal->id == '2', 'wrong terminal id'); - $this->assertTrue($userTerminal->name == 'terminal two', 'wrong terminal name'); - $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); - $this->assertTrue($userTerminal->user->id == '2', 'bad user id'); - $this->assertTrue($userTerminal->user->name == 'paired user two', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testUserTerminalCreate(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); - $resp1->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp1); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); + $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); $toopher = new ToopherApi('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultUserTerminal($userTerminal); } public function testUserTerminalCreateWithExtras(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); - $resp1->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp1); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); + $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); $toopher = new ToopherApi('key', 'secret', '', $this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id', array('foo'=>'bar')); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultUserTerminal($userTerminal); } + /** + * @expectedException InvalidArgumentException + */ + public function testEmptyKeyThrowsException() { + $toopher = new ToopherApi('', 'secret'); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testEmptySecretThrowsException() { + $toopher = new ToopherApi('key', ''); } /** * @expectedException ToopherRequestException */ public function testToopherRequestException(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 401 Unauthorized", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp1->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); - $this->mock->addResponse($resp1); - - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $resp = new HTTP_Request2_Response("HTTP/1.1 401 Unauthorized", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } - public function testToopherVersionStringExists() { - $this->assertNotEmpty(ToopherApi::VERSION, 'no version string'); - list($major, $minor, $patch) = explode('.', ToopherApi::VERSION); - $this->assertGreaterThanOrEqual(1, (int)$major); - $this->assertGreaterThanOrEqual(0, (int)$minor); - $this->assertGreaterThanOrEqual(0, (int)$patch); - } - /** * @expectedException ToopherRequestException */ public function test400WithEmptyBodyRaisesToopherRequestException(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $this->mock->addResponse($resp1); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } @@ -347,10 +323,10 @@ public function test400WithEmptyBodyRaisesToopherRequestException(){ * @expectedException ToopherRequestException */ public function test400WithUnprintableBodyRaisesToopherRequestException(){ - $resp1 = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp1->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); - $this->mock->addResponse($resp1); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } } diff --git a/test/UserTerminalTest.php b/test/UserTerminalTest.php index 411d9e6..fefbe2f 100644 --- a/test/UserTerminalTest.php +++ b/test/UserTerminalTest.php @@ -52,7 +52,7 @@ public function testUserTerminalRefreshFromServer(){ $resp->appendBody('{"id":"1", "name":"terminal name changed", "requester_specified_id":"requester specified id changed", "user":{"id":"1", "name":"user name changed", "toopher_authentication_enabled":false}}'); $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $userTerminal = $this->getUserTerminal($toopher); $userTerminal->refreshFromServer(); From a322f591e211889ce53e2c681a99437e334fd919 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 16:20:20 -0600 Subject: [PATCH 056/114] Use camelCase for variables --- lib/toopher_api.php | 162 ++++++++++++++--------------- test/AuthenticationRequestTest.php | 58 +++++------ test/PairingTest.php | 2 +- 3 files changed, 111 insertions(+), 111 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index ece0511..a0e537e 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -211,21 +211,21 @@ function __construct($key, $secret, $baseUrl = '', $httpAdapter = NULL) $this->advanced = new AdvancedApiUsageFactory($key, $secret, $baseUrl, $httpAdapter, $this); } - public function pair($username, $phrase_or_num = '', $kwargs = array()) + public function pair($username, $phraseOrNumber = '', $kwargs = array()) { $params = array('user_name' => $username); $params = array_merge($params, $kwargs); - if (!empty($phrase_or_num)) + if (!empty($phraseOrNumber)) { - if(preg_match('/\d/', $phrase_or_num, $match)) + if(preg_match('/\d/', $phraseOrNumber, $match)) { $url = 'pairings/create/sms'; - $params['phone_number'] = $phrase_or_num; + $params['phone_number'] = $phraseOrNumber; } else { $url = 'pairings/create'; - $params['pairing_phrase'] = $phrase_or_num; + $params['pairing_phrase'] = $phraseOrNumber; } } else @@ -236,21 +236,21 @@ public function pair($username, $phrase_or_num = '', $kwargs = array()) return new Pairing($result, $this); } - public function authenticate($id_or_username, $terminal, $actionName = '', $kwargs = array()) + public function authenticate($pairingIdOrUsername, $terminal, $actionName = '', $kwargs = array()) { $url = 'authentication_requests/initiate'; - $uuid_pattern = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; - if(preg_match($uuid_pattern, $id_or_username, $match)) + $uuidPattern = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; + if(preg_match($uuidPattern, $pairingIdOrUsername, $match)) { $params = array( - 'pairing_id' => $id_or_username, + 'pairing_id' => $pairingIdOrUsername, 'terminal_name' => $terminal ); } else { $params = array( - 'user_name' => $id_or_username, + 'user_name' => $pairingIdOrUsername, 'requester_specified_terminal_id' => $terminal ); } @@ -329,7 +329,7 @@ public function get_raw($endpoint) return $this->request('GET', $endpoint, array(), true); } - private function request($method, $endpoint, $parameters = array(), $raw_request = false) + private function request($method, $endpoint, $parameters = array(), $rawRequest = false) { $req = new HTTP_Request2(); $req->setAdapter($this->httpAdapter); @@ -365,11 +365,11 @@ private function request($method, $endpoint, $parameters = array(), $raw_request $err = json_decode($resultBody, true); if ($err === NULL) { - $json_error = $this->json_error_to_string(json_last_error()); - if (!empty($json_error)) { - error_log(sprintf("Error parsing response body JSON: %s", $json_error)); + $jsonError = $this->json_error_to_string(json_last_error()); + if (!empty($jsonError)) { + error_log(sprintf("Error parsing response body JSON: %s", $jsonError)); error_log(sprintf("response body: %s", $result->getBody())); - throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $json_error)); + throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $jsonError)); } } else { if(array_key_exists("error_message", $err)) { @@ -380,25 +380,25 @@ private function request($method, $endpoint, $parameters = array(), $raw_request } } - if ($raw_request) + if ($rawRequest) { return $resultBody; } else { $decoded = json_decode($resultBody, true); if ($decoded === NULL) { - $json_error = $this->json_error_to_string(json_last_error()); - if (!empty($json_error)) { - error_log(sprintf("Error parsing response body JSON: %s", $json_error)); + $jsonError = $this->json_error_to_string(json_last_error()); + if (!empty($jsonError)) { + error_log(sprintf("Error parsing response body JSON: %s", $jsonError)); error_log(sprintf("response body: %s", $result->getBody())); - throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $json_error)); + throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $jsonError)); } } return $decoded; } } - private function json_error_to_string($json_error_code) { - switch ($json_error_code) { + private function json_error_to_string($jsonErrorCode) { + switch ($jsonErrorCode) { case JSON_ERROR_NONE: return NULL; case JSON_ERROR_DEPTH: @@ -496,14 +496,14 @@ class Pairing { protected $api; - function __construct($json_response, $api) + function __construct($jsonResponse, $api) { $this->api = $api; - $this->id = $json_response['id']; - $this->enabled = $json_response['enabled']; - $this->pending = $json_response['pending']; - $this->user = new User($json_response['user'], $api); - $this->raw_response = $json_response; + $this->id = $jsonResponse['id']; + $this->enabled = $jsonResponse['enabled']; + $this->pending = $jsonResponse['pending']; + $this->user = new User($jsonResponse['user'], $api); + $this->raw_response = $jsonResponse; } public function refreshFromServer() @@ -543,12 +543,12 @@ public function getQrCodeImage() return $this->api->advanced->raw->get_raw($url); } - private function update($json_response) + private function update($jsonResponse) { - $this->enabled = $json_response['enabled']; - $this->pending = $json_response['pending']; - $this->user->update($json_response['user']); - $this->raw_response = $json_response; + $this->enabled = $jsonResponse['enabled']; + $this->pending = $jsonResponse['pending']; + $this->user->update($jsonResponse['user']); + $this->raw_response = $jsonResponse; } } @@ -556,19 +556,19 @@ class AuthenticationRequest { protected $api; - function __construct($json_response, $api) + function __construct($jsonResponse, $api) { $this->api = $api; - $this->id = $json_response['id']; - $this->pending = $json_response['pending']; - $this->granted = $json_response['granted']; - $this->automated = $json_response['automated']; - $this->reason_code = $json_response['reason_code']; - $this->reason = $json_response['reason']; - $this->terminal = new UserTerminal($json_response['terminal'], $api); - $this->user = new User($json_response['user'], $api); - $this->action = new Action($json_response['action']); - $this->raw_response = $json_response; + $this->id = $jsonResponse['id']; + $this->pending = $jsonResponse['pending']; + $this->granted = $jsonResponse['granted']; + $this->automated = $jsonResponse['automated']; + $this->reason_code = $jsonResponse['reason_code']; + $this->reason = $jsonResponse['reason']; + $this->terminal = new UserTerminal($jsonResponse['terminal'], $api); + $this->user = new User($jsonResponse['user'], $api); + $this->action = new Action($jsonResponse['action']); + $this->raw_response = $jsonResponse; } public function refreshFromServer() @@ -587,17 +587,17 @@ public function grantWithOtp($otp, $kwargs = array()) $this->update($result); } - private function update($json_response) + private function update($jsonResponse) { - $this->pending = $json_response['pending']; - $this->granted = $json_response['granted']; - $this->automated = $json_response['automated']; - $this->reason_code = $json_response['reason_code']; - $this->reason = $json_response['reason']; - $this->terminal->update($json_response['terminal']); - $this->user->update($json_response['user']); - $this->action->update($json_response['action']); - $this->raw_respones = $json_response; + $this->pending = $jsonResponse['pending']; + $this->granted = $jsonResponse['granted']; + $this->automated = $jsonResponse['automated']; + $this->reason_code = $jsonResponse['reason_code']; + $this->reason = $jsonResponse['reason']; + $this->terminal->update($jsonResponse['terminal']); + $this->user->update($jsonResponse['user']); + $this->action->update($jsonResponse['action']); + $this->raw_respones = $jsonResponse; } } @@ -605,13 +605,13 @@ class User { protected $api; - function __construct($json_response, $api) + function __construct($jsonResponse, $api) { $this->api = $api; - $this->id = $json_response['id']; - $this->name = $json_response['name']; - $this->toopher_authentication_enabled = $json_response['toopher_authentication_enabled']; - $this->raw_response = $json_response; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; + $this->raw_response = $jsonResponse; } public function refreshFromServer() @@ -635,11 +635,11 @@ public function disableToopherAuthentication() $this->update($result); } - public function update($json_response) + public function update($jsonResponse) { - $this->name = $json_response['name']; - $this->toopher_authentication_enabled = $json_response['toopher_authentication_enabled']; - $this->raw_response = $json_response; + $this->name = $jsonResponse['name']; + $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; + $this->raw_response = $jsonResponse; } } @@ -647,14 +647,14 @@ class UserTerminal { protected $api; - function __construct($json_response, $api) + function __construct($jsonResponse, $api) { $this->api = $api; - $this->id = $json_response['id']; - $this->name = $json_response['name']; - $this->requester_specified_id = $json_response['requester_specified_id']; - $this->user = new User($json_response['user'], $api); - $this->raw_response = $json_response; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->requester_specified_id = $jsonResponse['requester_specified_id']; + $this->user = new User($jsonResponse['user'], $api); + $this->raw_response = $jsonResponse; } public function refreshFromServer() @@ -664,28 +664,28 @@ public function refreshFromServer() $this->update($result); } - public function update($json_response) + public function update($jsonResponse) { - $this->name = $json_response['name']; - $this->requester_specified_id = $json_response['requester_specified_id']; - $this->user->update($json_response['user']); - $this->raw_response = $json_response; + $this->name = $jsonResponse['name']; + $this->requester_specified_id = $jsonResponse['requester_specified_id']; + $this->user->update($jsonResponse['user']); + $this->raw_response = $jsonResponse; } } class Action { - function __construct($json_response) + function __construct($jsonResponse) { - $this->id = $json_response['id']; - $this->name = $json_response['name']; - $this->raw_response = $json_response; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->raw_response = $jsonResponse; } - public function update($json_response) + public function update($jsonResponse) { - $this->name = $json_response['name']; - $this->raw_response = $json_response; + $this->name = $jsonResponse['name']; + $this->raw_response = $jsonResponse; } } diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php index 6d5f32d..b1d16d8 100644 --- a/test/AuthenticationRequestTest.php +++ b/test/AuthenticationRequestTest.php @@ -40,21 +40,21 @@ protected function getAuthenticationRequest($api) public function testAuthenticationRequest() { - $auth_request = $this->getAuthenticationRequest($this->getToopherApi()); - $this->assertTrue($auth_request->id == '1', 'Authentication request id was incorrect'); - $this->assertTrue($auth_request->pending == true, 'Authentication request should be pending'); - $this->assertTrue($auth_request->granted == false, 'Authentication request should not be granted'); - $this->assertTrue($auth_request->automated == false, 'Authentication request should not be automated'); - $this->assertTrue($auth_request->reason_code == '1', 'Authentication request reason code was incorrect'); - $this->assertTrue($auth_request->reason == 'some reason', 'Authentication request reason was incorrect'); - $this->assertTrue($auth_request->terminal->id == '1', 'Terminal id was incorrect'); - $this->assertTrue($auth_request->terminal->name == 'term name', 'Terminal name was incorrect'); - $this->assertTrue($auth_request->terminal->requester_specified_id == '1', 'Terminal requester_specified_id was incorrect'); - $this->assertTrue($auth_request->user->id == '1', 'User id was incorrect'); - $this->assertTrue($auth_request->user->name == 'user', 'User name was incorrect'); - $this->assertTrue($auth_request->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); - $this->assertTrue($auth_request->action->id == '1', 'Action id was incorrect'); - $this->assertTrue($auth_request->action->name == 'test', 'Action name was incorrect'); + $authRequest = $this->getAuthenticationRequest($this->getToopherApi()); + $this->assertTrue($authRequest->id == '1', 'Authentication request id was incorrect'); + $this->assertTrue($authRequest->pending == true, 'Authentication request should be pending'); + $this->assertTrue($authRequest->granted == false, 'Authentication request should not be granted'); + $this->assertTrue($authRequest->automated == false, 'Authentication request should not be automated'); + $this->assertTrue($authRequest->reason_code == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest->reason == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest->terminal->id == '1', 'Terminal id was incorrect'); + $this->assertTrue($authRequest->terminal->name == 'term name', 'Terminal name was incorrect'); + $this->assertTrue($authRequest->terminal->requester_specified_id == '1', 'Terminal requester_specified_id was incorrect'); + $this->assertTrue($authRequest->user->id == '1', 'User id was incorrect'); + $this->assertTrue($authRequest->user->name == 'user', 'User name was incorrect'); + $this->assertTrue($authRequest->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + $this->assertTrue($authRequest->action->id == '1', 'Action id was incorrect'); + $this->assertTrue($authRequest->action->name == 'test', 'Action name was incorrect'); } public function testAuthenticationRequestRefreshFromServer(){ @@ -63,17 +63,17 @@ public function testAuthenticationRequestRefreshFromServer(){ $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); - $auth_request = $this->getAuthenticationRequest($toopher); + $authRequest = $this->getAuthenticationRequest($toopher); - $auth_request->refreshFromServer(); + $authRequest->refreshFromServer(); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->assertTrue($auth_request->pending == false, 'Authentication request should not be pending'); - $this->assertTrue($auth_request->granted == true, 'Authentication request should be granted'); - $this->assertTrue($auth_request->automated == true, 'Authentication request should be automated'); - $this->assertTrue($auth_request->reason == 'some other reason', 'Authentication request reason was incorrect'); - $this->assertTrue($auth_request->terminal->name == 'term name changed', 'Terminal name was incorrect'); - $this->assertTrue($auth_request->user->name == 'user changed', 'User name was incorrect'); - $this->assertTrue($auth_request->action->name == 'test changed', 'Action name was incorrect'); + $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest->automated == true, 'Authentication request should be automated'); + $this->assertTrue($authRequest->reason == 'some other reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest->terminal->name == 'term name changed', 'Terminal name was incorrect'); + $this->assertTrue($authRequest->user->name == 'user changed', 'User name was incorrect'); + $this->assertTrue($authRequest->action->name == 'test changed', 'Action name was incorrect'); } public function testGrantAuthenticationRequestWithOtp(){ @@ -82,13 +82,13 @@ public function testGrantAuthenticationRequestWithOtp(){ $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); - $auth_request = $this->getAuthenticationRequest($toopher); + $authRequest = $this->getAuthenticationRequest($toopher); - $auth_request->grantWithOtp('otp'); + $authRequest->grantWithOtp('otp'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->assertTrue($auth_request->pending == false, 'wrong auth pending'); - $this->assertTrue($auth_request->granted == true, 'wrong auth granted'); - $this->assertTrue($auth_request->automated == true, 'wrong auth automated'); + $this->assertTrue($authRequest->pending == false, 'wrong auth pending'); + $this->assertTrue($authRequest->granted == true, 'wrong auth granted'); + $this->assertTrue($authRequest->automated == true, 'wrong auth automated'); } } diff --git a/test/PairingTest.php b/test/PairingTest.php index a07ee5b..d0575e0 100644 --- a/test/PairingTest.php +++ b/test/PairingTest.php @@ -103,7 +103,7 @@ public function testPairingGetQrCodeImage(){ $toopher = $this->getToopherApi($this->mock); $pairing = $this->getPairing($toopher); - $qr_image = $pairing->getQrCodeImage(); + $pairing->getQrCodeImage(); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/qr/pairings/1', "Last called url should be 'https://api.toopher.com/v1/qr/pairings/1'"); } From 9ef57923e94d18d2d3d5fedaf02a4e2c5d2f6067 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 17:44:32 -0600 Subject: [PATCH 057/114] Refactor ToopherApi.authenticate --- lib/toopher_api.php | 20 +++++++++++--------- test/ToopherApiTest.php | 2 +- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/lib/toopher_api.php b/lib/toopher_api.php index a0e537e..b6e25f8 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -236,29 +236,31 @@ public function pair($username, $phraseOrNumber = '', $kwargs = array()) return new Pairing($result, $this); } - public function authenticate($pairingIdOrUsername, $terminal, $actionName = '', $kwargs = array()) + public function authenticate($pairingIdOrUsername, $terminalName = NULL, $requesterSpecifiedId = NULL, $actionName = NULL, $kwargs = array()) { $url = 'authentication_requests/initiate'; $uuidPattern = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; if(preg_match($uuidPattern, $pairingIdOrUsername, $match)) { - $params = array( - 'pairing_id' => $pairingIdOrUsername, - 'terminal_name' => $terminal - ); + $params = array('pairing_id' => $pairingIdOrUsername); } else { - $params = array( - 'user_name' => $pairingIdOrUsername, - 'requester_specified_terminal_id' => $terminal - ); + $params = array('user_name' => $pairingIdOrUsername); } if(!empty($actionName)) { $params['action_name'] = $actionName; } + if(!empty($terminalName)) + { + $params['terminal_name'] = $terminalName; + } + if(!empty($requesterSpecifiedId)) + { + $params['requester_specified_terminal_id'] = $requesterSpecifiedId; + } $params = array_merge($params, $kwargs); $result = $this->advanced->raw->post($url, $params); return new AuthenticationRequest($result, $this); diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index f77ea90..19cc5b8 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -141,7 +141,7 @@ public function testAuthenticateWithUsername(){ $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->authenticate('user', '1'); + $authRequest = $toopher->authenticate('user', 'term name', '1'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultAuthenticationRequest($authRequest); } From d2e69beddd77de08a09ab6220bfee705d908cb30 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 17:44:49 -0600 Subject: [PATCH 058/114] Update PHP demo --- demo/toopher_demo.php | 120 ++++++++++++++++++++++++++++++++---------- 1 file changed, 93 insertions(+), 27 deletions(-) diff --git a/demo/toopher_demo.php b/demo/toopher_demo.php index bbccc5e..660c9de 100644 --- a/demo/toopher_demo.php +++ b/demo/toopher_demo.php @@ -29,45 +29,111 @@ $key = getenv('TOOPHER_CONSUMER_KEY'); $secret = getenv('TOOPHER_CONSUMER_SECRET'); if(empty($key) || empty($secret)){ - echo("enter consumer credentials (set environment variables to prevent prompting):\n"); - echo("TOOPHER_CONSUMER_KEY="); + echo("Enter your requester credentials (from https://dev.toopher.com).\n"); + echo("Hint: Set the TOOPHER_CONSUMER_SECRET and TOOPHER_CONSUMER_SECRET environment variables to avoid this prompt.\n"); + echo("Consumer Key:"); $key = rtrim(fgets($stdin)); - echo("TOOPHER_CONSUMER_SECRET="); + echo("Consumer Secret:"); $secret = rtrim(fgets($stdin)); } -echo ("using key=$key, secret=$secret\n"); +echo ("Using Consumer Key=$key, Consumer Secret=$secret\n"); $toopher = new ToopherApi($key, $secret); -echo("\nSTEP 1: Pair device\n"); -echo("enter pairing phrase:"); -$phrase = rtrim(fgets($stdin)); -echo("enter user name:"); -$userName = rtrim(fgets($stdin)); +while(true) { + while(true) { + echo("\nSTEP 1: Pair requester with phone\n"); + echo("----------------------------------------\n"); + echo("Pairing phrases are generated on the mobile app\n"); -$pairing = $toopher->pair($phrase, $userName); + do { + echo("Enter pairing phrase: "); + $phrase = rtrim(fgets($stdin)); + } while (empty($phrase)); -while(!$pairing['enabled']){ - echo("waiting for authorization...\n"); - sleep(1); - $pairing = $toopher->getPairingStatus($pairing['id']); + do { + echo("Enter user name: "); + $userName = rtrim(fgets($stdin)); + } while (empty($userName)); + + try { + $pairing = $toopher->pair($userName, $phrase); + break; + } catch (Exception $e) { + echo ("The pairing phrase was not accepted (Reason:$e)"); + } + } + + while(true) { + echo("Authorize pairing on phone and then press return to continue."); + rtrim(fgets($stdin)); + echo("\nChecking status of pairing request...\n"); + + try { + $pairing->refreshFromServer(); + if ($pairing->pending) { + echo("The pairing has not been authorized by the phone yet.\n"); + } elseif ($pairing->enabled) { + echo("Pairing complete\n"); + break 2; + } else { + echo("The pairing has been denied.\n"); + exit(0); + } + } catch (Exception $e) { + echo ("Could not check pairing status (Reason: $e)"); + } + } + + // while($pairing['pending']){ + // echo("Waiting for authorization...\n"); + // sleep(2); + // $pairing->refreshFromServer(); + // } + // + // if ($pairing->granted){ + // echo("Pairing complete!\n"); + // } else { + // echo("The pairing has been denied.\n"); + // } } -echo("paired successfully!\n"); -echo("\nSTEP 2: Authenticate login\n"); -echo("enter terminal name:"); -$terminalName = rtrim(fgets($stdin)); -echo("enter action name, or [ENTER] for none:"); while(true){ - $action = rtrim(fgets($stdin)); - echo("sending authentication request...\n"); - $auth = $toopher->authenticate($pairing['id'], $terminalName, $action); - while($auth['pending']){ - echo("waiting for authentication...\n"); - sleep(1); - $auth = $toopher->getAuthenticationStatus($auth['id']); + echo("\nSTEP 2: Authenticate log in\n"); + echo("----------------------------------------\n"); + do { + echo("Enter a terminal name for this authentication request [my computer]:"); + $terminalName = rtrim(fgets($stdin)); + } while (empty($terminalName)); + + echo("Sending authentication request...\n"); + try { + $auth = $toopher->authenticate($pairing->user->name, $terminalName); + } catch (Exception $e) { + echo ("Error initiating authentication (Reason: $e)"); + } + + while(true) { + echo ("Respond to authentication request on phone and then press return to continue."); + rtrim(fgets($stdin)); + echo ("\nChecking status of authenticationr request...\n"); + + try { + $auth->refreshFromServer(); + } catch (Exception $e) { + echo ("Could not check authentication status (Reason: $e)"); } - echo("Successfully authorized action '$action'. Enter another action to authorize again, or [Ctrl+C] to exit:"); + if ($auth->pending) { + echo ("The authentication request has not received a response from the phone yet.\n"); + } else { + $automation = $auth->automated ? 'automatically ' : ''; + $result = $auth->granted ? 'granted' : 'denied'; + echo ("The request was " . $automation . $result . "!\n" ); + break; + } + } + echo("Press return to authenticate again, or [Ctrl+C] to exit"); + rtrim(fgets($stdin)); } ?> From 449b03dc879ecbac1342a741f841988834641aeb Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 18:00:34 -0600 Subject: [PATCH 059/114] Update PHP README --- README.md | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index e551220..5262625 100644 --- a/README.md +++ b/README.md @@ -29,23 +29,28 @@ This library makes it super simple to do the Toopher two-step. Check it out: require_once("toopher_api.php"); // Create an API object using your credentials -$toopherApi = new ToopherApi($key, $secret); +$toopherApi = new ToopherApi("", ""); // Step 1 - Pair with their phone's Toopher app -$pairing = $toopherApi->pair("pairing phrase", "username@yourservice.com"); +// With pairing phrase +$pairing = $toopherApi->pair("username@yourservice.com", "pairing phrase"); +// With SMS +$pairing = $toopherApi->pair("username@yourservice.com", "555-555-5555"); +// With QR code +$pairing = $toopherApi->pair("username@yourservice.com"); + // Step 2 - Authenticate a log in -$authStatus = $toopherApi->authenticate($pairingStatus['id'], "my computer"); +// With a pairing id and terminal name +$authRequest = $toopherApi->authenticate($pairing->id, "my computer"); +// With a username, terminal name and requester specified terminal id +$authRequest = $toopherApi->authenticate("username", "my computer", "requester specified id"); + // Once they've responded you can then check the status -while($authStatus['pending']){ - $authStatus = $toopherApi->getAuthenticationStatus($authStatus['id']); - sleep(1); -} -if($authStatus['granted']){ - // Success! -} else { - // user declined the authorization! +$authRequest->refreshFromServer(); +if ($authRequest->pending == false && $authRequest->granted == true) { + // Success! } ``` From bc6d68abad98784c9fa18521eeb3a19d7916a4e0 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Feb 2015 18:15:55 -0600 Subject: [PATCH 060/114] Update composer --- composer.json | 4 ++-- composer.lock | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index a99dc74..d93438f 100644 --- a/composer.json +++ b/composer.json @@ -22,9 +22,9 @@ "require":{ "php": ">=5.3.0", "ext-json": "*", + "ext-oauth": "*", "pear-pear.php.net/HTTP_Request2": ">=2.1.1", - "pear-pear.php.net/HTTP_OAuth": ">=0.2.3", - "ext-oauth": "*" + "pear-pear.php.net/HTTP_OAuth": ">=0.2.3" }, "require-dev" : { "phpunit/phpunit": "3.7.*", diff --git a/composer.lock b/composer.lock index a1e2b80..bb7562b 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "2c3bc139cd3c8e3a096ed8c14f2b50c3", + "hash": "aa7afd273d0e396bc4d44cf727aaa41b", "packages": [ { "name": "pear-pear.php.net/Archive_Tar", From cb3b2e6708baa65bb8db7434cf1a294b8ae8ed1a Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 25 Feb 2015 12:42:10 -0600 Subject: [PATCH 061/114] Use composer package for ToopherIframe OAuth --- composer.json | 2 +- composer.lock | 47 ++++++++++++++++++++++++++++++--- lib/toopher_api.php | 54 ++++++++++++++++++++++++++++---------- test/ToopherIframeTest.php | 8 +++--- 4 files changed, 89 insertions(+), 22 deletions(-) diff --git a/composer.json b/composer.json index d93438f..c0f7bd1 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ "require":{ "php": ">=5.3.0", "ext-json": "*", - "ext-oauth": "*", + "vclayton/unpecl-oauth": "dev-master", "pear-pear.php.net/HTTP_Request2": ">=2.1.1", "pear-pear.php.net/HTTP_OAuth": ">=0.2.3" }, diff --git a/composer.lock b/composer.lock index bb7562b..950c961 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "aa7afd273d0e396bc4d44cf727aaa41b", + "hash": "584d9805081fa7f847fac815ad93ecea", "packages": [ { "name": "pear-pear.php.net/Archive_Tar", @@ -246,6 +246,47 @@ "BSD License" ], "description": "Selection of methods that are often needed when working with XML documents. Functionality includes creating of attribute lists from arrays, creation of tags, validation of XML names and more." + }, + { + "name": "vclayton/unpecl-oauth", + "version": "dev-master", + "source": { + "type": "git", + "url": "https://github.com/vclayton/unpecl-oauth.git", + "reference": "4ecff17a564d50fc874f86729d611a46088d42cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/vclayton/unpecl-oauth/zipball/4ecff17a564d50fc874f86729d611a46088d42cf", + "reference": "4ecff17a564d50fc874f86729d611a46088d42cf", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "ext-hash": "*", + "ext-openssl": "*", + "php": ">=5.1.0" + }, + "type": "library", + "autoload": { + "psr-0": { + "": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Native PHP drop-in replacement for the PECL OAuth extension", + "homepage": "https://github.com/vclayton/unpecl-oauth", + "keywords": [ + "oauth", + "pecl" + ], + "time": "2014-09-30 13:23:17" } ], "packages-dev": [ @@ -1194,14 +1235,14 @@ "aliases": [], "minimum-stability": "stable", "stability-flags": { + "vclayton/unpecl-oauth": 20, "satooshi/php-coveralls": 20 }, "prefer-stable": false, "prefer-lowest": false, "platform": { "php": ">=5.3.0", - "ext-json": "*", - "ext-oauth": "*" + "ext-json": "*" }, "platform-dev": [] } diff --git a/lib/toopher_api.php b/lib/toopher_api.php index b6e25f8..0f8b4f4 100644 --- a/lib/toopher_api.php +++ b/lib/toopher_api.php @@ -40,6 +40,8 @@ function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') $this->baseUrl = $baseUrl; $this->timestampOverride = NULL; $this->nonceOverride = NULL; + $this->oauthVersion = '1.0'; + $this->signatureMethod = 'HMAC-SHA1'; } public function setTimestampOverride($timestampOverride) @@ -165,24 +167,48 @@ private function signature($secret, $parameters) return base64_encode($sig); } - private function getOauthSignedUrl($url, $params) + private function getOauthSignedUrl($url, $queryParams) { - if (!is_null($this->timestampOverride)) { - $this->oauthConsumer->setTimestamp($this->timestampOverride); - } + $oauthParams = $this->getOauthParams(); + $encodedParams = $this->encodeParamsForSignature(array_merge($queryParams, $oauthParams)); + $signature = $this->oauthConsumer->generateSignature('GET', $url, $encodedParams); + $oauthParams['oauth_signature'] = $signature; + return $this->buildUrl($url, $queryParams, $oauthParams); + } + + private function encodeParamsForSignature($params) + { + foreach ($params as $key => $value) { + $params[$key] = oauth_urlencode($value); + }; + return $params; + } + + private function getOauthParams() + { + $oauthParams = array( + 'oauth_consumer_key' => $this->consumerKey, + 'oauth_signature_method' => $this->signatureMethod, + 'oauth_version' => $this->oauthVersion + ); if (!is_null($this->nonceOverride)) { - $this->oauthConsumer->setNonce($this->nonceOverride); + $oauthParams['oauth_nonce'] = $this->nonceOverride; + } else { + $oauthParams['oauth_nonce'] = uniqid().'.'.time(); } - - $oauthHeaderString = $this->oauthConsumer->getRequestHeader('GET', $url, $params); - $oauthHeaderArray = explode(",", str_replace("OAuth ", "", $oauthHeaderString)); - $oauthParams = array(); - foreach ($oauthHeaderArray as $value) { - $oauthParams[] = str_replace("\"", "", $value); + if (!is_null($this->timestampOverride)) { + $oauthParams['oauth_timestamp'] = $this->timestampOverride; + } else { + $oauthParams['oauth_timestamp'] = time(); } - $oauthParams = implode("&", $oauthParams); - $queryParams = http_build_query($params); - return $url . '?' . $queryParams . '&' . $oauthParams; + return $oauthParams; + } + + private function buildUrl($url, $queryParams, $oauthParams) + { + $query = http_build_query($queryParams); + $oauthQuery = http_build_query($oauthParams); + return $url . '?' . $query . '&' . $oauthQuery; } } diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 13e2f12..d32d1f9 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -66,7 +66,7 @@ public function testToopherIframeGetAuthenticationUrl() { $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D"; + $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D"; $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } @@ -76,7 +76,7 @@ public function testToopherIframeGetAuthenticationUrlWithExtras() $extras = array("allow_inline_pairing" => "false"); $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D"; + $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D"; $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'None', $extras); $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } @@ -85,7 +85,7 @@ public function testToopherIframeGetUserManagementUrl() { $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D"; + $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D"; $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com'); $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } @@ -95,7 +95,7 @@ public function testToopherIframeGetUserManagementUrlWithExtras() $extras = array("ttl" => "100"); $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_nonce=12345678&oauth_timestamp=1000&oauth_version=1.0&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D"; + $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D"; $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com', $extras); $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } From 5312e6d28693f74ac1f232925d5f7abcf1e44c46 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 25 Feb 2015 13:05:35 -0600 Subject: [PATCH 062/114] Remove old demo code --- demo/toopher_demo.php | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/demo/toopher_demo.php b/demo/toopher_demo.php index 660c9de..7bec1f4 100644 --- a/demo/toopher_demo.php +++ b/demo/toopher_demo.php @@ -84,18 +84,6 @@ echo ("Could not check pairing status (Reason: $e)"); } } - - // while($pairing['pending']){ - // echo("Waiting for authorization...\n"); - // sleep(2); - // $pairing->refreshFromServer(); - // } - // - // if ($pairing->granted){ - // echo("Pairing complete!\n"); - // } else { - // echo("The pairing has been denied.\n"); - // } } while(true){ From ec7f170d6cf2fbf9bf502820dba788b6df5eb799 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 25 Feb 2015 17:12:50 -0600 Subject: [PATCH 063/114] Try to fix coveralls --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 0a7eb47..a991c74 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,6 @@ php: before_script: composer install script: - mkdir -p build/logs - - php vendor/bin/phpunit -c phpunit.xml.dist + - php vendor/bin/phpunit test after_script: - php vendor/bin/coveralls -v From 5980ab6dc0eff00e9e7175309844b1568ad3d923 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 25 Feb 2015 18:08:56 -0600 Subject: [PATCH 064/114] Simplify Pairing test --- test/PairingTest.php | 35 +++++++++++++++-------------------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/test/PairingTest.php b/test/PairingTest.php index d0575e0..bc7696c 100644 --- a/test/PairingTest.php +++ b/test/PairingTest.php @@ -51,19 +51,19 @@ public function testPairing(){ public function testPairingRefreshFromServer(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); - $resp->appendBody('{"id":"1","enabled":false,"pending":true,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":false}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $pairing = $this->getPairing($toopher); - - $pairing->refreshFromServer(); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->assertTrue($pairing->enabled == false, 'Pairing should not be enabled'); - $this->assertTrue($pairing->pending == true, 'Pairing should be pending'); - $this->assertTrue($pairing->user->name == 'user name changed', 'User name was incorrect'); - $this->assertTrue($pairing->user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp->appendBody('{"id":"1","enabled":false,"pending":true,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":false}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); + + $pairing->refreshFromServer(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->assertTrue($pairing->enabled == false, 'Pairing should not be enabled'); + $this->assertTrue($pairing->pending == true, 'Pairing should be pending'); + $this->assertTrue($pairing->user->name == 'user name changed', 'User name was incorrect'); + $this->assertTrue($pairing->user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); } public function testGetPairingResetLink(){ @@ -86,13 +86,8 @@ public function testEmailPairingResetLink(){ $toopher = $this->getToopherApi($this->mock); $pairing = $this->getPairing($toopher); - try { - $pairing->emailResetLink('jdoe@example.com'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - } - catch(Exception $e) { - $this->fail('Unexpected exception has been raised: ' . $e); - } + $pairing->emailResetLink('jdoe@example.com'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); } public function testPairingGetQrCodeImage(){ From 4eb86f1b99674ad83b1b241a7d2c819a8fd4f487 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 25 Feb 2015 18:09:06 -0600 Subject: [PATCH 065/114] Fix spacing in tests --- test/AuthenticationRequestTest.php | 48 +++---- test/PairingTest.php | 40 +++--- test/ToopherApiTest.php | 218 ++++++++++++++--------------- test/ToopherIframeTest.php | 10 +- 4 files changed, 158 insertions(+), 158 deletions(-) diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php index b1d16d8..a388d0a 100644 --- a/test/AuthenticationRequestTest.php +++ b/test/AuthenticationRequestTest.php @@ -58,37 +58,37 @@ public function testAuthenticationRequest() } public function testAuthenticationRequestRefreshFromServer(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user changed", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user changed", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test changed"}}'); - $this->mock->addResponse($resp); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user changed", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user changed", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test changed"}}'); + $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $authRequest = $this->getAuthenticationRequest($toopher); + $toopher = $this->getToopherApi($this->mock); + $authRequest = $this->getAuthenticationRequest($toopher); - $authRequest->refreshFromServer(); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); - $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); - $this->assertTrue($authRequest->automated == true, 'Authentication request should be automated'); - $this->assertTrue($authRequest->reason == 'some other reason', 'Authentication request reason was incorrect'); - $this->assertTrue($authRequest->terminal->name == 'term name changed', 'Terminal name was incorrect'); - $this->assertTrue($authRequest->user->name == 'user changed', 'User name was incorrect'); - $this->assertTrue($authRequest->action->name == 'test changed', 'Action name was incorrect'); + $authRequest->refreshFromServer(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest->automated == true, 'Authentication request should be automated'); + $this->assertTrue($authRequest->reason == 'some other reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest->terminal->name == 'term name changed', 'Terminal name was incorrect'); + $this->assertTrue($authRequest->user->name == 'user changed', 'User name was incorrect'); + $this->assertTrue($authRequest->action->name == 'test changed', 'Action name was incorrect'); } public function testGrantAuthenticationRequestWithOtp(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1/otp_auth'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1/otp_auth'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $authRequest = $this->getAuthenticationRequest($toopher); + $toopher = $this->getToopherApi($this->mock); + $authRequest = $this->getAuthenticationRequest($toopher); - $authRequest->grantWithOtp('otp'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->assertTrue($authRequest->pending == false, 'wrong auth pending'); - $this->assertTrue($authRequest->granted == true, 'wrong auth granted'); - $this->assertTrue($authRequest->automated == true, 'wrong auth automated'); + $authRequest->grantWithOtp('otp'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($authRequest->pending == false, 'wrong auth pending'); + $this->assertTrue($authRequest->granted == true, 'wrong auth granted'); + $this->assertTrue($authRequest->automated == true, 'wrong auth automated'); } } diff --git a/test/PairingTest.php b/test/PairingTest.php index bc7696c..b8c57b0 100644 --- a/test/PairingTest.php +++ b/test/PairingTest.php @@ -67,40 +67,40 @@ public function testPairingRefreshFromServer(){ } public function testGetPairingResetLink(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); - $resp->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); - $this->mock->addResponse($resp); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); + $resp->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); + $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $this->getPairing($toopher); + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); - $resetLink = $pairing->getResetLink(); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde", 'Pairing reset link was incorrect'); + $resetLink = $pairing->getResetLink(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde", 'Pairing reset link was incorrect'); } public function testEmailPairingResetLink(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); - $this->mock->addResponse($resp); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); + $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $this->getPairing($toopher); + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); $pairing->emailResetLink('jdoe@example.com'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); } public function testPairingGetQrCodeImage(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/qr/pairings/1'); - $resp->appendBody('{}'); - $this->mock->addResponse($resp); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/qr/pairings/1'); + $resp->appendBody('{}'); + $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $this->getPairing($toopher); + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); - $pairing->getQrCodeImage(); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/qr/pairings/1', "Last called url should be 'https://api.toopher.com/v1/qr/pairings/1'"); + $pairing->getQrCodeImage(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/qr/pairings/1', "Last called url should be 'https://api.toopher.com/v1/qr/pairings/1'"); } } diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 19cc5b8..2d596d2 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -82,129 +82,129 @@ public function compareToDefaultUserTerminal($userTerminal) } public function testCanCreateToopherApiWithArguments() { - $toopher = new ToopherApi('key', 'secret'); + $toopher = new ToopherApi('key', 'secret'); } public function testToopherVersionStringExists() { - $this->assertNotEmpty(ToopherApi::VERSION, 'no version string'); - list($major, $minor, $patch) = explode('.', ToopherApi::VERSION); - $this->assertGreaterThanOrEqual(1, (int)$major); - $this->assertGreaterThanOrEqual(0, (int)$minor); - $this->assertGreaterThanOrEqual(0, (int)$patch); + $this->assertNotEmpty(ToopherApi::VERSION, 'no version string'); + list($major, $minor, $patch) = explode('.', ToopherApi::VERSION); + $this->assertGreaterThanOrEqual(1, (int)$major); + $this->assertGreaterThanOrEqual(0, (int)$minor); + $this->assertGreaterThanOrEqual(0, (int)$patch); } public function testPair(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->pair('user', 'immediate_pair'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultPairing($pairing); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); + $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->pair('user', 'immediate_pair'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } public function testPairSms(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); - $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->pair('user', '555-555-5555'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultPairing($pairing); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); + $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->pair('user', '555-555-5555'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } public function testPairQr(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); - $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->pair('user'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultPairing($pairing); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); + $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->pair('user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } public function testAuthenticateWithPairingId(){ - $id = Uuid::uuid4()->toString(); - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->authenticate($id, 'term name'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultAuthenticationRequest($authRequest, $id); + $id = Uuid::uuid4()->toString(); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->authenticate($id, 'term name'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultAuthenticationRequest($authRequest, $id); } public function testAuthenticateWithUsername(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->authenticate('user', 'term name', '1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultAuthenticationRequest($authRequest); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->authenticate('user', 'term name', '1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultAuthenticationRequest($authRequest); } public function testRawPost(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $params = array('pairing_id' => '1', 'terminal_name' => 'term name'); - $authRequest = $toopher->advanced->raw->post('authentication_requests/initiate', $params); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); - $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); - $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); - $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); - $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); - $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); - $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); - $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); - $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $params = array('pairing_id' => '1', 'terminal_name' => 'term name'); + $authRequest = $toopher->advanced->raw->post('authentication_requests/initiate', $params); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); + $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); + $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); + $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); + $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); } public function testRawGet(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->advanced->raw->get('authentication_requests/1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); - $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); - $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); - $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); - $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); - $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); - $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); - $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); - $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->advanced->raw->get('authentication_requests/1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); + $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); + $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); + $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); + $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); } public function testPairingsGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); - $resp->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->advanced->pairings->getById('1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultPairing($pairing); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->advanced->pairings->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultPairing($pairing); } public function testAuthenticationRequestsGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->advanced->authenticationRequests->getById('1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultAuthenticationRequest($authRequest); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->advanced->authenticationRequests->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultAuthenticationRequest($authRequest); } public function testUsersGetById(){ @@ -288,46 +288,46 @@ public function testUserTerminalCreateWithExtras(){ * @expectedException InvalidArgumentException */ public function testEmptyKeyThrowsException() { - $toopher = new ToopherApi('', 'secret'); + $toopher = new ToopherApi('', 'secret'); } /** * @expectedException InvalidArgumentException */ public function testEmptySecretThrowsException() { - $toopher = new ToopherApi('key', ''); + $toopher = new ToopherApi('key', ''); } /** * @expectedException ToopherRequestException */ public function testToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 401 Unauthorized", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $auth = $toopher->advanced->authenticationRequests->getById('1'); + $resp = new HTTP_Request2_Response("HTTP/1.1 401 Unauthorized", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } /** * @expectedException ToopherRequestException */ public function test400WithEmptyBodyRaisesToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $auth = $toopher->advanced->authenticationRequests->getById('1'); + $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } /** * @expectedException ToopherRequestException */ public function test400WithUnprintableBodyRaisesToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $auth = $toopher->advanced->authenticationRequests->getById('1'); + $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } } diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index d32d1f9..7b04a8d 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -64,11 +64,11 @@ protected function setUp() public function testToopherIframeGetAuthenticationUrl() { - $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D"; - $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); - $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); + $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); + $this->toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D"; + $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); + $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } public function testToopherIframeGetAuthenticationUrlWithExtras() From 00b299ef7c6350ca6e365392ccda2c7fac1a48a9 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 26 Feb 2015 11:58:25 -0600 Subject: [PATCH 066/114] Move classes into separate files --- composer.lock | 6 +- demo/bootstrap.php | 8 +- lib/Action.php | 41 +++ lib/AuthenticationRequest.php | 74 +++++ lib/Pairing.php | 85 ++++++ lib/{toopher_api.php => ToopherApi.php} | 383 ------------------------ lib/ToopherIframe.php | 211 +++++++++++++ lib/User.php | 67 +++++ lib/UserTerminal.php | 55 ++++ test/bootstrap.php | 8 +- 10 files changed, 550 insertions(+), 388 deletions(-) create mode 100644 lib/Action.php create mode 100644 lib/AuthenticationRequest.php create mode 100644 lib/Pairing.php rename lib/{toopher_api.php => ToopherApi.php} (50%) create mode 100644 lib/ToopherIframe.php create mode 100644 lib/User.php create mode 100644 lib/UserTerminal.php diff --git a/composer.lock b/composer.lock index 950c961..4f50008 100644 --- a/composer.lock +++ b/composer.lock @@ -8,10 +8,10 @@ "packages": [ { "name": "pear-pear.php.net/Archive_Tar", - "version": "1.3.13", + "version": "1.3.14", "dist": { "type": "file", - "url": "http://pear.php.net/get/Archive_Tar-1.3.13.tgz", + "url": "http://pear.php.net/get/Archive_Tar-1.3.14.tgz", "reference": null, "shasum": null }, @@ -19,7 +19,7 @@ "php": ">=4.3.0.0" }, "replace": { - "pear-pear/archive_tar": "== 1.3.13.0" + "pear-pear/archive_tar": "== 1.3.14.0" }, "type": "pear-library", "autoload": { diff --git a/demo/bootstrap.php b/demo/bootstrap.php index c1c1e80..8ef7e4a 100644 --- a/demo/bootstrap.php +++ b/demo/bootstrap.php @@ -1,5 +1,11 @@ diff --git a/lib/Action.php b/lib/Action.php new file mode 100644 index 0000000..a9fcc59 --- /dev/null +++ b/lib/Action.php @@ -0,0 +1,41 @@ +id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->raw_response = $jsonResponse; + } + + public function update($jsonResponse) + { + $this->name = $jsonResponse['name']; + $this->raw_response = $jsonResponse; + } +} + +?> diff --git a/lib/AuthenticationRequest.php b/lib/AuthenticationRequest.php new file mode 100644 index 0000000..7ec472f --- /dev/null +++ b/lib/AuthenticationRequest.php @@ -0,0 +1,74 @@ +api = $api; + $this->id = $jsonResponse['id']; + $this->pending = $jsonResponse['pending']; + $this->granted = $jsonResponse['granted']; + $this->automated = $jsonResponse['automated']; + $this->reason_code = $jsonResponse['reason_code']; + $this->reason = $jsonResponse['reason']; + $this->terminal = new UserTerminal($jsonResponse['terminal'], $api); + $this->user = new User($jsonResponse['user'], $api); + $this->action = new Action($jsonResponse['action']); + $this->raw_response = $jsonResponse; + } + + public function refreshFromServer() + { + $url = 'authentication_requests/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + + public function grantWithOtp($otp, $kwargs = array()) + { + $url = 'authentication_requests/' . $this->id . '/otp_auth'; + $params = array('otp' => $otp); + $params = array_merge($params, $kwargs); + $result = $this->api->advanced->raw->post($url, $params); + $this->update($result); + } + + private function update($jsonResponse) + { + $this->pending = $jsonResponse['pending']; + $this->granted = $jsonResponse['granted']; + $this->automated = $jsonResponse['automated']; + $this->reason_code = $jsonResponse['reason_code']; + $this->reason = $jsonResponse['reason']; + $this->terminal->update($jsonResponse['terminal']); + $this->user->update($jsonResponse['user']); + $this->action->update($jsonResponse['action']); + $this->raw_respones = $jsonResponse; + } +} + +?> diff --git a/lib/Pairing.php b/lib/Pairing.php new file mode 100644 index 0000000..aaf66f2 --- /dev/null +++ b/lib/Pairing.php @@ -0,0 +1,85 @@ +api = $api; + $this->id = $jsonResponse['id']; + $this->enabled = $jsonResponse['enabled']; + $this->pending = $jsonResponse['pending']; + $this->user = new User($jsonResponse['user'], $api); + $this->raw_response = $jsonResponse; + } + + public function refreshFromServer() + { + $url = 'pairings/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + + public function getResetLink($kwargs = array()) + { + if(!array_key_exists('security_question', $kwargs)) + { + $kwargs['security_question'] = NULL; + } + if(!array_key_exists('security_answer', $kwargs)) + { + $kwargs['security_answer'] = NULL; + } + + $url = 'pairings/' . $this->id . '/generate_reset_link'; + $result = $this->api->advanced->raw->post($url, $kwargs); + return $result['url']; + } + + public function emailResetLink($email, $kwargs = array()) + { + $params = array('reset_email' => $email); + $params = array_merge($params, $kwargs); + $url = 'pairings/' . $this->id . '/send_reset_link'; + $this->api->advanced->raw->post($url, $params); + } + + public function getQrCodeImage() + { + $url = 'qr/pairings/' . $this->id; + return $this->api->advanced->raw->get_raw($url); + } + + private function update($jsonResponse) + { + $this->enabled = $jsonResponse['enabled']; + $this->pending = $jsonResponse['pending']; + $this->user->update($jsonResponse['user']); + $this->raw_response = $jsonResponse; + } +} + +?> diff --git a/lib/toopher_api.php b/lib/ToopherApi.php similarity index 50% rename from lib/toopher_api.php rename to lib/ToopherApi.php index 0f8b4f4..589e7de 100644 --- a/lib/toopher_api.php +++ b/lib/ToopherApi.php @@ -26,192 +26,6 @@ class ToopherRequestException extends Exception { } -class SignatureValidationError extends Exception -{ -} - -class ToopherIframe -{ - function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') - { - $this->consumerSecret = $secret; - $this->consumerKey = $key; - $this->oauthConsumer = new OAuth($key, $secret); - $this->baseUrl = $baseUrl; - $this->timestampOverride = NULL; - $this->nonceOverride = NULL; - $this->oauthVersion = '1.0'; - $this->signatureMethod = 'HMAC-SHA1'; - } - - public function setTimestampOverride($timestampOverride) - { - $this->timestampOverride = $timestampOverride; - } - - public function setNonceOverride($nonceOverride) - { - $this->nonceOverride = $nonceOverride; - } - - private function getUnixTimestamp() - { - if (!is_null($this->timestampOverride)) { - return $this->timestampOverride; - } else { - return time(); - } - } - - public function getAuthenticationUrl($username, $resetEmail, $requestToken, $actionName = 'Log In', $requesterMetadata = 'None', $kwargs = array()) - { - if (array_key_exists('ttl', $kwargs)) { - $ttl = $kwargs['ttl']; - unset($kwargs['ttl']); - } else { - $ttl = 300; - } - - $params = array( - 'v' => '2', - 'username' => $username, - 'reset_email' => $resetEmail, - 'action_name' => $actionName, - 'session_token' => $requestToken, - 'requester_metadata' => $requesterMetadata, - 'expires' => $this->getUnixTimestamp() + $ttl - ); - $params = array_merge($params, $kwargs); - - return $this->getOauthSignedUrl($this->baseUrl . 'web/authenticate', $params); - } - - public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) - { - if (array_key_exists('ttl', $kwargs)) { - $ttl = $kwargs['ttl']; - unset($kwargs['ttl']); - } else { - $ttl = 300; - } - - $params = array( - 'v' => '2', - 'username' => $username, - 'reset_email' => $resetEmail, - 'expires' => $this->getUnixTimestamp() + $ttl - ); - $params = array_merge($params, $kwargs); - return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $params); - } - - public function validatePostback($parameters, $sessionToken, $ttl) - { - try { - $data = array(); - - foreach ($parameters as $key => $value) { - $data[$key] = $value[0]; - } - - $missingKeys = array(); - if (!array_key_exists('toopher_sig', $data)) { - $missingKeys[] = 'toopher_sig'; - } - if (!array_key_exists('timestamp', $data)) { - $missingKeys[] = 'timestamp'; - } - if (!array_key_exists('session_token', $data)) { - $missingKeys[] = 'session_token'; - } - if (count($missingKeys) > 0) { - $keys = implode(',', $missingKeys); - throw new SignatureValidationError('Missing required keys: ' . $keys); - } - - if ($data['session_token'] != $sessionToken) { - throw new SignatureValidationError('Session token does not match expected value'); - } - - $maybeSignature = $data['toopher_sig']; - unset($data['toopher_sig']); - $signatureValid = false; - try { - $computedSignature = $this->signature($this->consumerSecret, $data); - $signatureValid = $maybeSignature == $computedSignature; - } catch (Exception $e) { - throw new SignatureValidationError('Error while calculating signature: ' . $e); - } - - if (!$signatureValid) { - throw new SignatureValidationError('Computed signature does not match'); - } - - $ttlValid = ($this->getUnixTimestamp() - $ttl) < $data['timestamp']; - if (!$ttlValid) { - throw new SignatureValidationError('TTL Expired'); - } - - return $data; - } catch (Exception $e) { - throw new SignatureValidationError ('Exception while validating toopher signature: ' . $e); - } - } - - private function signature($secret, $parameters) - { - $oauthConsumer = new HTTP_OAuth_Consumer($this->consumerKey, $this->consumerSecret); - $params = $oauthConsumer->buildHttpQuery($parameters); - $key = mb_convert_encoding($secret, "UTF-8"); - $sig = hash_hmac('sha1', $params, $secret, true); - return base64_encode($sig); - } - - private function getOauthSignedUrl($url, $queryParams) - { - $oauthParams = $this->getOauthParams(); - $encodedParams = $this->encodeParamsForSignature(array_merge($queryParams, $oauthParams)); - $signature = $this->oauthConsumer->generateSignature('GET', $url, $encodedParams); - $oauthParams['oauth_signature'] = $signature; - return $this->buildUrl($url, $queryParams, $oauthParams); - } - - private function encodeParamsForSignature($params) - { - foreach ($params as $key => $value) { - $params[$key] = oauth_urlencode($value); - }; - return $params; - } - - private function getOauthParams() - { - $oauthParams = array( - 'oauth_consumer_key' => $this->consumerKey, - 'oauth_signature_method' => $this->signatureMethod, - 'oauth_version' => $this->oauthVersion - ); - if (!is_null($this->nonceOverride)) { - $oauthParams['oauth_nonce'] = $this->nonceOverride; - } else { - $oauthParams['oauth_nonce'] = uniqid().'.'.time(); - } - if (!is_null($this->timestampOverride)) { - $oauthParams['oauth_timestamp'] = $this->timestampOverride; - } else { - $oauthParams['oauth_timestamp'] = time(); - } - return $oauthParams; - } - - private function buildUrl($url, $queryParams, $oauthParams) - { - $query = http_build_query($queryParams); - $oauthQuery = http_build_query($oauthParams); - return $url . '?' . $query . '&' . $oauthQuery; - } -} - class ToopherApi { const VERSION = '2.0.0'; @@ -520,201 +334,4 @@ public function create($username, $terminalName, $requesterSpecifiedId, $kwargs } } -class Pairing -{ - protected $api; - - function __construct($jsonResponse, $api) - { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->enabled = $jsonResponse['enabled']; - $this->pending = $jsonResponse['pending']; - $this->user = new User($jsonResponse['user'], $api); - $this->raw_response = $jsonResponse; - } - - public function refreshFromServer() - { - $url = 'pairings/' . $this->id; - $result = $this->api->advanced->raw->get($url); - $this->update($result); - } - - public function getResetLink($kwargs = array()) - { - if(!array_key_exists('security_question', $kwargs)) - { - $kwargs['security_question'] = NULL; - } - if(!array_key_exists('security_answer', $kwargs)) - { - $kwargs['security_answer'] = NULL; - } - - $url = 'pairings/' . $this->id . '/generate_reset_link'; - $result = $this->api->advanced->raw->post($url, $kwargs); - return $result['url']; - } - - public function emailResetLink($email, $kwargs = array()) - { - $params = array('reset_email' => $email); - $params = array_merge($params, $kwargs); - $url = 'pairings/' . $this->id . '/send_reset_link'; - $this->api->advanced->raw->post($url, $params); - } - - public function getQrCodeImage() - { - $url = 'qr/pairings/' . $this->id; - return $this->api->advanced->raw->get_raw($url); - } - - private function update($jsonResponse) - { - $this->enabled = $jsonResponse['enabled']; - $this->pending = $jsonResponse['pending']; - $this->user->update($jsonResponse['user']); - $this->raw_response = $jsonResponse; - } -} - -class AuthenticationRequest -{ - protected $api; - - function __construct($jsonResponse, $api) - { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->pending = $jsonResponse['pending']; - $this->granted = $jsonResponse['granted']; - $this->automated = $jsonResponse['automated']; - $this->reason_code = $jsonResponse['reason_code']; - $this->reason = $jsonResponse['reason']; - $this->terminal = new UserTerminal($jsonResponse['terminal'], $api); - $this->user = new User($jsonResponse['user'], $api); - $this->action = new Action($jsonResponse['action']); - $this->raw_response = $jsonResponse; - } - - public function refreshFromServer() - { - $url = 'authentication_requests/' . $this->id; - $result = $this->api->advanced->raw->get($url); - $this->update($result); - } - - public function grantWithOtp($otp, $kwargs = array()) - { - $url = 'authentication_requests/' . $this->id . '/otp_auth'; - $params = array('otp' => $otp); - $params = array_merge($params, $kwargs); - $result = $this->api->advanced->raw->post($url, $params); - $this->update($result); - } - - private function update($jsonResponse) - { - $this->pending = $jsonResponse['pending']; - $this->granted = $jsonResponse['granted']; - $this->automated = $jsonResponse['automated']; - $this->reason_code = $jsonResponse['reason_code']; - $this->reason = $jsonResponse['reason']; - $this->terminal->update($jsonResponse['terminal']); - $this->user->update($jsonResponse['user']); - $this->action->update($jsonResponse['action']); - $this->raw_respones = $jsonResponse; - } -} - -class User -{ - protected $api; - - function __construct($jsonResponse, $api) - { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; - $this->raw_response = $jsonResponse; - } - - public function refreshFromServer() - { - $url = 'users/' . $this->id; - $result = $this->api->advanced->raw->get($url); - $this->update($result); - } - - public function enableToopherAuthentication() - { - $url = 'users/' . $this->id; - $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "true")); - $this->update($result); - } - - public function disableToopherAuthentication() - { - $url = 'users/' . $this->id; - $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "false")); - $this->update($result); - } - - public function update($jsonResponse) - { - $this->name = $jsonResponse['name']; - $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; - $this->raw_response = $jsonResponse; - } -} - -class UserTerminal -{ - protected $api; - - function __construct($jsonResponse, $api) - { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->requester_specified_id = $jsonResponse['requester_specified_id']; - $this->user = new User($jsonResponse['user'], $api); - $this->raw_response = $jsonResponse; - } - - public function refreshFromServer() - { - $url = 'user_terminals/' . $this->id; - $result = $this->api->advanced->raw->get($url); - $this->update($result); - } - - public function update($jsonResponse) - { - $this->name = $jsonResponse['name']; - $this->requester_specified_id = $jsonResponse['requester_specified_id']; - $this->user->update($jsonResponse['user']); - $this->raw_response = $jsonResponse; - } -} - -class Action -{ - function __construct($jsonResponse) - { - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->raw_response = $jsonResponse; - } - - public function update($jsonResponse) - { - $this->name = $jsonResponse['name']; - $this->raw_response = $jsonResponse; - } -} - ?> diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php new file mode 100644 index 0000000..e037ea7 --- /dev/null +++ b/lib/ToopherIframe.php @@ -0,0 +1,211 @@ +consumerSecret = $secret; + $this->consumerKey = $key; + $this->oauthConsumer = new OAuth($key, $secret); + $this->baseUrl = $baseUrl; + $this->timestampOverride = NULL; + $this->nonceOverride = NULL; + $this->oauthVersion = '1.0'; + $this->signatureMethod = 'HMAC-SHA1'; + } + + public function setTimestampOverride($timestampOverride) + { + $this->timestampOverride = $timestampOverride; + } + + public function setNonceOverride($nonceOverride) + { + $this->nonceOverride = $nonceOverride; + } + + private function getUnixTimestamp() + { + if (!is_null($this->timestampOverride)) { + return $this->timestampOverride; + } else { + return time(); + } + } + + public function getAuthenticationUrl($username, $resetEmail, $requestToken, $actionName = 'Log In', $requesterMetadata = 'None', $kwargs = array()) + { + if (array_key_exists('ttl', $kwargs)) { + $ttl = $kwargs['ttl']; + unset($kwargs['ttl']); + } else { + $ttl = 300; + } + + $params = array( + 'v' => '2', + 'username' => $username, + 'reset_email' => $resetEmail, + 'action_name' => $actionName, + 'session_token' => $requestToken, + 'requester_metadata' => $requesterMetadata, + 'expires' => $this->getUnixTimestamp() + $ttl + ); + $params = array_merge($params, $kwargs); + + return $this->getOauthSignedUrl($this->baseUrl . 'web/authenticate', $params); + } + + public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) + { + if (array_key_exists('ttl', $kwargs)) { + $ttl = $kwargs['ttl']; + unset($kwargs['ttl']); + } else { + $ttl = 300; + } + + $params = array( + 'v' => '2', + 'username' => $username, + 'reset_email' => $resetEmail, + 'expires' => $this->getUnixTimestamp() + $ttl + ); + $params = array_merge($params, $kwargs); + return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $params); + } + + public function validatePostback($parameters, $sessionToken, $ttl) + { + try { + $data = array(); + + foreach ($parameters as $key => $value) { + $data[$key] = $value[0]; + } + + $missingKeys = array(); + if (!array_key_exists('toopher_sig', $data)) { + $missingKeys[] = 'toopher_sig'; + } + if (!array_key_exists('timestamp', $data)) { + $missingKeys[] = 'timestamp'; + } + if (!array_key_exists('session_token', $data)) { + $missingKeys[] = 'session_token'; + } + if (count($missingKeys) > 0) { + $keys = implode(',', $missingKeys); + throw new SignatureValidationError('Missing required keys: ' . $keys); + } + + if ($data['session_token'] != $sessionToken) { + throw new SignatureValidationError('Session token does not match expected value'); + } + + $maybeSignature = $data['toopher_sig']; + unset($data['toopher_sig']); + $signatureValid = false; + try { + $computedSignature = $this->signature($this->consumerSecret, $data); + $signatureValid = $maybeSignature == $computedSignature; + } catch (Exception $e) { + throw new SignatureValidationError('Error while calculating signature: ' . $e); + } + + if (!$signatureValid) { + throw new SignatureValidationError('Computed signature does not match'); + } + + $ttlValid = ($this->getUnixTimestamp() - $ttl) < $data['timestamp']; + if (!$ttlValid) { + throw new SignatureValidationError('TTL Expired'); + } + + return $data; + } catch (Exception $e) { + throw new SignatureValidationError ('Exception while validating toopher signature: ' . $e); + } + } + + private function signature($secret, $parameters) + { + $oauthConsumer = new HTTP_OAuth_Consumer($this->consumerKey, $this->consumerSecret); + $params = $oauthConsumer->buildHttpQuery($parameters); + $key = mb_convert_encoding($secret, "UTF-8"); + $sig = hash_hmac('sha1', $params, $secret, true); + return base64_encode($sig); + } + + private function getOauthSignedUrl($url, $queryParams) + { + $oauthParams = $this->getOauthParams(); + $encodedParams = $this->encodeParamsForSignature(array_merge($queryParams, $oauthParams)); + $signature = $this->oauthConsumer->generateSignature('GET', $url, $encodedParams); + $oauthParams['oauth_signature'] = $signature; + return $this->buildUrl($url, $queryParams, $oauthParams); + } + + private function encodeParamsForSignature($params) + { + foreach ($params as $key => $value) { + $params[$key] = oauth_urlencode($value); + }; + return $params; + } + + private function getOauthParams() + { + $oauthParams = array( + 'oauth_consumer_key' => $this->consumerKey, + 'oauth_signature_method' => $this->signatureMethod, + 'oauth_version' => $this->oauthVersion + ); + if (!is_null($this->nonceOverride)) { + $oauthParams['oauth_nonce'] = $this->nonceOverride; + } else { + $oauthParams['oauth_nonce'] = uniqid().'.'.time(); + } + if (!is_null($this->timestampOverride)) { + $oauthParams['oauth_timestamp'] = $this->timestampOverride; + } else { + $oauthParams['oauth_timestamp'] = time(); + } + return $oauthParams; + } + + private function buildUrl($url, $queryParams, $oauthParams) + { + $query = http_build_query($queryParams); + $oauthQuery = http_build_query($oauthParams); + return $url . '?' . $query . '&' . $oauthQuery; + } +} + +?> diff --git a/lib/User.php b/lib/User.php new file mode 100644 index 0000000..b144e71 --- /dev/null +++ b/lib/User.php @@ -0,0 +1,67 @@ +api = $api; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; + $this->raw_response = $jsonResponse; + } + + public function refreshFromServer() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + + public function enableToopherAuthentication() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "true")); + $this->update($result); + } + + public function disableToopherAuthentication() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "false")); + $this->update($result); + } + + public function update($jsonResponse) + { + $this->name = $jsonResponse['name']; + $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; + $this->raw_response = $jsonResponse; + } +} + +?> diff --git a/lib/UserTerminal.php b/lib/UserTerminal.php new file mode 100644 index 0000000..9d363d7 --- /dev/null +++ b/lib/UserTerminal.php @@ -0,0 +1,55 @@ +api = $api; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->requester_specified_id = $jsonResponse['requester_specified_id']; + $this->user = new User($jsonResponse['user'], $api); + $this->raw_response = $jsonResponse; + } + + public function refreshFromServer() + { + $url = 'user_terminals/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + + public function update($jsonResponse) + { + $this->name = $jsonResponse['name']; + $this->requester_specified_id = $jsonResponse['requester_specified_id']; + $this->user->update($jsonResponse['user']); + $this->raw_response = $jsonResponse; + } +} + +?> diff --git a/test/bootstrap.php b/test/bootstrap.php index c1c1e80..8ef7e4a 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -1,5 +1,11 @@ From 1d609515ad82367850d15e4a72a7c1ee8e1476c6 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 08:58:20 -0600 Subject: [PATCH 067/114] Cleanup error mesages in demo --- demo/toopher_demo.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/demo/toopher_demo.php b/demo/toopher_demo.php index 7bec1f4..90ff293 100644 --- a/demo/toopher_demo.php +++ b/demo/toopher_demo.php @@ -60,7 +60,7 @@ $pairing = $toopher->pair($userName, $phrase); break; } catch (Exception $e) { - echo ("The pairing phrase was not accepted (Reason:$e)"); + echo ("The pairing phrase was not accepted. Please try pairing again.\n"); } } @@ -78,10 +78,10 @@ break 2; } else { echo("The pairing has been denied.\n"); - exit(0); + break; } } catch (Exception $e) { - echo ("Could not check pairing status (Reason: $e)"); + echo ("Could not check pairing status. Please try authorizing again.)\n"); } } } From b59ba18bbaaa6d2f0d129788d1c86efbedc1ba74 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 09:25:42 -0600 Subject: [PATCH 068/114] Little edits --- lib/ToopherApi.php | 8 ++++---- lib/ToopherIframe.php | 6 ++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/ToopherApi.php b/lib/ToopherApi.php index 589e7de..c4841b7 100644 --- a/lib/ToopherApi.php +++ b/lib/ToopherApi.php @@ -51,7 +51,7 @@ function __construct($key, $secret, $baseUrl = '', $httpAdapter = NULL) $this->advanced = new AdvancedApiUsageFactory($key, $secret, $baseUrl, $httpAdapter, $this); } - public function pair($username, $phraseOrNumber = '', $kwargs = array()) + public function pair($username, $phraseOrNumber = NULL, $kwargs = array()) { $params = array('user_name' => $username); $params = array_merge($params, $kwargs); @@ -80,7 +80,7 @@ public function authenticate($pairingIdOrUsername, $terminalName = NULL, $reques { $url = 'authentication_requests/initiate'; $uuidPattern = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; - if(preg_match($uuidPattern, $pairingIdOrUsername, $match)) + if (preg_match($uuidPattern, $pairingIdOrUsername, $match)) { $params = array('pairing_id' => $pairingIdOrUsername); } @@ -197,7 +197,7 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest } $resultBody = $result->getBody(); - if ($result->getStatus() != 200) + if ($result->getStatus() >= 400) { error_log(sprintf("Toopher API call returned unexpected HTTP response: %d - %s", $result->getStatus(), $result->getReasonPhrase())); if (empty($resultBody)) { @@ -295,7 +295,7 @@ public function getByName($username) $users = $this->api->advanced->raw->get($url, $params); if (sizeof($users) > 1) { throw new ToopherRequestException(sprintf("Multiple users with name = %s", $username)); - } elseif (empty ($users)) { + } elseif (empty($users)) { throw new ToopherRequestException(sprintf("No users with name = %s", $username)); } return new User(array_shift($users), $this->api); diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index e037ea7..0e335be 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -28,6 +28,8 @@ class SignatureValidationError extends Exception class ToopherIframe { + const VERSION = '2'; + function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') { $this->consumerSecret = $secret; @@ -69,7 +71,7 @@ public function getAuthenticationUrl($username, $resetEmail, $requestToken, $act } $params = array( - 'v' => '2', + 'v' => ToopherIframe::VERSION, 'username' => $username, 'reset_email' => $resetEmail, 'action_name' => $actionName, @@ -190,7 +192,7 @@ private function getOauthParams() if (!is_null($this->nonceOverride)) { $oauthParams['oauth_nonce'] = $this->nonceOverride; } else { - $oauthParams['oauth_nonce'] = uniqid().'.'.time(); + $oauthParams['oauth_nonce'] = uniqid() . '.' . time(); } if (!is_null($this->timestampOverride)) { $oauthParams['oauth_timestamp'] = $this->timestampOverride; From 05216ce0be3a4b2d99377d60e23fa89c6c52b3b3 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 09:59:56 -0600 Subject: [PATCH 069/114] Refactor demo --- demo/toopher_demo.php | 128 +++++++++++++++++++++++++++--------------- 1 file changed, 84 insertions(+), 44 deletions(-) diff --git a/demo/toopher_demo.php b/demo/toopher_demo.php index 90ff293..3dc35ae 100644 --- a/demo/toopher_demo.php +++ b/demo/toopher_demo.php @@ -26,24 +26,43 @@ $stdin = fopen('php://stdin', 'r'); -$key = getenv('TOOPHER_CONSUMER_KEY'); -$secret = getenv('TOOPHER_CONSUMER_SECRET'); -if(empty($key) || empty($secret)){ - echo("Enter your requester credentials (from https://dev.toopher.com).\n"); - echo("Hint: Set the TOOPHER_CONSUMER_SECRET and TOOPHER_CONSUMER_SECRET environment variables to avoid this prompt.\n"); - echo("Consumer Key:"); - $key = rtrim(fgets($stdin)); - echo("Consumer Secret:"); - $secret = rtrim(fgets($stdin)); +function printHorizontalLine($character = '-') +{ + echo(str_repeat($character, 40) . "\n"); } -echo ("Using Consumer Key=$key, Consumer Secret=$secret\n"); -$toopher = new ToopherApi($key, $secret); +function printTextWithUnderline($text, $character = '-') +{ + echo ("\n" . $text . "\n"); + printHorizontalLine($character); +} + +function initializeApi() +{ + global $stdin; + + $key = getenv('TOOPHER_CONSUMER_KEY'); + $secret = getenv('TOOPHER_CONSUMER_SECRET'); + if(empty($key) || empty($secret)){ + echo("Enter your requester credentials (from https://dev.toopher.com).\n"); + echo("Hint: Set the TOOPHER_CONSUMER_SECRET and TOOPHER_CONSUMER_SECRET environment variables to avoid this prompt.\n"); + echo("Consumer Key:"); + $key = rtrim(fgets($stdin)); + echo("Consumer Secret:"); + $secret = rtrim(fgets($stdin)); + } + + echo ("\nUsing Consumer Key=$key, Consumer Secret=$secret\n"); + return new ToopherApi($key, $secret); +} + +function pair($toopher) +{ + global $stdin; -while(true) { while(true) { - echo("\nSTEP 1: Pair requester with phone\n"); - echo("----------------------------------------\n"); + + printTextWithUnderline("STEP 1: Pair requester with phone"); echo("Pairing phrases are generated on the mobile app\n"); do { @@ -75,7 +94,7 @@ echo("The pairing has not been authorized by the phone yet.\n"); } elseif ($pairing->enabled) { echo("Pairing complete\n"); - break 2; + return $pairing; } else { echo("The pairing has been denied.\n"); break; @@ -86,42 +105,63 @@ } } -while(true){ - echo("\nSTEP 2: Authenticate log in\n"); - echo("----------------------------------------\n"); - do { - echo("Enter a terminal name for this authentication request [my computer]:"); - $terminalName = rtrim(fgets($stdin)); - } while (empty($terminalName)); - - echo("Sending authentication request...\n"); - try { - $auth = $toopher->authenticate($pairing->user->name, $terminalName); - } catch (Exception $e) { - echo ("Error initiating authentication (Reason: $e)"); - } +function authenticate($pairing, $toopher) +{ + global $stdin; - while(true) { - echo ("Respond to authentication request on phone and then press return to continue."); - rtrim(fgets($stdin)); - echo ("\nChecking status of authenticationr request...\n"); + while(true) + { + printTextWithUnderline("STEP 2: Authenticate log in"); + do { + echo("Enter a terminal name for this authentication request [my computer]:"); + $terminalName = rtrim(fgets($stdin)); + } while (empty($terminalName)); + echo("Sending authentication request...\n"); try { - $auth->refreshFromServer(); + $auth = $toopher->authenticate($pairing->user->name, $terminalName); } catch (Exception $e) { - echo ("Could not check authentication status (Reason: $e)"); + echo ("Error initiating authentication (Reason: $e)"); } - if ($auth->pending) { - echo ("The authentication request has not received a response from the phone yet.\n"); - } else { - $automation = $auth->automated ? 'automatically ' : ''; - $result = $auth->granted ? 'granted' : 'denied'; - echo ("The request was " . $automation . $result . "!\n" ); - break; + while(true) { + echo ("Respond to authentication request on phone and then press return to continue."); + rtrim(fgets($stdin)); + echo ("\nChecking status of authenticationr request...\n"); + + try { + $auth->refreshFromServer(); + } catch (Exception $e) { + echo ("Could not check authentication status (Reason: $e)"); + } + + if ($auth->pending) { + echo ("The authentication request has not received a response from the phone yet.\n"); + } else { + $automation = $auth->automated ? 'automatically ' : ''; + $result = $auth->granted ? 'granted' : 'denied'; + echo ("The request was " . $automation . $result . "!\n" ); + break; + } } + echo("Press return to authenticate again, or [Ctrl+C] to exit"); + rtrim(fgets($stdin)); } - echo("Press return to authenticate again, or [Ctrl+C] to exit"); - rtrim(fgets($stdin)); } + +function demo() +{ + printTextWithUnderline("Toopher Library Demo", "="); + + $toopher = initializeApi(); + + do { + $pairing = pair($toopher); + } while (!$pairing); + + authenticate($pairing, $toopher); +} + +demo() + ?> From cf38c402c3fb5c41936084aa57d02043a8e4f6d4 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 12:07:42 -0600 Subject: [PATCH 070/114] Use constant for ToopherIframe version --- lib/ToopherIframe.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 0e335be..17cabb7 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -94,7 +94,7 @@ public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) } $params = array( - 'v' => '2', + 'v' => ToopherIframe::VERSION, 'username' => $username, 'reset_email' => $resetEmail, 'expires' => $this->getUnixTimestamp() + $ttl From 353c6de873d70926d99d798a59518336a211f8ee Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 12:27:03 -0600 Subject: [PATCH 071/114] Use 4-space tabs --- demo/toopher_demo.php | 205 +++++++++++---------- lib/Action.php | 22 +-- lib/Pairing.php | 11 +- lib/ToopherApi.php | 181 +++++++++---------- lib/ToopherIframe.php | 345 +++++++++++++++++------------------ lib/User.php | 66 +++---- lib/UserTerminal.php | 52 +++--- test/ToopherApiTest.php | 392 ++++++++++++++++++++-------------------- 8 files changed, 626 insertions(+), 648 deletions(-) diff --git a/demo/toopher_demo.php b/demo/toopher_demo.php index 3dc35ae..5897f26 100644 --- a/demo/toopher_demo.php +++ b/demo/toopher_demo.php @@ -28,138 +28,137 @@ function printHorizontalLine($character = '-') { - echo(str_repeat($character, 40) . "\n"); + echo(str_repeat($character, 40) . "\n"); } function printTextWithUnderline($text, $character = '-') { - echo ("\n" . $text . "\n"); - printHorizontalLine($character); + echo ("\n" . $text . "\n"); + printHorizontalLine($character); } function initializeApi() { - global $stdin; - - $key = getenv('TOOPHER_CONSUMER_KEY'); - $secret = getenv('TOOPHER_CONSUMER_SECRET'); - if(empty($key) || empty($secret)){ - echo("Enter your requester credentials (from https://dev.toopher.com).\n"); - echo("Hint: Set the TOOPHER_CONSUMER_SECRET and TOOPHER_CONSUMER_SECRET environment variables to avoid this prompt.\n"); - echo("Consumer Key:"); - $key = rtrim(fgets($stdin)); - echo("Consumer Secret:"); - $secret = rtrim(fgets($stdin)); - } - - echo ("\nUsing Consumer Key=$key, Consumer Secret=$secret\n"); - return new ToopherApi($key, $secret); + global $stdin; + + $key = getenv('TOOPHER_CONSUMER_KEY'); + $secret = getenv('TOOPHER_CONSUMER_SECRET'); + if(empty($key) || empty($secret)){ + echo("Enter your requester credentials (from https://dev.toopher.com).\n"); + echo("Hint: Set the TOOPHER_CONSUMER_SECRET and TOOPHER_CONSUMER_SECRET environment variables to avoid this prompt.\n"); + echo("Consumer Key:"); + $key = rtrim(fgets($stdin)); + echo("Consumer Secret:"); + $secret = rtrim(fgets($stdin)); + } + + echo ("\nUsing Consumer Key=$key, Consumer Secret=$secret\n"); + return new ToopherApi($key, $secret); } function pair($toopher) { - global $stdin; - - while(true) { - - printTextWithUnderline("STEP 1: Pair requester with phone"); - echo("Pairing phrases are generated on the mobile app\n"); + global $stdin; - do { - echo("Enter pairing phrase: "); - $phrase = rtrim(fgets($stdin)); - } while (empty($phrase)); - - do { - echo("Enter user name: "); - $userName = rtrim(fgets($stdin)); - } while (empty($userName)); - - try { - $pairing = $toopher->pair($userName, $phrase); - break; - } catch (Exception $e) { - echo ("The pairing phrase was not accepted. Please try pairing again.\n"); + while(true) { + printTextWithUnderline("STEP 1: Pair requester with phone"); + echo("Pairing phrases are generated on the mobile app\n"); + + do { + echo("Enter pairing phrase: "); + $phrase = rtrim(fgets($stdin)); + } while (empty($phrase)); + + do { + echo("Enter user name: "); + $userName = rtrim(fgets($stdin)); + } while (empty($userName)); + + try { + $pairing = $toopher->pair($userName, $phrase); + break; + } catch (Exception $e) { + echo ("The pairing phrase was not accepted. Please try pairing again.\n"); + } } - } - - while(true) { - echo("Authorize pairing on phone and then press return to continue."); - rtrim(fgets($stdin)); - echo("\nChecking status of pairing request...\n"); - - try { - $pairing->refreshFromServer(); - if ($pairing->pending) { - echo("The pairing has not been authorized by the phone yet.\n"); - } elseif ($pairing->enabled) { - echo("Pairing complete\n"); - return $pairing; - } else { - echo("The pairing has been denied.\n"); - break; - } - } catch (Exception $e) { - echo ("Could not check pairing status. Please try authorizing again.)\n"); + + while(true) { + echo("Authorize pairing on phone and then press return to continue."); + rtrim(fgets($stdin)); + echo("\nChecking status of pairing request...\n"); + + try { + $pairing->refreshFromServer(); + if ($pairing->pending) { + echo("The pairing has not been authorized by the phone yet.\n"); + } elseif ($pairing->enabled) { + echo("Pairing complete\n"); + return $pairing; + } else { + echo("The pairing has been denied.\n"); + break; + } + } catch (Exception $e) { + echo ("Could not check pairing status. Please try authorizing again.)\n"); + } } - } } function authenticate($pairing, $toopher) { - global $stdin; - - while(true) - { - printTextWithUnderline("STEP 2: Authenticate log in"); - do { - echo("Enter a terminal name for this authentication request [my computer]:"); - $terminalName = rtrim(fgets($stdin)); - } while (empty($terminalName)); - - echo("Sending authentication request...\n"); - try { - $auth = $toopher->authenticate($pairing->user->name, $terminalName); - } catch (Exception $e) { - echo ("Error initiating authentication (Reason: $e)"); - } + global $stdin; while(true) { - echo ("Respond to authentication request on phone and then press return to continue."); - rtrim(fgets($stdin)); - echo ("\nChecking status of authenticationr request...\n"); - - try { - $auth->refreshFromServer(); - } catch (Exception $e) { - echo ("Could not check authentication status (Reason: $e)"); - } - - if ($auth->pending) { - echo ("The authentication request has not received a response from the phone yet.\n"); - } else { - $automation = $auth->automated ? 'automatically ' : ''; - $result = $auth->granted ? 'granted' : 'denied'; - echo ("The request was " . $automation . $result . "!\n" ); - break; - } + printTextWithUnderline("STEP 2: Authenticate log in"); + + do { + echo("Enter a terminal name for this authentication request [my computer]:"); + $terminalName = rtrim(fgets($stdin)); + } while (empty($terminalName)); + + echo("Sending authentication request...\n"); + try { + $auth = $toopher->authenticate($pairing->user->name, $terminalName); + } catch (Exception $e) { + echo ("Error initiating authentication (Reason: $e)"); + } + + while(true) { + echo ("Respond to authentication request on phone and then press return to continue."); + rtrim(fgets($stdin)); + echo ("\nChecking status of authenticationr request...\n"); + + try { + $auth->refreshFromServer(); + } catch (Exception $e) { + echo ("Could not check authentication status (Reason: $e)"); + } + + if ($auth->pending) { + echo ("The authentication request has not received a response from the phone yet.\n"); + } else { + $automation = $auth->automated ? 'automatically ' : ''; + $result = $auth->granted ? 'granted' : 'denied'; + echo ("The request was " . $automation . $result . "!\n" ); + break; + } + } + echo("Press return to authenticate again, or [Ctrl+C] to exit"); + rtrim(fgets($stdin)); } - echo("Press return to authenticate again, or [Ctrl+C] to exit"); - rtrim(fgets($stdin)); - } } function demo() { - printTextWithUnderline("Toopher Library Demo", "="); + printTextWithUnderline("Toopher Library Demo", "="); - $toopher = initializeApi(); + $toopher = initializeApi(); - do { - $pairing = pair($toopher); - } while (!$pairing); + do { + $pairing = pair($toopher); + } while (!$pairing); - authenticate($pairing, $toopher); + authenticate($pairing, $toopher); } demo() diff --git a/lib/Action.php b/lib/Action.php index a9fcc59..f441a48 100644 --- a/lib/Action.php +++ b/lib/Action.php @@ -24,18 +24,18 @@ class Action { - function __construct($jsonResponse) - { - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->raw_response = $jsonResponse; - } + function __construct($jsonResponse) + { + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->raw_response = $jsonResponse; + } - public function update($jsonResponse) - { - $this->name = $jsonResponse['name']; - $this->raw_response = $jsonResponse; - } + public function update($jsonResponse) + { + $this->name = $jsonResponse['name']; + $this->raw_response = $jsonResponse; + } } ?> diff --git a/lib/Pairing.php b/lib/Pairing.php index aaf66f2..dc9f0c8 100644 --- a/lib/Pairing.php +++ b/lib/Pairing.php @@ -45,15 +45,12 @@ public function refreshFromServer() public function getResetLink($kwargs = array()) { - if(!array_key_exists('security_question', $kwargs)) - { + if(!array_key_exists('security_question', $kwargs)) { $kwargs['security_question'] = NULL; } - if(!array_key_exists('security_answer', $kwargs)) - { + if(!array_key_exists('security_answer', $kwargs)) { $kwargs['security_answer'] = NULL; } - $url = 'pairings/' . $this->id . '/generate_reset_link'; $result = $this->api->advanced->raw->post($url, $kwargs); return $result['url']; @@ -69,8 +66,8 @@ public function emailResetLink($email, $kwargs = array()) public function getQrCodeImage() { - $url = 'qr/pairings/' . $this->id; - return $this->api->advanced->raw->get_raw($url); + $url = 'qr/pairings/' . $this->id; + return $this->api->advanced->raw->get_raw($url); } private function update($jsonResponse) diff --git a/lib/ToopherApi.php b/lib/ToopherApi.php index c4841b7..eaf9db5 100644 --- a/lib/ToopherApi.php +++ b/lib/ToopherApi.php @@ -28,7 +28,7 @@ class ToopherRequestException extends Exception class ToopherApi { - const VERSION = '2.0.0'; + const VERSION = '2.0.0'; protected $baseUrl; protected $oauthConsumer; @@ -36,12 +36,10 @@ class ToopherApi function __construct($key, $secret, $baseUrl = '', $httpAdapter = NULL) { - if(empty($key)) - { + if (empty($key)) { throw new InvalidArgumentException('Toopher consumer key cannot be empty'); } - if(empty($secret)) - { + if (empty($secret)) { throw new InvalidArgumentException('Toopher consumer secret cannot be empty'); } @@ -55,21 +53,15 @@ public function pair($username, $phraseOrNumber = NULL, $kwargs = array()) { $params = array('user_name' => $username); $params = array_merge($params, $kwargs); - if (!empty($phraseOrNumber)) - { - if(preg_match('/\d/', $phraseOrNumber, $match)) - { + if (!empty($phraseOrNumber)) { + if (preg_match('/\d/', $phraseOrNumber, $match)) { $url = 'pairings/create/sms'; $params['phone_number'] = $phraseOrNumber; - } - else - { + } else { $url = 'pairings/create'; $params['pairing_phrase'] = $phraseOrNumber; } - } - else - { + } else { $url = 'pairings/create/qr'; } $result = $this->advanced->raw->post($url, $params); @@ -80,26 +72,19 @@ public function authenticate($pairingIdOrUsername, $terminalName = NULL, $reques { $url = 'authentication_requests/initiate'; $uuidPattern = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; - if (preg_match($uuidPattern, $pairingIdOrUsername, $match)) - { + if (preg_match($uuidPattern, $pairingIdOrUsername, $match)) { $params = array('pairing_id' => $pairingIdOrUsername); - } - else - { + } else { $params = array('user_name' => $pairingIdOrUsername); } - - if(!empty($actionName)) - { + if (!empty($actionName)) { $params['action_name'] = $actionName; } - if(!empty($terminalName)) - { - $params['terminal_name'] = $terminalName; + if (!empty($terminalName)) { + $params['terminal_name'] = $terminalName; } - if(!empty($requesterSpecifiedId)) - { - $params['requester_specified_terminal_id'] = $requesterSpecifiedId; + if (!empty($requesterSpecifiedId)) { + $params['requester_specified_terminal_id'] = $requesterSpecifiedId; } $params = array_merge($params, $kwargs); $result = $this->advanced->raw->post($url, $params); @@ -109,12 +94,12 @@ public function authenticate($pairingIdOrUsername, $terminalName = NULL, $reques abstract class ToopherObjectFactory { - protected $api; + protected $api; - function __construct($api) - { - $this->api = $api; - } + function __construct($api) + { + $this->api = $api; + } } class AdvancedApiUsageFactory @@ -137,12 +122,10 @@ class ApiRawRequester function __construct($key, $secret, $baseUrl, $httpAdapter) { - if(empty($key)) - { + if (empty($key)) { throw new InvalidArgumentException('Toopher consumer key cannot be empty'); } - if(empty($secret)) - { + if (empty($secret)) { throw new InvalidArgumentException('Toopher consumer secret cannot be empty'); } @@ -153,7 +136,7 @@ function __construct($key, $secret, $baseUrl, $httpAdapter) public function getOauthConsumer() { - return $this->oauthConsumer; + return $this->oauthConsumer; } public function post($endpoint, $parameters) @@ -168,21 +151,18 @@ public function get($endpoint) public function get_raw($endpoint) { - return $this->request('GET', $endpoint, array(), true); + return $this->request('GET', $endpoint, array(), true); } private function request($method, $endpoint, $parameters = array(), $rawRequest = false) { $req = new HTTP_Request2(); $req->setAdapter($this->httpAdapter); - $req->setHeader(array('User-Agent' => - sprintf('Toopher-PHP/%s (PHP %s)', ToopherApi::VERSION, phpversion()))); + $req->setHeader(array('User-Agent' => sprintf('Toopher-PHP/%s (PHP %s)', ToopherApi::VERSION, phpversion()))); $req->setMethod($method); $req->setUrl($this->baseUrl . $endpoint); - if(!is_null($parameters)) - { - foreach($parameters as $key => $value) - { + if (!is_null($parameters)) { + foreach($parameters as $key => $value) { $req->addPostParameter($key, $value); } } @@ -197,8 +177,7 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest } $resultBody = $result->getBody(); - if ($result->getStatus() >= 400) - { + if ($result->getStatus() >= 400) { error_log(sprintf("Toopher API call returned unexpected HTTP response: %d - %s", $result->getStatus(), $result->getReasonPhrase())); if (empty($resultBody)) { error_log("empty response body"); @@ -208,13 +187,15 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest $err = json_decode($resultBody, true); if ($err === NULL) { $jsonError = $this->json_error_to_string(json_last_error()); - if (!empty($jsonError)) { + if (!empty($jsonError)) + { error_log(sprintf("Error parsing response body JSON: %s", $jsonError)); error_log(sprintf("response body: %s", $result->getBody())); throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $jsonError)); } } else { - if(array_key_exists("error_message", $err)) { + if(array_key_exists("error_message", $err)) + { throw new ToopherRequestException($err['error_message'], $err['error_code']); } else { throw new ToopherRequestException(sprintf("%s - %s", $result->getReasonPhrase(), $resultBody), $result->getStatus()); @@ -222,24 +203,24 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest } } - if ($rawRequest) - { - return $resultBody; + if ($rawRequest) { + return $resultBody; } else { - $decoded = json_decode($resultBody, true); - if ($decoded === NULL) { - $jsonError = $this->json_error_to_string(json_last_error()); - if (!empty($jsonError)) { - error_log(sprintf("Error parsing response body JSON: %s", $jsonError)); - error_log(sprintf("response body: %s", $result->getBody())); - throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $jsonError)); - } - } - return $decoded; + $decoded = json_decode($resultBody, true); + if ($decoded === NULL) { + $jsonError = $this->json_error_to_string(json_last_error()); + if (!empty($jsonError)) { + error_log(sprintf("Error parsing response body JSON: %s", $jsonError)); + error_log(sprintf("response body: %s", $result->getBody())); + throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $jsonError)); + } + } + return $decoded; } } - private function json_error_to_string($jsonErrorCode) { + private function json_error_to_string($jsonErrorCode) + { switch ($jsonErrorCode) { case JSON_ERROR_NONE: return NULL; @@ -283,55 +264,55 @@ class Users extends ToopherObjectFactory { public function getById($userId) { - $url = 'users/' . $userId; - $result = $this->api->advanced->raw->get($url); - return new User($result, $this->api); + $url = 'users/' . $userId; + $result = $this->api->advanced->raw->get($url); + return new User($result, $this->api); } public function getByName($username) { - $url = 'users'; - $params = array('user_name' => $username); - $users = $this->api->advanced->raw->get($url, $params); - if (sizeof($users) > 1) { - throw new ToopherRequestException(sprintf("Multiple users with name = %s", $username)); - } elseif (empty($users)) { - throw new ToopherRequestException(sprintf("No users with name = %s", $username)); - } - return new User(array_shift($users), $this->api); + $url = 'users'; + $params = array('user_name' => $username); + $users = $this->api->advanced->raw->get($url, $params); + if (sizeof($users) > 1) { + throw new ToopherRequestException(sprintf("Multiple users with name = %s", $username)); + } elseif (empty($users)) { + throw new ToopherRequestException(sprintf("No users with name = %s", $username)); + } + return new User(array_shift($users), $this->api); } public function create($username, $kwargs = array()) { - $url = 'users/create'; - $params = array('name' => $username); - $params = array_merge($params, $kwargs); - $result = $this->api->advanced->raw->post($url, $params); - return new User($result, $this->api); + $url = 'users/create'; + $params = array('name' => $username); + $params = array_merge($params, $kwargs); + $result = $this->api->advanced->raw->post($url, $params); + return new User($result, $this->api); } } class UserTerminals extends ToopherObjectFactory { - public function getById($userTerminalId) - { - $url = 'user_terminals/' . $userTerminalId; - $result = $this->api->advanced->raw->get($url); - return new UserTerminal($result, $this->api); - } - - public function create($username, $terminalName, $requesterSpecifiedId, $kwargs = array()) - { - $url = 'user_terminals/create'; - $params = array( - 'user_name' => $username, - 'name' => $terminalName, - 'name_extra' => $requesterSpecifiedId - ); - $params = array_merge($params, $kwargs); - $result = $this->api->advanced->raw->post($url, $params); - return new UserTerminal($result, $this->api); - } + public function getById($userTerminalId) + { + $url = 'user_terminals/' . $userTerminalId; + $result = $this->api->advanced->raw->get($url); + return new UserTerminal($result, $this->api); + } + + public function create($username, $terminalName, $requesterSpecifiedId, $kwargs = array()) + { + $url = 'user_terminals/create'; + $params = array( + 'user_name' => $username, + 'name' => $terminalName, + 'name_extra' => $requesterSpecifiedId + ); + $params = array_merge($params, $kwargs); + $result = $this->api->advanced->raw->post($url, $params); + return new UserTerminal($result, $this->api); + } } ?> diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 17cabb7..0fa26c1 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -28,186 +28,187 @@ class SignatureValidationError extends Exception class ToopherIframe { - const VERSION = '2'; - - function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') - { - $this->consumerSecret = $secret; - $this->consumerKey = $key; - $this->oauthConsumer = new OAuth($key, $secret); - $this->baseUrl = $baseUrl; - $this->timestampOverride = NULL; - $this->nonceOverride = NULL; - $this->oauthVersion = '1.0'; - $this->signatureMethod = 'HMAC-SHA1'; - } - - public function setTimestampOverride($timestampOverride) - { - $this->timestampOverride = $timestampOverride; - } - - public function setNonceOverride($nonceOverride) - { - $this->nonceOverride = $nonceOverride; - } - - private function getUnixTimestamp() - { - if (!is_null($this->timestampOverride)) { - return $this->timestampOverride; - } else { - return time(); + const VERSION = '2'; + + function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') + { + $this->consumerSecret = $secret; + $this->consumerKey = $key; + $this->oauthConsumer = new OAuth($key, $secret); + $this->baseUrl = $baseUrl; + $this->timestampOverride = NULL; + $this->nonceOverride = NULL; + $this->oauthVersion = '1.0'; + $this->signatureMethod = 'HMAC-SHA1'; } - } - - public function getAuthenticationUrl($username, $resetEmail, $requestToken, $actionName = 'Log In', $requesterMetadata = 'None', $kwargs = array()) - { - if (array_key_exists('ttl', $kwargs)) { - $ttl = $kwargs['ttl']; - unset($kwargs['ttl']); - } else { - $ttl = 300; + + public function setTimestampOverride($timestampOverride) + { + $this->timestampOverride = $timestampOverride; + } + + public function setNonceOverride($nonceOverride) + { + $this->nonceOverride = $nonceOverride; + } + + private function getUnixTimestamp() + { + if (!is_null($this->timestampOverride)) { + return $this->timestampOverride; + } else { + return time(); + } + } + + public function getAuthenticationUrl($username, $resetEmail, $requestToken = 'None', $actionName = 'Log In', $requesterMetadata = 'None', $kwargs = array()) + { + if (array_key_exists('ttl', $kwargs)) { + $ttl = $kwargs['ttl']; + unset($kwargs['ttl']); + } else { + $ttl = 300; + } + + $params = array( + 'v' => ToopherIframe::VERSION, + 'username' => $username, + 'reset_email' => $resetEmail, + 'action_name' => $actionName, + 'session_token' => $requestToken, + 'requester_metadata' => $requesterMetadata, + 'expires' => $this->getUnixTimestamp() + $ttl + ); + $params = array_merge($params, $kwargs); + + return $this->getOauthSignedUrl($this->baseUrl . 'web/authenticate', $params); } - $params = array( - 'v' => ToopherIframe::VERSION, - 'username' => $username, - 'reset_email' => $resetEmail, - 'action_name' => $actionName, - 'session_token' => $requestToken, - 'requester_metadata' => $requesterMetadata, - 'expires' => $this->getUnixTimestamp() + $ttl - ); - $params = array_merge($params, $kwargs); - - return $this->getOauthSignedUrl($this->baseUrl . 'web/authenticate', $params); - } - - public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) - { - if (array_key_exists('ttl', $kwargs)) { - $ttl = $kwargs['ttl']; - unset($kwargs['ttl']); - } else { - $ttl = 300; + public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) + { + if (array_key_exists('ttl', $kwargs)) { + $ttl = $kwargs['ttl']; + unset($kwargs['ttl']); + } else { + $ttl = 300; + } + + $params = array( + 'v' => ToopherIframe::VERSION, + 'username' => $username, + 'reset_email' => $resetEmail, + 'expires' => $this->getUnixTimestamp() + $ttl + ); + $params = array_merge($params, $kwargs); + return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $params); } - $params = array( - 'v' => ToopherIframe::VERSION, - 'username' => $username, - 'reset_email' => $resetEmail, - 'expires' => $this->getUnixTimestamp() + $ttl - ); - $params = array_merge($params, $kwargs); - return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $params); - } - - public function validatePostback($parameters, $sessionToken, $ttl) - { - try { - $data = array(); - - foreach ($parameters as $key => $value) { - $data[$key] = $value[0]; - } - - $missingKeys = array(); - if (!array_key_exists('toopher_sig', $data)) { - $missingKeys[] = 'toopher_sig'; - } - if (!array_key_exists('timestamp', $data)) { - $missingKeys[] = 'timestamp'; - } - if (!array_key_exists('session_token', $data)) { - $missingKeys[] = 'session_token'; - } - if (count($missingKeys) > 0) { - $keys = implode(',', $missingKeys); - throw new SignatureValidationError('Missing required keys: ' . $keys); - } - - if ($data['session_token'] != $sessionToken) { - throw new SignatureValidationError('Session token does not match expected value'); - } - - $maybeSignature = $data['toopher_sig']; - unset($data['toopher_sig']); - $signatureValid = false; - try { - $computedSignature = $this->signature($this->consumerSecret, $data); - $signatureValid = $maybeSignature == $computedSignature; - } catch (Exception $e) { - throw new SignatureValidationError('Error while calculating signature: ' . $e); - } - - if (!$signatureValid) { - throw new SignatureValidationError('Computed signature does not match'); - } - - $ttlValid = ($this->getUnixTimestamp() - $ttl) < $data['timestamp']; - if (!$ttlValid) { - throw new SignatureValidationError('TTL Expired'); - } - - return $data; - } catch (Exception $e) { - throw new SignatureValidationError ('Exception while validating toopher signature: ' . $e); + public function validatePostback($parameters, $sessionToken, $ttl) + { + try { + $data = array(); + + foreach ($parameters as $key => $value) { + $data[$key] = $value[0]; + } + + $missingKeys = array(); + if (!array_key_exists('toopher_sig', $data)) { + $missingKeys[] = 'toopher_sig'; + } + if (!array_key_exists('timestamp', $data)) { + $missingKeys[] = 'timestamp'; + } + if (!array_key_exists('session_token', $data)) { + $missingKeys[] = 'session_token'; + } + if (count($missingKeys) > 0) { + $keys = implode(',', $missingKeys); + throw new SignatureValidationError('Missing required keys: ' . $keys); + } + + if ($data['session_token'] != $sessionToken) { + throw new SignatureValidationError('Session token does not match expected value'); + } + + $maybeSignature = $data['toopher_sig']; + unset($data['toopher_sig']); + $signatureValid = false; + try { + $computedSignature = $this->signature($this->consumerSecret, $data); + $signatureValid = $maybeSignature == $computedSignature; + } catch (Exception $e) { + throw new SignatureValidationError('Error while calculating signature: ' . $e); + } + + if (!$signatureValid) { + throw new SignatureValidationError('Computed signature does not match'); + } + + $ttlValid = ($this->getUnixTimestamp() - $ttl) < $data['timestamp']; + if (!$ttlValid) { + throw new SignatureValidationError('TTL Expired'); + } + + return $data; + } catch (Exception $e) { + throw new SignatureValidationError ('Exception while validating toopher signature: ' . $e); + } } - } - - private function signature($secret, $parameters) - { - $oauthConsumer = new HTTP_OAuth_Consumer($this->consumerKey, $this->consumerSecret); - $params = $oauthConsumer->buildHttpQuery($parameters); - $key = mb_convert_encoding($secret, "UTF-8"); - $sig = hash_hmac('sha1', $params, $secret, true); - return base64_encode($sig); - } - - private function getOauthSignedUrl($url, $queryParams) - { - $oauthParams = $this->getOauthParams(); - $encodedParams = $this->encodeParamsForSignature(array_merge($queryParams, $oauthParams)); - $signature = $this->oauthConsumer->generateSignature('GET', $url, $encodedParams); - $oauthParams['oauth_signature'] = $signature; - return $this->buildUrl($url, $queryParams, $oauthParams); - } - - private function encodeParamsForSignature($params) - { - foreach ($params as $key => $value) { - $params[$key] = oauth_urlencode($value); - }; - return $params; - } - - private function getOauthParams() - { - $oauthParams = array( - 'oauth_consumer_key' => $this->consumerKey, - 'oauth_signature_method' => $this->signatureMethod, - 'oauth_version' => $this->oauthVersion - ); - if (!is_null($this->nonceOverride)) { - $oauthParams['oauth_nonce'] = $this->nonceOverride; - } else { - $oauthParams['oauth_nonce'] = uniqid() . '.' . time(); + + private function signature($secret, $parameters) + { + $oauthConsumer = new HTTP_OAuth_Consumer($this->consumerKey, $this->consumerSecret); + $params = $oauthConsumer->buildHttpQuery($parameters); + $key = mb_convert_encoding($secret, "UTF-8"); + $sig = hash_hmac('sha1', $params, $secret, true); + return base64_encode($sig); } - if (!is_null($this->timestampOverride)) { - $oauthParams['oauth_timestamp'] = $this->timestampOverride; - } else { - $oauthParams['oauth_timestamp'] = time(); + + private function getOauthSignedUrl($url, $queryParams) + { + $oauthParams = $this->getOauthParams(); + $encodedParams = $this->encodeParamsForSignature(array_merge($queryParams, $oauthParams)); + $signature = $this->oauthConsumer->generateSignature('GET', $url, $encodedParams); + $oauthParams['oauth_signature'] = $signature; + return $this->buildUrl($url, $queryParams, $oauthParams); + } + + private function encodeParamsForSignature($params) + { + foreach ($params as $key => $value) { + $params[$key] = oauth_urlencode($value); + } + return $params; + } + + private function getOauthParams() + { + $oauthParams = array( + 'oauth_consumer_key' => $this->consumerKey, + 'oauth_signature_method' => $this->signatureMethod, + 'oauth_version' => $this->oauthVersion + ); + + if (!is_null($this->nonceOverride)) { + $oauthParams['oauth_nonce'] = $this->nonceOverride; + } else { + $oauthParams['oauth_nonce'] = uniqid() . '.' . time(); + } + if (!is_null($this->timestampOverride)) { + $oauthParams['oauth_timestamp'] = $this->timestampOverride; + } else { + $oauthParams['oauth_timestamp'] = time(); + } + return $oauthParams; + } + + private function buildUrl($url, $queryParams, $oauthParams) + { + $query = http_build_query($queryParams); + $oauthQuery = http_build_query($oauthParams); + return $url . '?' . $query . '&' . $oauthQuery; } - return $oauthParams; - } - - private function buildUrl($url, $queryParams, $oauthParams) - { - $query = http_build_query($queryParams); - $oauthQuery = http_build_query($oauthParams); - return $url . '?' . $query . '&' . $oauthQuery; - } } ?> diff --git a/lib/User.php b/lib/User.php index b144e71..122ffbb 100644 --- a/lib/User.php +++ b/lib/User.php @@ -24,44 +24,44 @@ class User { - protected $api; + protected $api; - function __construct($jsonResponse, $api) - { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; - $this->raw_response = $jsonResponse; - } + function __construct($jsonResponse, $api) + { + $this->api = $api; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; + $this->raw_response = $jsonResponse; + } - public function refreshFromServer() - { - $url = 'users/' . $this->id; - $result = $this->api->advanced->raw->get($url); - $this->update($result); - } + public function refreshFromServer() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } - public function enableToopherAuthentication() - { - $url = 'users/' . $this->id; - $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "true")); - $this->update($result); - } + public function enableToopherAuthentication() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "true")); + $this->update($result); + } - public function disableToopherAuthentication() - { - $url = 'users/' . $this->id; - $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "false")); - $this->update($result); - } + public function disableToopherAuthentication() + { + $url = 'users/' . $this->id; + $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "false")); + $this->update($result); + } - public function update($jsonResponse) - { - $this->name = $jsonResponse['name']; - $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; - $this->raw_response = $jsonResponse; - } + public function update($jsonResponse) + { + $this->name = $jsonResponse['name']; + $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; + $this->raw_response = $jsonResponse; + } } ?> diff --git a/lib/UserTerminal.php b/lib/UserTerminal.php index 9d363d7..14534b5 100644 --- a/lib/UserTerminal.php +++ b/lib/UserTerminal.php @@ -24,32 +24,32 @@ class UserTerminal { - protected $api; - - function __construct($jsonResponse, $api) - { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->requester_specified_id = $jsonResponse['requester_specified_id']; - $this->user = new User($jsonResponse['user'], $api); - $this->raw_response = $jsonResponse; - } - - public function refreshFromServer() - { - $url = 'user_terminals/' . $this->id; - $result = $this->api->advanced->raw->get($url); - $this->update($result); - } - - public function update($jsonResponse) - { - $this->name = $jsonResponse['name']; - $this->requester_specified_id = $jsonResponse['requester_specified_id']; - $this->user->update($jsonResponse['user']); - $this->raw_response = $jsonResponse; - } + protected $api; + + function __construct($jsonResponse, $api) + { + $this->api = $api; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->requester_specified_id = $jsonResponse['requester_specified_id']; + $this->user = new User($jsonResponse['user'], $api); + $this->raw_response = $jsonResponse; + } + + public function refreshFromServer() + { + $url = 'user_terminals/' . $this->id; + $result = $this->api->advanced->raw->get($url); + $this->update($result); + } + + public function update($jsonResponse) + { + $this->name = $jsonResponse['name']; + $this->requester_specified_id = $jsonResponse['requester_specified_id']; + $this->user->update($jsonResponse['user']); + $this->raw_response = $jsonResponse; + } } ?> diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 2d596d2..8772a7d 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -28,306 +28,306 @@ class ToopherApiTests extends PHPUnit_Framework_TestCase { protected function setUp() { - $this->mock = new HTTP_Request2_Adapter_Mock(); + $this->mock = new HTTP_Request2_Adapter_Mock(); } protected function getToopherApi($mock) { - return new ToopherApi('key', 'secret', '', $mock); + return new ToopherApi('key', 'secret', '', $mock); } public function compareToDefaultPairing($pairing) { - $this->assertTrue($pairing->id == '1', 'Pairing id was incorrect'); - $this->assertTrue($pairing->enabled == true, 'Pairing should be enabled'); - $this->assertTrue($pairing->pending == false, 'Pairing should not be pending'); - $this->assertTrue($pairing->user->id == '1', 'User id was incorrect'); - $this->assertTrue($pairing->user->name == 'user', 'User name was wrong'); - $this->assertTrue($pairing->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + $this->assertTrue($pairing->id == '1', 'Pairing id was incorrect'); + $this->assertTrue($pairing->enabled == true, 'Pairing should be enabled'); + $this->assertTrue($pairing->pending == false, 'Pairing should not be pending'); + $this->assertTrue($pairing->user->id == '1', 'User id was incorrect'); + $this->assertTrue($pairing->user->name == 'user', 'User name was wrong'); + $this->assertTrue($pairing->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); } public function compareToDefaultAuthenticationRequest($authRequest, $id = '1') { - $this->assertTrue($authRequest->id == $id, 'Authentiation request id was incorrect'); - $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); - $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); - $this->assertTrue($authRequest->automated == true, 'Authentiation request should be automated'); - $this->assertTrue($authRequest->reason_code == '1', 'Authentication request reason code was incorrect'); - $this->assertTrue($authRequest->reason == 'some reason', 'Authentication request reason was incorrect'); - $this->assertTrue($authRequest->terminal->id == '1', 'Terminal id was incorrect'); - $this->assertTrue($authRequest->terminal->name == 'term name', 'Terminal name was incorrect'); - $this->assertTrue($authRequest->terminal->requester_specified_id == '1', 'Terminal requester_specified_id was incorrect'); - $this->assertTrue($authRequest->user->id == '1', 'User id was incorrect'); - $this->assertTrue($authRequest->user->name == 'user', 'User name was incorrect'); - $this->assertTrue($authRequest->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); - $this->assertTrue($authRequest->action->id == '1', 'Action id was incorrect'); - $this->assertTrue($authRequest->action->name == 'test', 'Action name was incorrect'); + $this->assertTrue($authRequest->id == $id, 'Authentiation request id was incorrect'); + $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest->automated == true, 'Authentiation request should be automated'); + $this->assertTrue($authRequest->reason_code == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest->reason == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest->terminal->id == '1', 'Terminal id was incorrect'); + $this->assertTrue($authRequest->terminal->name == 'term name', 'Terminal name was incorrect'); + $this->assertTrue($authRequest->terminal->requester_specified_id == '1', 'Terminal requester_specified_id was incorrect'); + $this->assertTrue($authRequest->user->id == '1', 'User id was incorrect'); + $this->assertTrue($authRequest->user->name == 'user', 'User name was incorrect'); + $this->assertTrue($authRequest->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + $this->assertTrue($authRequest->action->id == '1', 'Action id was incorrect'); + $this->assertTrue($authRequest->action->name == 'test', 'Action name was incorrect'); } public function compareToDefaultUser($user) { - $this->assertTrue($user->id == '1', 'User id was incorrect'); - $this->assertTrue($user->name == 'user', 'User name was incorrect'); - $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + $this->assertTrue($user->id == '1', 'User id was incorrect'); + $this->assertTrue($user->name == 'user', 'User name was incorrect'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); } public function compareToDefaultUserTerminal($userTerminal) { - $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); - $this->assertTrue($userTerminal->name == 'terminal name', 'wrong terminal name'); - $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); - $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); - $this->assertTrue($userTerminal->user->name == 'user name', 'bad user name'); - $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); + $this->assertTrue($userTerminal->id == '1', 'wrong terminal id'); + $this->assertTrue($userTerminal->name == 'terminal name', 'wrong terminal name'); + $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id', 'wrong requester specified id'); + $this->assertTrue($userTerminal->user->id == '1', 'bad user id'); + $this->assertTrue($userTerminal->user->name == 'user name', 'bad user name'); + $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } public function testCanCreateToopherApiWithArguments() { - $toopher = new ToopherApi('key', 'secret'); + $toopher = new ToopherApi('key', 'secret'); } public function testToopherVersionStringExists() { - $this->assertNotEmpty(ToopherApi::VERSION, 'no version string'); - list($major, $minor, $patch) = explode('.', ToopherApi::VERSION); - $this->assertGreaterThanOrEqual(1, (int)$major); - $this->assertGreaterThanOrEqual(0, (int)$minor); - $this->assertGreaterThanOrEqual(0, (int)$patch); + $this->assertNotEmpty(ToopherApi::VERSION, 'no version string'); + list($major, $minor, $patch) = explode('.', ToopherApi::VERSION); + $this->assertGreaterThanOrEqual(1, (int)$major); + $this->assertGreaterThanOrEqual(0, (int)$minor); + $this->assertGreaterThanOrEqual(0, (int)$patch); } public function testPair(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); - $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->pair('user', 'immediate_pair'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultPairing($pairing); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); + $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->pair('user', 'immediate_pair'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } public function testPairSms(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); - $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->pair('user', '555-555-5555'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultPairing($pairing); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); + $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->pair('user', '555-555-5555'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } public function testPairQr(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); - $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->pair('user'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultPairing($pairing); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); + $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->pair('user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultPairing($pairing); } public function testAuthenticateWithPairingId(){ - $id = Uuid::uuid4()->toString(); - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->authenticate($id, 'term name'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultAuthenticationRequest($authRequest, $id); + $id = Uuid::uuid4()->toString(); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->authenticate($id, 'term name'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultAuthenticationRequest($authRequest, $id); } public function testAuthenticateWithUsername(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->authenticate('user', 'term name', '1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultAuthenticationRequest($authRequest); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->authenticate('user', 'term name', '1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultAuthenticationRequest($authRequest); } public function testRawPost(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $params = array('pairing_id' => '1', 'terminal_name' => 'term name'); - $authRequest = $toopher->advanced->raw->post('authentication_requests/initiate', $params); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); - $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); - $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); - $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); - $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); - $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); - $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); - $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); - $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $params = array('pairing_id' => '1', 'terminal_name' => 'term name'); + $authRequest = $toopher->advanced->raw->post('authentication_requests/initiate', $params); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); + $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); + $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); + $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); + $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); } public function testRawGet(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->advanced->raw->get('authentication_requests/1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); - $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); - $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); - $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); - $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); - $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); - $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); - $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); - $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->advanced->raw->get('authentication_requests/1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); + $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest['granted'] == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest['automated'] == true, 'Authentication request should be automated'); + $this->assertTrue($authRequest['reason_code'] == '1', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest['reason'] == 'some reason', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest['terminal'] == array('id'=>'1', 'name'=>'term name', 'requester_specified_id'=>'1', 'user'=>array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true)), 'Terminal data was incorrect'); + $this->assertTrue($authRequest['user'] == array('id'=>'1', 'name'=>'user', 'toopher_authentication_enabled'=>true), 'User data was incorrect'); + $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); } public function testPairingsGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); - $resp->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->advanced->pairings->getById('1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultPairing($pairing); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $toopher->advanced->pairings->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultPairing($pairing); } public function testAuthenticationRequestsGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->advanced->authenticationRequests->getById('1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultAuthenticationRequest($authRequest); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->advanced->authenticationRequests->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultAuthenticationRequest($authRequest); } public function testUsersGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); - $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $user = $toopher->advanced->users->getById('1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultUser($user); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $user = $toopher->advanced->users->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultUser($user); } public function testUsersGetByName(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); - $resp->appendBody('[{"id":"1","name":"user","toopher_authentication_enabled":true}]'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $user = $toopher->advanced->users->getByName('paired user'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultUser($user); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); + $resp->appendBody('[{"id":"1","name":"user","toopher_authentication_enabled":true}]'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $user = $toopher->advanced->users->getByName('paired user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultUser($user); } public function testUsersCreate(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); - $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $user = $toopher->advanced->users->create('paired user'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultUser($user); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); + $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $user = $toopher->advanced->users->create('paired user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultUser($user); } public function testUsersCreateWithExtras(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); - $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); - $this->mock->addResponse($resp); - - $toopher = $this->getToopherApi($this->mock); - $user = $toopher->advanced->users->create('paired user', array('foo'=>'bar')); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultUser($user); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); + $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $user = $toopher->advanced->users->create('paired user', array('foo'=>'bar')); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultUser($user); } public function testUserTerminalsGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); - $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $userTerminal = $toopher->advanced->userTerminals->getById('1'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultUserTerminal($userTerminal); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + + $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $userTerminal = $toopher->advanced->userTerminals->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultUserTerminal($userTerminal); } public function testUserTerminalCreate(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); - $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultUserTerminal($userTerminal); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); + $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + + $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultUserTerminal($userTerminal); } public function testUserTerminalCreateWithExtras(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); - $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); - $this->mock->addResponse($resp); - - $toopher = new ToopherApi('key', 'secret', '', $this->mock); - $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id', array('foo'=>'bar')); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->compareToDefaultUserTerminal($userTerminal); + $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); + $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); + $this->mock->addResponse($resp); + + $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id', array('foo'=>'bar')); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultUserTerminal($userTerminal); } /** * @expectedException InvalidArgumentException */ public function testEmptyKeyThrowsException() { - $toopher = new ToopherApi('', 'secret'); + $toopher = new ToopherApi('', 'secret'); } /** * @expectedException InvalidArgumentException */ public function testEmptySecretThrowsException() { - $toopher = new ToopherApi('key', ''); + $toopher = new ToopherApi('key', ''); } /** * @expectedException ToopherRequestException */ public function testToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 401 Unauthorized", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $auth = $toopher->advanced->authenticationRequests->getById('1'); + $resp = new HTTP_Request2_Response("HTTP/1.1 401 Unauthorized", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } /** * @expectedException ToopherRequestException */ public function test400WithEmptyBodyRaisesToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $auth = $toopher->advanced->authenticationRequests->getById('1'); + $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } /** * @expectedException ToopherRequestException */ public function test400WithUnprintableBodyRaisesToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); - $this->mock->addResponse($resp); - $toopher = $this->getToopherApi($this->mock); - $auth = $toopher->advanced->authenticationRequests->getById('1'); + $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); } } From 7abd1c84c4d06da0243b541ae31d418d7a3d1c69 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 13:10:35 -0600 Subject: [PATCH 072/114] Default to single quotes and not double --- demo/toopher_demo.php | 30 ++++++++--------- lib/ToopherApi.php | 26 +++++++-------- lib/ToopherIframe.php | 2 +- lib/User.php | 4 +-- test/ActionTest.php | 4 +-- test/AuthenticationRequestTest.php | 10 +++--- test/PairingTest.php | 12 +++---- test/ToopherApiTest.php | 52 +++++++++++++++--------------- test/ToopherIframeTest.php | 14 ++++---- test/UserTerminalTest.php | 6 ++-- test/UserTest.php | 16 ++++----- 11 files changed, 88 insertions(+), 88 deletions(-) diff --git a/demo/toopher_demo.php b/demo/toopher_demo.php index 5897f26..f8a5d69 100644 --- a/demo/toopher_demo.php +++ b/demo/toopher_demo.php @@ -22,7 +22,7 @@ SOFTWARE. */ -require_once("bootstrap.php"); +require_once('bootstrap.php'); $stdin = fopen('php://stdin', 'r'); @@ -46,9 +46,9 @@ function initializeApi() if(empty($key) || empty($secret)){ echo("Enter your requester credentials (from https://dev.toopher.com).\n"); echo("Hint: Set the TOOPHER_CONSUMER_SECRET and TOOPHER_CONSUMER_SECRET environment variables to avoid this prompt.\n"); - echo("Consumer Key:"); + echo('Consumer Key:'); $key = rtrim(fgets($stdin)); - echo("Consumer Secret:"); + echo('Consumer Secret:'); $secret = rtrim(fgets($stdin)); } @@ -61,16 +61,16 @@ function pair($toopher) global $stdin; while(true) { - printTextWithUnderline("STEP 1: Pair requester with phone"); + printTextWithUnderline('STEP 1: Pair requester with phone'); echo("Pairing phrases are generated on the mobile app\n"); do { - echo("Enter pairing phrase: "); + echo('Enter pairing phrase: '); $phrase = rtrim(fgets($stdin)); } while (empty($phrase)); do { - echo("Enter user name: "); + echo('Enter user name: '); $userName = rtrim(fgets($stdin)); } while (empty($userName)); @@ -83,7 +83,7 @@ function pair($toopher) } while(true) { - echo("Authorize pairing on phone and then press return to continue."); + echo('Authorize pairing on phone and then press return to continue.'); rtrim(fgets($stdin)); echo("\nChecking status of pairing request...\n"); @@ -109,10 +109,10 @@ function authenticate($pairing, $toopher) global $stdin; while(true) { - printTextWithUnderline("STEP 2: Authenticate log in"); + printTextWithUnderline('STEP 2: Authenticate log in'); do { - echo("Enter a terminal name for this authentication request [my computer]:"); + echo('Enter a terminal name for this authentication request [my computer]:'); $terminalName = rtrim(fgets($stdin)); } while (empty($terminalName)); @@ -120,18 +120,18 @@ function authenticate($pairing, $toopher) try { $auth = $toopher->authenticate($pairing->user->name, $terminalName); } catch (Exception $e) { - echo ("Error initiating authentication (Reason: $e)"); + echo ('Error initiating authentication (Reason: $e)'); } while(true) { - echo ("Respond to authentication request on phone and then press return to continue."); + echo ('Respond to authentication request on phone and then press return to continue.'); rtrim(fgets($stdin)); echo ("\nChecking status of authenticationr request...\n"); try { $auth->refreshFromServer(); } catch (Exception $e) { - echo ("Could not check authentication status (Reason: $e)"); + echo ('Could not check authentication status (Reason: $e)'); } if ($auth->pending) { @@ -139,18 +139,18 @@ function authenticate($pairing, $toopher) } else { $automation = $auth->automated ? 'automatically ' : ''; $result = $auth->granted ? 'granted' : 'denied'; - echo ("The request was " . $automation . $result . "!\n" ); + echo ('The request was ' . $automation . $result . "!\n" ); break; } } - echo("Press return to authenticate again, or [Ctrl+C] to exit"); + echo('Press return to authenticate again, or [Ctrl+C] to exit'); rtrim(fgets($stdin)); } } function demo() { - printTextWithUnderline("Toopher Library Demo", "="); + printTextWithUnderline('Toopher Library Demo', '='); $toopher = initializeApi(); diff --git a/lib/ToopherApi.php b/lib/ToopherApi.php index eaf9db5..8173b77 100644 --- a/lib/ToopherApi.php +++ b/lib/ToopherApi.php @@ -173,14 +173,14 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest $result = $this->oauthConsumer->sendRequest($this->baseUrl . $endpoint, $parameters, $method); } catch (Exception $e) { error_log($e); - throw new ToopherRequestException("Error making Toopher API request", $e->getCode(), $e); + throw new ToopherRequestException('Error making Toopher API request', $e->getCode(), $e); } $resultBody = $result->getBody(); if ($result->getStatus() >= 400) { - error_log(sprintf("Toopher API call returned unexpected HTTP response: %d - %s", $result->getStatus(), $result->getReasonPhrase())); + error_log(sprintf('Toopher API call returned unexpected HTTP response: %d - %s', $result->getStatus(), $result->getReasonPhrase())); if (empty($resultBody)) { - error_log("empty response body"); + error_log('empty response body'); throw new ToopherRequestException($result->getReasonPhrase(), $result->getStatus()); } @@ -189,16 +189,16 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest $jsonError = $this->json_error_to_string(json_last_error()); if (!empty($jsonError)) { - error_log(sprintf("Error parsing response body JSON: %s", $jsonError)); - error_log(sprintf("response body: %s", $result->getBody())); - throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $jsonError)); + error_log(sprintf('Error parsing response body JSON: %s', $jsonError)); + error_log(sprintf('response body: %s', $result->getBody())); + throw new ToopherRequestException(sprintf('JSON Parsing Error: %s', $jsonError)); } } else { - if(array_key_exists("error_message", $err)) + if(array_key_exists('error_message', $err)) { throw new ToopherRequestException($err['error_message'], $err['error_code']); } else { - throw new ToopherRequestException(sprintf("%s - %s", $result->getReasonPhrase(), $resultBody), $result->getStatus()); + throw new ToopherRequestException(sprintf('%s - %s', $result->getReasonPhrase(), $resultBody), $result->getStatus()); } } } @@ -210,9 +210,9 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest if ($decoded === NULL) { $jsonError = $this->json_error_to_string(json_last_error()); if (!empty($jsonError)) { - error_log(sprintf("Error parsing response body JSON: %s", $jsonError)); - error_log(sprintf("response body: %s", $result->getBody())); - throw new ToopherRequestException(sprintf("JSON Parsing Error: %s", $jsonError)); + error_log(sprintf('Error parsing response body JSON: %s', $jsonError)); + error_log(sprintf('response body: %s', $result->getBody())); + throw new ToopherRequestException(sprintf('JSON Parsing Error: %s', $jsonError)); } } return $decoded; @@ -275,9 +275,9 @@ public function getByName($username) $params = array('user_name' => $username); $users = $this->api->advanced->raw->get($url, $params); if (sizeof($users) > 1) { - throw new ToopherRequestException(sprintf("Multiple users with name = %s", $username)); + throw new ToopherRequestException(sprintf('Multiple users with name = %s', $username)); } elseif (empty($users)) { - throw new ToopherRequestException(sprintf("No users with name = %s", $username)); + throw new ToopherRequestException(sprintf('No users with name = %s', $username)); } return new User(array_shift($users), $this->api); } diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 0fa26c1..8c2fe8b 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -160,7 +160,7 @@ private function signature($secret, $parameters) { $oauthConsumer = new HTTP_OAuth_Consumer($this->consumerKey, $this->consumerSecret); $params = $oauthConsumer->buildHttpQuery($parameters); - $key = mb_convert_encoding($secret, "UTF-8"); + $key = mb_convert_encoding($secret, 'UTF-8'); $sig = hash_hmac('sha1', $params, $secret, true); return base64_encode($sig); } diff --git a/lib/User.php b/lib/User.php index 122ffbb..8f447a5 100644 --- a/lib/User.php +++ b/lib/User.php @@ -45,14 +45,14 @@ public function refreshFromServer() public function enableToopherAuthentication() { $url = 'users/' . $this->id; - $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "true")); + $result = $this->api->advanced->raw->post($url, array('toopher_authentication_enabled' => 'true')); $this->update($result); } public function disableToopherAuthentication() { $url = 'users/' . $this->id; - $result = $this->api->advanced->raw->post($url, array("toopher_authentication_enabled" => "false")); + $result = $this->api->advanced->raw->post($url, array('toopher_authentication_enabled' => 'false')); $this->update($result); } diff --git a/test/ActionTest.php b/test/ActionTest.php index 69a41c5..9e0006d 100644 --- a/test/ActionTest.php +++ b/test/ActionTest.php @@ -27,7 +27,7 @@ class ActionTests extends PHPUnit_Framework_TestCase { public function testAction() { $toopher = new ToopherApi('key', 'secret'); - $action = new Action(["id" => "1", "name" => "action"]); + $action = new Action(['id' => '1', 'name' => 'action']); $this->assertTrue($action->id == '1', 'Action id was incorrect'); $this->assertTrue($action->name == 'action', 'Action name was incorrect'); } @@ -35,7 +35,7 @@ public function testAction() public function testActionUpdate() { $toopher = new ToopherApi('key', 'secret'); - $action = new Action(["id" => "1", "name" => "action changed"]); + $action = new Action(['id' => '1', 'name' => 'action changed']); $action->update(['id'=>'1', 'name'=>'action changed']); $this->assertTrue($action->id == '1', 'Action id was incorrect'); $this->assertTrue($action->name == 'action changed', 'Action name was incorrect'); diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php index a388d0a..470baf2 100644 --- a/test/AuthenticationRequestTest.php +++ b/test/AuthenticationRequestTest.php @@ -35,7 +35,7 @@ protected function getToopherApi($mock = NULL) protected function getAuthenticationRequest($api) { - return new AuthenticationRequest(["id"=>"1","pending"=>true,"granted"=>false,"automated"=>false,"reason_code"=>"1","reason"=>"some reason","terminal"=>["id"=>"1","name"=>"term name","requester_specified_id"=>"1","user"=>["id"=>"1","name"=>"user","toopher_authentication_enabled"=>"true"]],"user"=>["id"=>"1","name"=>"user", "toopher_authentication_enabled"=>"true"],"action"=>["id"=>"1","name"=>"test"]], $api); + return new AuthenticationRequest(['id'=>'1','pending'=>true,'granted'=>false,'automated'=>false,'reason_code'=>'1','reason'=>'some reason','terminal'=>['id'=>'1','name'=>'term name','requester_specified_id'=>'1','user'=>['id'=>'1','name'=>'user','toopher_authentication_enabled'=>'true']],'user'=>['id'=>'1','name'=>'user', 'toopher_authentication_enabled'=>'true'],'action'=>['id'=>'1','name'=>'test']], $api); } public function testAuthenticationRequest() @@ -58,8 +58,8 @@ public function testAuthenticationRequest() } public function testAuthenticationRequestRefreshFromServer(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user changed", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user changed", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test changed"}}'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user changed", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user changed", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test changed"}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -77,8 +77,8 @@ public function testAuthenticationRequestRefreshFromServer(){ } public function testGrantAuthenticationRequestWithOtp(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1/otp_auth'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1/otp_auth'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); diff --git a/test/PairingTest.php b/test/PairingTest.php index b8c57b0..3abece3 100644 --- a/test/PairingTest.php +++ b/test/PairingTest.php @@ -36,7 +36,7 @@ protected function getToopherApi($mock = NULL) protected function getPairing($api) { - return new Pairing(["id" => "1","enabled" => true, "pending" => false, "user" => ["id" => "1","name" => "user", "toopher_authentication_enabled" => "true"]], $api); + return new Pairing(['id' => '1','enabled' => true, 'pending' => false, 'user' => ['id' => '1','name' => 'user', 'toopher_authentication_enabled' => 'true']], $api); } public function testPairing(){ @@ -51,7 +51,7 @@ public function testPairing(){ public function testPairingRefreshFromServer(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1'); $resp->appendBody('{"id":"1","enabled":false,"pending":true,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":false}}'); $this->mock->addResponse($resp); @@ -67,7 +67,7 @@ public function testPairingRefreshFromServer(){ } public function testGetPairingResetLink(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); $resp->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); $this->mock->addResponse($resp); @@ -76,11 +76,11 @@ public function testGetPairingResetLink(){ $resetLink = $pairing->getResetLink(); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->assertTrue($resetLink == "http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde", 'Pairing reset link was incorrect'); + $this->assertTrue($resetLink == 'http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde', 'Pairing reset link was incorrect'); } public function testEmailPairingResetLink(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -91,7 +91,7 @@ public function testEmailPairingResetLink(){ } public function testPairingGetQrCodeImage(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/qr/pairings/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/qr/pairings/1'); $resp->appendBody('{}'); $this->mock->addResponse($resp); diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 8772a7d..f833896 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -21,7 +21,7 @@ SOFTWARE. */ -require_once("bootstrap.php"); +require_once('bootstrap.php'); use Rhumsaa\Uuid\Uuid; class ToopherApiTests extends PHPUnit_Framework_TestCase { @@ -94,7 +94,7 @@ public function testToopherVersionStringExists() { } public function testPair(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create'); $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -104,7 +104,7 @@ public function testPair(){ } public function testPairSms(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/sms'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create/sms'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -114,7 +114,7 @@ public function testPairSms(){ } public function testPairQr(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/create/qr'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create/qr'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -125,8 +125,8 @@ public function testPairQr(){ public function testAuthenticateWithPairingId(){ $id = Uuid::uuid4()->toString(); - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -136,8 +136,8 @@ public function testAuthenticateWithPairingId(){ } public function testAuthenticateWithUsername(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -147,8 +147,8 @@ public function testAuthenticateWithUsername(){ } public function testRawPost(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/initiate'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -167,8 +167,8 @@ public function testRawPost(){ } public function testRawGet(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -186,7 +186,7 @@ public function testRawGet(){ } public function testPairingsGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/pairings/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1'); $resp->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -197,8 +197,8 @@ public function testPairingsGetById(){ } public function testAuthenticationRequestsGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":"true"},"action":{"id":"1","name":"test"}}'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -208,7 +208,7 @@ public function testAuthenticationRequestsGetById(){ } public function testUsersGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -219,7 +219,7 @@ public function testUsersGetById(){ } public function testUsersGetByName(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users'); $resp->appendBody('[{"id":"1","name":"user","toopher_authentication_enabled":true}]'); $this->mock->addResponse($resp); @@ -230,7 +230,7 @@ public function testUsersGetByName(){ } public function testUsersCreate(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/create'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -241,7 +241,7 @@ public function testUsersCreate(){ } public function testUsersCreateWithExtras(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/create'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/create'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -252,7 +252,7 @@ public function testUsersCreateWithExtras(){ } public function testUserTerminalsGetById(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/1'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -263,7 +263,7 @@ public function testUserTerminalsGetById(){ } public function testUserTerminalCreate(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/create'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -274,7 +274,7 @@ public function testUserTerminalCreate(){ } public function testUserTerminalCreateWithExtras(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/create'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/create'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -302,7 +302,7 @@ public function testEmptySecretThrowsException() { * @expectedException ToopherRequestException */ public function testToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 401 Unauthorized", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 401 Unauthorized', false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -313,7 +313,7 @@ public function testToopherRequestException(){ * @expectedException ToopherRequestException */ public function test400WithEmptyBodyRaisesToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 403 Forbidden', false, 'https://api.toopher.com/v1/authentication_requests/1'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); @@ -323,8 +323,8 @@ public function test400WithEmptyBodyRaisesToopherRequestException(){ * @expectedException ToopherRequestException */ public function test400WithUnprintableBodyRaisesToopherRequestException(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 403 Forbidden", false, 'https://api.toopher.com/v1/authentication_requests/1'); - $resp->appendBody(sprintf('{"error_code":403, "error_message":"%c"}', chr(5))); + $resp = new HTTP_Request2_Response('HTTP/1.1 403 Forbidden', false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody(sprintf("{'error_code':403, 'error_message':'%c'}", chr(5))); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 7b04a8d..b5baefd 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -21,7 +21,7 @@ SOFTWARE. */ -require_once("bootstrap.php"); +require_once('bootstrap.php'); use Rhumsaa\Uuid\Uuid; class ToopherIframeTests extends PHPUnit_Framework_TestCase { @@ -66,17 +66,17 @@ public function testToopherIframeGetAuthenticationUrl() { $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D"; + $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D'; $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } public function testToopherIframeGetAuthenticationUrlWithExtras() { - $extras = array("allow_inline_pairing" => "false"); + $extras = array('allow_inline_pairing' => 'false'); $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D"; + $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D'; $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'None', $extras); $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } @@ -85,17 +85,17 @@ public function testToopherIframeGetUserManagementUrl() { $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D"; + $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D'; $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com'); $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } public function testToopherIframeGetUserManagementUrlWithExtras() { - $extras = array("ttl" => "100"); + $extras = array('ttl' => '100'); $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D"; + $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D'; $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com', $extras); $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } diff --git a/test/UserTerminalTest.php b/test/UserTerminalTest.php index fefbe2f..0a29d7a 100644 --- a/test/UserTerminalTest.php +++ b/test/UserTerminalTest.php @@ -34,7 +34,7 @@ protected function getToopherApi($mock = NULL) protected function getUserTerminal($api) { - return new UserTerminal(["id" => "1", "name" => "terminal name", "requester_specified_id" => "requester specified id", "user" => ["id" => "1","name" => "user name", "toopher_authentication_enabled" => true]], $api); + return new UserTerminal(['id' => '1', 'name' => 'terminal name', 'requester_specified_id' => 'requester specified id', 'user' => ['id' => '1','name' => 'user name', 'toopher_authentication_enabled' => true]], $api); } public function testUserTerminal(){ @@ -48,7 +48,7 @@ public function testUserTerminal(){ } public function testUserTerminalRefreshFromServer(){ - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/user_terminals/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/1'); $resp->appendBody('{"id":"1", "name":"terminal name changed", "requester_specified_id":"requester specified id changed", "user":{"id":"1", "name":"user name changed", "toopher_authentication_enabled":false}}'); $this->mock->addResponse($resp); @@ -65,7 +65,7 @@ public function testUserTerminalRefreshFromServer(){ public function testUserTerminalUpdate(){ $userTerminal = $this->getUserTerminal($this->getToopherApi()); - $userTerminal->update(["id"=>"1", "name"=>"terminal name changed", "requester_specified_id"=>"requester specified id changed", "user"=>["id"=>"1", "name"=>"user name changed", "toopher_authentication_enabled"=>false]]); + $userTerminal->update(['id'=>'1', 'name'=>'terminal name changed', 'requester_specified_id'=>'requester specified id changed', 'user'=>['id'=>'1', 'name'=>'user name changed', 'toopher_authentication_enabled'=>false]]); $this->assertTrue($userTerminal->name == 'terminal name changed', 'Terminal name was wrong'); $this->assertTrue($userTerminal->requester_specified_id == 'requester specified id changed', 'Terminal requester_specified_id was incorrect'); $this->assertTrue($userTerminal->user->name == 'user name changed', 'User name was incorrect'); diff --git a/test/UserTest.php b/test/UserTest.php index 631e0ad..da11404 100644 --- a/test/UserTest.php +++ b/test/UserTest.php @@ -35,7 +35,7 @@ protected function getToopherApi($mock = NULL) protected function getUser($api) { - return new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => true], $api); + return new User(['id' => '1', 'name' => 'user', 'toopher_authentication_enabled' => true], $api); } public function testUser() @@ -48,7 +48,7 @@ public function testUser() public function testUserRefreshFromServer() { - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp->appendBody('{"id":"1","name":"user changed","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -63,23 +63,23 @@ public function testUserRefreshFromServer() public function testUserEnableToopherAuthentication() { - $resp = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); - $user = new User(["id" => "1", "name" => "user", "toopher_authentication_enabled" => false], $toopher); + $user = new User(['id' => '1', 'name' => 'user', 'toopher_authentication_enabled' => false], $toopher); $this->assertTrue($user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); $user->enableToopherAuthentication(); $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == "toopher_authentication_enabled=true", "Post params should include 'toopher_authentication_enabled=true'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == 'toopher_authentication_enabled=true', "Post params should include 'toopher_authentication_enabled=true'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); } public function testUserDisableToopherAuthentication() { - $resp1 = new HTTP_Request2_Response("HTTP/1.1 200 OK", false, 'https://api.toopher.com/v1/users/1'); + $resp1 = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":false}'); $this->mock->addResponse($resp1); @@ -89,7 +89,7 @@ public function testUserDisableToopherAuthentication() $user->disableToopherAuthentication(); $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == "toopher_authentication_enabled=false", "Post params should include'toopher_authentication_enabled=false"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == 'toopher_authentication_enabled=false', "Post params should include'toopher_authentication_enabled=false'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); } @@ -97,7 +97,7 @@ public function testUserUpdate() { $toopher = $this->getToopherApi($this->mock); $user = $this->getUser($toopher); - $user->update(["id" => "1", "name" => "user changed", "toopher_authentication_enabled" => false]); + $user->update(['id' => '1', 'name' => 'user changed', 'toopher_authentication_enabled' => false]); $this->assertTrue($user->name == 'user changed', 'User name was incorrect'); $this->assertTrue($user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); } From 51bcf0b817ea476bb166052484f0e68932e38a12 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 13:47:52 -0600 Subject: [PATCH 073/114] Rename tests to be more descriptive --- test/ActionTest.php | 4 +-- test/AuthenticationRequestTest.php | 48 +++++++++++++++++++++++++----- test/PairingTest.php | 27 +++++++++++++---- test/ToopherApiTest.php | 28 ++++++++--------- test/ToopherIframeTest.php | 8 ++--- test/UserTerminalTest.php | 6 ++-- test/UserTest.php | 12 ++++---- 7 files changed, 92 insertions(+), 41 deletions(-) diff --git a/test/ActionTest.php b/test/ActionTest.php index 9e0006d..4cbae70 100644 --- a/test/ActionTest.php +++ b/test/ActionTest.php @@ -24,7 +24,7 @@ class ActionTests extends PHPUnit_Framework_TestCase { - public function testAction() + public function testActionCreatesAction() { $toopher = new ToopherApi('key', 'secret'); $action = new Action(['id' => '1', 'name' => 'action']); @@ -32,7 +32,7 @@ public function testAction() $this->assertTrue($action->name == 'action', 'Action name was incorrect'); } - public function testActionUpdate() + public function testActionUpdateChangesAction() { $toopher = new ToopherApi('key', 'secret'); $action = new Action(['id' => '1', 'name' => 'action changed']); diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php index 470baf2..2138b99 100644 --- a/test/AuthenticationRequestTest.php +++ b/test/AuthenticationRequestTest.php @@ -28,6 +28,37 @@ protected function setUp() $this->mock = new HTTP_Request2_Adapter_Mock(); } + protected function getAuthenticationRequestJson() + { + return [ + 'id'=>'1', + 'pending'=>true, + 'granted'=>false, + 'automated'=>false, + 'reason_code'=>'1', + 'reason'=>'some reason', + 'terminal'=>[ + 'id'=>'1', + 'name'=>'term name', + 'requester_specified_id'=>'1', + 'user'=>[ + 'id'=>'1', + 'name'=>'user', + 'toopher_authentication_enabled'=>'true' + ] + ], + 'user'=>[ + 'id'=>'1', + 'name'=>'user', + 'toopher_authentication_enabled'=>'true' + ], + 'action'=>[ + 'id'=>'1', + 'name'=>'test' + ] + ]; + } + protected function getToopherApi($mock = NULL) { return new ToopherApi('key', 'secret', '', $mock); @@ -35,10 +66,10 @@ protected function getToopherApi($mock = NULL) protected function getAuthenticationRequest($api) { - return new AuthenticationRequest(['id'=>'1','pending'=>true,'granted'=>false,'automated'=>false,'reason_code'=>'1','reason'=>'some reason','terminal'=>['id'=>'1','name'=>'term name','requester_specified_id'=>'1','user'=>['id'=>'1','name'=>'user','toopher_authentication_enabled'=>'true']],'user'=>['id'=>'1','name'=>'user', 'toopher_authentication_enabled'=>'true'],'action'=>['id'=>'1','name'=>'test']], $api); + return new AuthenticationRequest($this->getAuthenticationRequestJson(), $api); } - public function testAuthenticationRequest() + public function testAuthenticationRequestCreatesAuthenticationRequest() { $authRequest = $this->getAuthenticationRequest($this->getToopherApi()); $this->assertTrue($authRequest->id == '1', 'Authentication request id was incorrect'); @@ -57,7 +88,8 @@ public function testAuthenticationRequest() $this->assertTrue($authRequest->action->name == 'test', 'Action name was incorrect'); } - public function testAuthenticationRequestRefreshFromServer(){ + public function testAuthenticationRequestRefreshFromServerUpdatesAuthenticationRequest() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user changed", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user changed", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test changed"}}'); $this->mock->addResponse($resp); @@ -76,7 +108,7 @@ public function testAuthenticationRequestRefreshFromServer(){ $this->assertTrue($authRequest->action->name == 'test changed', 'Action name was incorrect'); } - public function testGrantAuthenticationRequestWithOtp(){ + public function testGrantAuthenticationRequestPostsOtp(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1/otp_auth'); $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); @@ -86,9 +118,11 @@ public function testGrantAuthenticationRequestWithOtp(){ $authRequest->grantWithOtp('otp'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->assertTrue($authRequest->pending == false, 'wrong auth pending'); - $this->assertTrue($authRequest->granted == true, 'wrong auth granted'); - $this->assertTrue($authRequest->automated == true, 'wrong auth automated'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == 'otp=otp', "Post params should include 'otp=otp'"); + + $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest->automated == true, 'Authentication request should be automated'); } } diff --git a/test/PairingTest.php b/test/PairingTest.php index 3abece3..dd8d247 100644 --- a/test/PairingTest.php +++ b/test/PairingTest.php @@ -29,6 +29,20 @@ protected function setUp() $this->mock = new HTTP_Request2_Adapter_Mock(); } + protected function getPairingJson() + { + return [ + 'id' => '1', + 'enabled' => true, + 'pending' => false, + 'user' => [ + 'id' => '1', + 'name' => 'user', + 'toopher_authentication_enabled' => 'true' + ] + ]; + } + protected function getToopherApi($mock = NULL) { return new ToopherApi('key', 'secret', '', $mock); @@ -36,10 +50,10 @@ protected function getToopherApi($mock = NULL) protected function getPairing($api) { - return new Pairing(['id' => '1','enabled' => true, 'pending' => false, 'user' => ['id' => '1','name' => 'user', 'toopher_authentication_enabled' => 'true']], $api); + return new Pairing($this->getPairingJson(), $api); } - public function testPairing(){ + public function testPairingCreatesPairing(){ $pairing = $this->getPairing($this->getToopherApi()); $this->assertTrue($pairing->id == '1', 'Pairing id was incorrect'); $this->assertTrue($pairing->enabled == true, 'Pairing should be enabled'); @@ -50,7 +64,7 @@ public function testPairing(){ } - public function testPairingRefreshFromServer(){ + public function testPairingRefreshFromServerUpdatesPairing(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1'); $resp->appendBody('{"id":"1","enabled":false,"pending":true,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":false}}'); $this->mock->addResponse($resp); @@ -66,7 +80,7 @@ public function testPairingRefreshFromServer(){ $this->assertTrue($pairing->user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); } - public function testGetPairingResetLink(){ + public function testGetPairingResetLinkShouldReturnValidLink(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1/generate_reset_link'); $resp->appendBody('{"url":"http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde"}'); $this->mock->addResponse($resp); @@ -79,7 +93,7 @@ public function testGetPairingResetLink(){ $this->assertTrue($resetLink == 'http://api.toopher.test/v1/pairings/1/reset?reset_authorization=abcde', 'Pairing reset link was incorrect'); } - public function testEmailPairingResetLink(){ + public function testEmailPairingResetLinkShouldPostToCorrectUrl(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1/send_reset_link'); $this->mock->addResponse($resp); @@ -88,9 +102,10 @@ public function testEmailPairingResetLink(){ $pairing->emailResetLink('jdoe@example.com'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/pairings/1/send_reset_link', "Last called url should be 'https://api.toopher.com/v1/pairings/1/send_reset_link'"); } - public function testPairingGetQrCodeImage(){ + public function testPairingGetQrCodeImageShouldGetFromCorrectUrl(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/qr/pairings/1'); $resp->appendBody('{}'); $this->mock->addResponse($resp); diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index f833896..0bbbea2 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -93,7 +93,7 @@ public function testToopherVersionStringExists() { $this->assertGreaterThanOrEqual(0, (int)$patch); } - public function testPair(){ + public function testPairReturnsPairing(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create'); $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -103,7 +103,7 @@ public function testPair(){ $this->compareToDefaultPairing($pairing); } - public function testPairSms(){ + public function testPairSmsReturnsPairing(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create/sms'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -113,7 +113,7 @@ public function testPairSms(){ $this->compareToDefaultPairing($pairing); } - public function testPairQr(){ + public function testPairQrReturnsPairing(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create/qr'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -123,7 +123,7 @@ public function testPairQr(){ $this->compareToDefaultPairing($pairing); } - public function testAuthenticateWithPairingId(){ + public function testAuthenticateWithPairingIdReturnsAuthenticationRequest(){ $id = Uuid::uuid4()->toString(); $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); @@ -135,7 +135,7 @@ public function testAuthenticateWithPairingId(){ $this->compareToDefaultAuthenticationRequest($authRequest, $id); } - public function testAuthenticateWithUsername(){ + public function testAuthenticateWithUsernameReturnsAuthenticationRequest(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); @@ -185,7 +185,7 @@ public function testRawGet(){ $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); } - public function testPairingsGetById(){ + public function testPairingsGetByIdReturnsPairing(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1'); $resp->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -196,7 +196,7 @@ public function testPairingsGetById(){ $this->compareToDefaultPairing($pairing); } - public function testAuthenticationRequestsGetById(){ + public function testAuthenticationRequestsGetByIdReturnsAuthenticationRequest(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); @@ -207,7 +207,7 @@ public function testAuthenticationRequestsGetById(){ $this->compareToDefaultAuthenticationRequest($authRequest); } - public function testUsersGetById(){ + public function testUsersGetByIdReturnsUser(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -218,7 +218,7 @@ public function testUsersGetById(){ $this->compareToDefaultUser($user); } - public function testUsersGetByName(){ + public function testUsersGetByNameReturnsUser(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users'); $resp->appendBody('[{"id":"1","name":"user","toopher_authentication_enabled":true}]'); $this->mock->addResponse($resp); @@ -229,7 +229,7 @@ public function testUsersGetByName(){ $this->compareToDefaultUser($user); } - public function testUsersCreate(){ + public function testUsersCreateReturnsUser(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/create'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -240,7 +240,7 @@ public function testUsersCreate(){ $this->compareToDefaultUser($user); } - public function testUsersCreateWithExtras(){ + public function testUsersCreateWithExtrasReturnsUser(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/create'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -251,7 +251,7 @@ public function testUsersCreateWithExtras(){ $this->compareToDefaultUser($user); } - public function testUserTerminalsGetById(){ + public function testUserTerminalsGetByIdReturnsUserTerminal(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/1'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -262,7 +262,7 @@ public function testUserTerminalsGetById(){ $this->compareToDefaultUserTerminal($userTerminal); } - public function testUserTerminalCreate(){ + public function testUserTerminalCreateReturnsUserTerminal(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/create'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -273,7 +273,7 @@ public function testUserTerminalCreate(){ $this->compareToDefaultUserTerminal($userTerminal); } - public function testUserTerminalCreateWithExtras(){ + public function testUserTerminalCreateWithExtrasReturnsUserTerminal(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/create'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index b5baefd..099df34 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -62,7 +62,7 @@ protected function setUp() $this->toopherIframe = new ToopherIframe($this->getIframeKey(), $this->getIframeSecret(), 'https://api.toopher.test/v1/'); } - public function testToopherIframeGetAuthenticationUrl() + public function testToopherIframeGetAuthenticationUrlReturnsValidUrl() { $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); @@ -71,7 +71,7 @@ public function testToopherIframeGetAuthenticationUrl() $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } - public function testToopherIframeGetAuthenticationUrlWithExtras() + public function testToopherIframeGetAuthenticationUrlWithExtrasReturnsValidUrl() { $extras = array('allow_inline_pairing' => 'false'); $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); @@ -81,7 +81,7 @@ public function testToopherIframeGetAuthenticationUrlWithExtras() $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } - public function testToopherIframeGetUserManagementUrl() + public function testToopherIframeGetUserManagementUrlReturnsValidUrl() { $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); @@ -90,7 +90,7 @@ public function testToopherIframeGetUserManagementUrl() $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } - public function testToopherIframeGetUserManagementUrlWithExtras() + public function testToopherIframeGetUserManagementUrlWithExtrasReturnsValidUrl() { $extras = array('ttl' => '100'); $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); diff --git a/test/UserTerminalTest.php b/test/UserTerminalTest.php index 0a29d7a..19ff5f8 100644 --- a/test/UserTerminalTest.php +++ b/test/UserTerminalTest.php @@ -37,7 +37,7 @@ protected function getUserTerminal($api) return new UserTerminal(['id' => '1', 'name' => 'terminal name', 'requester_specified_id' => 'requester specified id', 'user' => ['id' => '1','name' => 'user name', 'toopher_authentication_enabled' => true]], $api); } - public function testUserTerminal(){ + public function testUserTerminalCreatesUserTerminal(){ $userTerminal = $this->getUserTerminal($this->getToopherApi()); $this->assertTrue($userTerminal->id == '1', 'Terminal id was incorrect'); $this->assertTrue($userTerminal->name == 'terminal name', 'Terminal name was incorrect'); @@ -47,7 +47,7 @@ public function testUserTerminal(){ $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); } - public function testUserTerminalRefreshFromServer(){ + public function testUserTerminalRefreshFromServerUpdatesUserTerminal(){ $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/1'); $resp->appendBody('{"id":"1", "name":"terminal name changed", "requester_specified_id":"requester specified id changed", "user":{"id":"1", "name":"user name changed", "toopher_authentication_enabled":false}}'); $this->mock->addResponse($resp); @@ -63,7 +63,7 @@ public function testUserTerminalRefreshFromServer(){ $this->assertTrue($userTerminal->user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); } - public function testUserTerminalUpdate(){ + public function testUserTerminalUpdateChangesUserTerminal(){ $userTerminal = $this->getUserTerminal($this->getToopherApi()); $userTerminal->update(['id'=>'1', 'name'=>'terminal name changed', 'requester_specified_id'=>'requester specified id changed', 'user'=>['id'=>'1', 'name'=>'user name changed', 'toopher_authentication_enabled'=>false]]); $this->assertTrue($userTerminal->name == 'terminal name changed', 'Terminal name was wrong'); diff --git a/test/UserTest.php b/test/UserTest.php index da11404..928d56f 100644 --- a/test/UserTest.php +++ b/test/UserTest.php @@ -38,7 +38,7 @@ protected function getUser($api) return new User(['id' => '1', 'name' => 'user', 'toopher_authentication_enabled' => true], $api); } - public function testUser() + public function testUserCreatesUser() { $user = $this->getUser($this->getToopherApi()); $this->assertTrue($user->id == '1', 'User id was incorrect'); @@ -46,7 +46,7 @@ public function testUser() $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); } - public function testUserRefreshFromServer() + public function testUserRefreshFromServerUpdatesUser() { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp->appendBody('{"id":"1","name":"user changed","toopher_authentication_enabled":true}'); @@ -61,7 +61,7 @@ public function testUserRefreshFromServer() $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); } - public function testUserEnableToopherAuthentication() + public function testUserEnableToopherAuthenticationPostsToCorrectUrl() { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); @@ -75,9 +75,10 @@ public function testUserEnableToopherAuthentication() $this->assertTrue($user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == 'toopher_authentication_enabled=true', "Post params should include 'toopher_authentication_enabled=true'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/users/1', "Last called url should be 'https://api.toopher/v1/users/1'"); } - public function testUserDisableToopherAuthentication() + public function testUserDisableToopherAuthenticationPostsToCorrectUrl() { $resp1 = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp1->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":false}'); @@ -91,9 +92,10 @@ public function testUserDisableToopherAuthentication() $this->assertTrue($user->toopher_authentication_enabled == false, 'toopher authentication should not be enabled'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == 'toopher_authentication_enabled=false', "Post params should include'toopher_authentication_enabled=false'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/users/1', "Last called url should be 'https://api.toopher/v1/users/1'"); } - public function testUserUpdate() + public function testUserUpdateChangesUser() { $toopher = $this->getToopherApi($this->mock); $user = $this->getUser($toopher); From 85ff9324648c8bdf23128a4def336d653280921d Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 14:00:33 -0600 Subject: [PATCH 074/114] Update test commands in README --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5262625..584538b 100644 --- a/README.md +++ b/README.md @@ -74,10 +74,10 @@ To avoid being prompted for your Toopher API key and secret, you can define them #### Tests To run all unit tests: ```shell -$ phpunit test/test_toopher_api.php +$ phpunit test ``` Note: `phpunit` may be found in `vendor/bin/php` so your test command would be ```shell -$ vendor/bin/phpunit test/test_toopher_api.php +$ vendor/bin/phpunit test ``` From c1f5e6b39940eb471ecdbb0a182cf749cbdad446 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 14:07:24 -0600 Subject: [PATCH 075/114] Throw ToopherRequestException when Action json is incomplete --- lib/Action.php | 18 +++++++++++++----- test/ActionTest.php | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/lib/Action.php b/lib/Action.php index f441a48..8b4801c 100644 --- a/lib/Action.php +++ b/lib/Action.php @@ -26,15 +26,23 @@ class Action { function __construct($jsonResponse) { - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->raw_response = $jsonResponse; + try { + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse action from response: ' . $e->getMessage()); + } } public function update($jsonResponse) { - $this->name = $jsonResponse['name']; - $this->raw_response = $jsonResponse; + try { + $this->name = $jsonResponse['name']; + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse action from response: ' . $e->getMessage()); + } } } diff --git a/test/ActionTest.php b/test/ActionTest.php index 4cbae70..3679ce1 100644 --- a/test/ActionTest.php +++ b/test/ActionTest.php @@ -40,6 +40,27 @@ public function testActionUpdateChangesAction() $this->assertTrue($action->id == '1', 'Action id was incorrect'); $this->assertTrue($action->name == 'action changed', 'Action name was incorrect'); } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse action from response + */ + public function testActionMissingKeyFails() + { + $toopher = new ToopherApi('key', 'secret'); + $action = new Action(['name' => 'action changed']); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse action from response + */ + public function testActionUpdateMissingKeyFails() + { + $toopher = new ToopherApi('key', 'secret'); + $action = new Action(['id' => '1', 'name' => 'action changed']); + $action->update(['id'=>'1']); + } } ?> From 9897c4090e824adec839828619f0d45058de3ecc Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 14:17:47 -0600 Subject: [PATCH 076/114] Throw ToopherRequestException when AuthenticationRequest json is incomplete --- lib/AuthenticationRequest.php | 48 +++++++++++++++++------------- test/AuthenticationRequestTest.php | 27 +++++++++++++++++ 2 files changed, 55 insertions(+), 20 deletions(-) diff --git a/lib/AuthenticationRequest.php b/lib/AuthenticationRequest.php index 7ec472f..2a52304 100644 --- a/lib/AuthenticationRequest.php +++ b/lib/AuthenticationRequest.php @@ -28,17 +28,21 @@ class AuthenticationRequest function __construct($jsonResponse, $api) { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->pending = $jsonResponse['pending']; - $this->granted = $jsonResponse['granted']; - $this->automated = $jsonResponse['automated']; - $this->reason_code = $jsonResponse['reason_code']; - $this->reason = $jsonResponse['reason']; - $this->terminal = new UserTerminal($jsonResponse['terminal'], $api); - $this->user = new User($jsonResponse['user'], $api); - $this->action = new Action($jsonResponse['action']); - $this->raw_response = $jsonResponse; + try { + $this->api = $api; + $this->id = $jsonResponse['id']; + $this->pending = $jsonResponse['pending']; + $this->granted = $jsonResponse['granted']; + $this->automated = $jsonResponse['automated']; + $this->reason_code = $jsonResponse['reason_code']; + $this->reason = $jsonResponse['reason']; + $this->terminal = new UserTerminal($jsonResponse['terminal'], $api); + $this->user = new User($jsonResponse['user'], $api); + $this->action = new Action($jsonResponse['action']); + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse authentication request from response: ' . $e->getMessage()); + } } public function refreshFromServer() @@ -59,15 +63,19 @@ public function grantWithOtp($otp, $kwargs = array()) private function update($jsonResponse) { - $this->pending = $jsonResponse['pending']; - $this->granted = $jsonResponse['granted']; - $this->automated = $jsonResponse['automated']; - $this->reason_code = $jsonResponse['reason_code']; - $this->reason = $jsonResponse['reason']; - $this->terminal->update($jsonResponse['terminal']); - $this->user->update($jsonResponse['user']); - $this->action->update($jsonResponse['action']); - $this->raw_respones = $jsonResponse; + try { + $this->pending = $jsonResponse['pending']; + $this->granted = $jsonResponse['granted']; + $this->automated = $jsonResponse['automated']; + $this->reason_code = $jsonResponse['reason_code']; + $this->reason = $jsonResponse['reason']; + $this->terminal->update($jsonResponse['terminal']); + $this->user->update($jsonResponse['user']); + $this->action->update($jsonResponse['action']); + $this->raw_respones = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse authentication request from response: ' . $e->getMessage()); + } } } diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php index 2138b99..38dc3d1 100644 --- a/test/AuthenticationRequestTest.php +++ b/test/AuthenticationRequestTest.php @@ -124,6 +124,33 @@ public function testGrantAuthenticationRequestPostsOtp(){ $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); $this->assertTrue($authRequest->automated == true, 'Authentication request should be automated'); } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse authentication request from response + */ + public function testAuthenticationRequestMissingKeyFails() + { + $authJson = $this->getAuthenticationRequestJson(); + unset($authJson['id']); + new AuthenticationRequest($authJson, $this->getToopherApi()); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse authentication request from response + */ + public function testAuthenticationRequestUpdateMissingKeyFails() + { + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"id":"1","granted":true,"automated":true,"reason_code":"1","reason":"some other reason","terminal":{"id":"1","name":"term name changed","requester_specified_id":"1","user":{"id":"1","name":"user changed", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user changed", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test changed"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $this->getAuthenticationRequest($toopher); + + $authRequest->refreshFromServer(); + } } ?> From e0c2244e5ae35618f092d75272193d124cf3db49 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 14:24:39 -0600 Subject: [PATCH 077/114] Throw ToopherRequestException when Pairing json is incomplete --- lib/Pairing.php | 30 ++++++++++++++++++++---------- test/PairingTest.php | 27 +++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 10 deletions(-) diff --git a/lib/Pairing.php b/lib/Pairing.php index dc9f0c8..4b07584 100644 --- a/lib/Pairing.php +++ b/lib/Pairing.php @@ -28,12 +28,17 @@ class Pairing function __construct($jsonResponse, $api) { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->enabled = $jsonResponse['enabled']; - $this->pending = $jsonResponse['pending']; - $this->user = new User($jsonResponse['user'], $api); - $this->raw_response = $jsonResponse; + try { + $this->api = $api; + $this->id = $jsonResponse['id']; + $this->enabled = $jsonResponse['enabled']; + $this->pending = $jsonResponse['pending']; + $this->user = new User($jsonResponse['user'], $api); + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse pairing from response: ' . $e->getMessage()); + } + } public function refreshFromServer() @@ -72,10 +77,15 @@ public function getQrCodeImage() private function update($jsonResponse) { - $this->enabled = $jsonResponse['enabled']; - $this->pending = $jsonResponse['pending']; - $this->user->update($jsonResponse['user']); - $this->raw_response = $jsonResponse; + try { + $this->enabled = $jsonResponse['enabled']; + $this->pending = $jsonResponse['pending']; + $this->user->update($jsonResponse['user']); + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse pairing from response: ' . $e->getMessage()); + } + } } diff --git a/test/PairingTest.php b/test/PairingTest.php index dd8d247..59258c0 100644 --- a/test/PairingTest.php +++ b/test/PairingTest.php @@ -117,6 +117,33 @@ public function testPairingGetQrCodeImageShouldGetFromCorrectUrl(){ $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/qr/pairings/1', "Last called url should be 'https://api.toopher.com/v1/qr/pairings/1'"); } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse pairing from response + */ + public function testPairingMissingKeyFails() + { + $pairingJson = $this->getPairingJson(); + unset($pairingJson['id']); + new Pairing($pairingJson, $this->getToopherApi()); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse pairing from response + */ + public function testPairingUpdateMissingKeyFails() + { + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1'); + $resp->appendBody('{"id":"1","pending":true,"user":{"id":"1","name":"user name changed", "toopher_authentication_enabled":false}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $pairing = $this->getPairing($toopher); + + $pairing->refreshFromServer(); + } } ?> From c75f12fc9fb984ae0f8b73e896bd2d09b35b8417 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 14:31:18 -0600 Subject: [PATCH 078/114] Throw ToopherRequestException when UserTerminal json is incomplete --- lib/UserTerminal.php | 28 ++++++++++++++++++---------- test/UserTerminalTest.php | 38 +++++++++++++++++++++++++++++++++++++- 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/lib/UserTerminal.php b/lib/UserTerminal.php index 14534b5..a061a27 100644 --- a/lib/UserTerminal.php +++ b/lib/UserTerminal.php @@ -28,12 +28,16 @@ class UserTerminal function __construct($jsonResponse, $api) { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->requester_specified_id = $jsonResponse['requester_specified_id']; - $this->user = new User($jsonResponse['user'], $api); - $this->raw_response = $jsonResponse; + try { + $this->api = $api; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->requester_specified_id = $jsonResponse['requester_specified_id']; + $this->user = new User($jsonResponse['user'], $api); + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse user terminal from response: ' . $e->getMessage()); + } } public function refreshFromServer() @@ -45,10 +49,14 @@ public function refreshFromServer() public function update($jsonResponse) { - $this->name = $jsonResponse['name']; - $this->requester_specified_id = $jsonResponse['requester_specified_id']; - $this->user->update($jsonResponse['user']); - $this->raw_response = $jsonResponse; + try { + $this->name = $jsonResponse['name']; + $this->requester_specified_id = $jsonResponse['requester_specified_id']; + $this->user->update($jsonResponse['user']); + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse user terminal from response: ' . $e->getMessage()); + } } } diff --git a/test/UserTerminalTest.php b/test/UserTerminalTest.php index 19ff5f8..1df7e69 100644 --- a/test/UserTerminalTest.php +++ b/test/UserTerminalTest.php @@ -27,6 +27,20 @@ protected function setUp() $this->mock = new HTTP_Request2_Adapter_Mock(); } + protected function getUserTerminalJson() + { + return [ + 'id' => '1', + 'name' => 'terminal name', + 'requester_specified_id' => 'requester specified id', + 'user' => [ + 'id' => '1', + 'name' => 'user name', + 'toopher_authentication_enabled' => true + ] + ]; + } + protected function getToopherApi($mock = NULL) { return new ToopherApi('key', 'secret', '', $mock); @@ -34,7 +48,7 @@ protected function getToopherApi($mock = NULL) protected function getUserTerminal($api) { - return new UserTerminal(['id' => '1', 'name' => 'terminal name', 'requester_specified_id' => 'requester specified id', 'user' => ['id' => '1','name' => 'user name', 'toopher_authentication_enabled' => true]], $api); + return new UserTerminal($this->getUserTerminalJson(), $api); } public function testUserTerminalCreatesUserTerminal(){ @@ -71,6 +85,28 @@ public function testUserTerminalUpdateChangesUserTerminal(){ $this->assertTrue($userTerminal->user->name == 'user name changed', 'User name was incorrect'); $this->assertTrue($userTerminal->user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse user terminal from response + */ + public function testUserTerminalMissingKeyFails() + { + $userTerminalJson = $this->getUserTerminalJson(); + unset($userTerminalJson['id']); + new UserTerminal($userTerminalJson, $this->getToopherApi()); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse user terminal from response + */ + public function testUserTerminalUpdateMissingKeyFails() + { + $userTerminal = $this->getUserTerminal($this->getToopherApi()); + $userTerminal->update(['id'=>'1', 'requester_specified_id'=>'requester specified id changed', 'user'=>['id'=>'1', 'name'=>'user name changed', 'toopher_authentication_enabled'=>false]]); + } + } ?> From a5fdcacc2bdac0d3192c3deabeafcb2e678bad2b Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 14:37:41 -0600 Subject: [PATCH 079/114] Throw ToopherRequestException when User json is incomplete --- lib/User.php | 25 +++++++++++++++++-------- test/UserTest.php | 22 ++++++++++++++++++++-- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/lib/User.php b/lib/User.php index 8f447a5..0d92731 100644 --- a/lib/User.php +++ b/lib/User.php @@ -28,11 +28,15 @@ class User function __construct($jsonResponse, $api) { - $this->api = $api; - $this->id = $jsonResponse['id']; - $this->name = $jsonResponse['name']; - $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; - $this->raw_response = $jsonResponse; + try { + $this->api = $api; + $this->id = $jsonResponse['id']; + $this->name = $jsonResponse['name']; + $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse user from response: ' . $e->getMessage()); + } } public function refreshFromServer() @@ -58,9 +62,14 @@ public function disableToopherAuthentication() public function update($jsonResponse) { - $this->name = $jsonResponse['name']; - $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; - $this->raw_response = $jsonResponse; + try { + $this->name = $jsonResponse['name']; + $this->toopher_authentication_enabled = $jsonResponse['toopher_authentication_enabled']; + $this->raw_response = $jsonResponse; + } catch (Exception $e) { + throw new ToopherRequestException('Could not parse user from response: ' . $e->getMessage()); + } + } } diff --git a/test/UserTest.php b/test/UserTest.php index 928d56f..22345d5 100644 --- a/test/UserTest.php +++ b/test/UserTest.php @@ -97,12 +97,30 @@ public function testUserDisableToopherAuthenticationPostsToCorrectUrl() public function testUserUpdateChangesUser() { - $toopher = $this->getToopherApi($this->mock); - $user = $this->getUser($toopher); + $user = $this->getUser($this->getToopherApi()); $user->update(['id' => '1', 'name' => 'user changed', 'toopher_authentication_enabled' => false]); $this->assertTrue($user->name == 'user changed', 'User name was incorrect'); $this->assertTrue($user->toopher_authentication_enabled == false, 'User should not be toopher_authentication_enabled'); } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse user from response + */ + public function testUserMissingKeyFails() + { + $user = new User(['name' => 'user', 'toopher_authentication_enabled' => true], $this->getToopherApi()); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Could not parse user from response + */ + public function testUserUpdateMissingKeyFails() + { + $user = $this->getUser($this->getToopherApi()); + $user->update(['id' => '1', 'toopher_authentication_enabled' => false]); + } } ?> From 776007bad1e8980e0b60cb149d869806bf76ee9c Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 14:40:19 -0600 Subject: [PATCH 080/114] Remove ToopherApi from Action tests --- test/ActionTest.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/test/ActionTest.php b/test/ActionTest.php index 3679ce1..73382b3 100644 --- a/test/ActionTest.php +++ b/test/ActionTest.php @@ -26,7 +26,6 @@ class ActionTests extends PHPUnit_Framework_TestCase { public function testActionCreatesAction() { - $toopher = new ToopherApi('key', 'secret'); $action = new Action(['id' => '1', 'name' => 'action']); $this->assertTrue($action->id == '1', 'Action id was incorrect'); $this->assertTrue($action->name == 'action', 'Action name was incorrect'); @@ -34,7 +33,6 @@ public function testActionCreatesAction() public function testActionUpdateChangesAction() { - $toopher = new ToopherApi('key', 'secret'); $action = new Action(['id' => '1', 'name' => 'action changed']); $action->update(['id'=>'1', 'name'=>'action changed']); $this->assertTrue($action->id == '1', 'Action id was incorrect'); @@ -47,7 +45,6 @@ public function testActionUpdateChangesAction() */ public function testActionMissingKeyFails() { - $toopher = new ToopherApi('key', 'secret'); $action = new Action(['name' => 'action changed']); } @@ -57,7 +54,6 @@ public function testActionMissingKeyFails() */ public function testActionUpdateMissingKeyFails() { - $toopher = new ToopherApi('key', 'secret'); $action = new Action(['id' => '1', 'name' => 'action changed']); $action->update(['id'=>'1']); } From 24400a218363be382f06ff888768a3bbfe1846cf Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 27 Feb 2015 15:17:02 -0600 Subject: [PATCH 081/114] Add tests for ToopherApi and reorder --- test/ToopherApiTest.php | 132 +++++++++++++++++++++++++++++----------- 1 file changed, 95 insertions(+), 37 deletions(-) diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 0bbbea2..19eb985 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -31,7 +31,7 @@ protected function setUp() $this->mock = new HTTP_Request2_Adapter_Mock(); } - protected function getToopherApi($mock) + protected function getToopherApi($mock = NULL) { return new ToopherApi('key', 'secret', '', $mock); } @@ -81,11 +81,31 @@ public function compareToDefaultUserTerminal($userTerminal) $this->assertTrue($userTerminal->user->toopher_authentication_enabled == true, 'toopher authentication should be enabled'); } - public function testCanCreateToopherApiWithArguments() { + /** + * @expectedException InvalidArgumentException + * @expectedExceptionMessage Toopher consumer key cannot be empty + */ + public function testEmptyKeyThrowsException() + { + $toopher = new ToopherApi('', 'secret'); + } + + /** + * @expectedException InvalidArgumentException + * @expectedExceptionMessage Toopher consumer secret cannot be empty + */ + public function testEmptySecretThrowsException() + { + $toopher = new ToopherApi('key', ''); + } + + public function testCanCreateToopherApiWithArguments() + { $toopher = new ToopherApi('key', 'secret'); } - public function testToopherVersionStringExists() { + public function testToopherVersionStringExists() + { $this->assertNotEmpty(ToopherApi::VERSION, 'no version string'); list($major, $minor, $patch) = explode('.', ToopherApi::VERSION); $this->assertGreaterThanOrEqual(1, (int)$major); @@ -93,7 +113,8 @@ public function testToopherVersionStringExists() { $this->assertGreaterThanOrEqual(0, (int)$patch); } - public function testPairReturnsPairing(){ + public function testPairReturnsPairing() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create'); $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -103,7 +124,8 @@ public function testPairReturnsPairing(){ $this->compareToDefaultPairing($pairing); } - public function testPairSmsReturnsPairing(){ + public function testPairSmsReturnsPairing() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create/sms'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -113,7 +135,8 @@ public function testPairSmsReturnsPairing(){ $this->compareToDefaultPairing($pairing); } - public function testPairQrReturnsPairing(){ + public function testPairQrReturnsPairing() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create/qr'); $resp->appendBody('{"id":"1", "enabled":true, "pending":false, "user":{"id":"1", "name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -123,7 +146,8 @@ public function testPairQrReturnsPairing(){ $this->compareToDefaultPairing($pairing); } - public function testAuthenticateWithPairingIdReturnsAuthenticationRequest(){ + public function testAuthenticateWithPairingIdReturnsAuthenticationRequest() + { $id = Uuid::uuid4()->toString(); $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); @@ -135,7 +159,8 @@ public function testAuthenticateWithPairingIdReturnsAuthenticationRequest(){ $this->compareToDefaultAuthenticationRequest($authRequest, $id); } - public function testAuthenticateWithUsernameReturnsAuthenticationRequest(){ + public function testAuthenticateWithUsernameReturnsAuthenticationRequest() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); @@ -146,7 +171,8 @@ public function testAuthenticateWithUsernameReturnsAuthenticationRequest(){ $this->compareToDefaultAuthenticationRequest($authRequest); } - public function testRawPost(){ + public function testRawPost() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); @@ -166,7 +192,8 @@ public function testRawPost(){ $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); } - public function testRawGet(){ + public function testRawGet() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); @@ -185,7 +212,8 @@ public function testRawGet(){ $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); } - public function testPairingsGetByIdReturnsPairing(){ + public function testPairingsGetByIdReturnsPairing() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1'); $resp->appendBody('{"id":"1","enabled":true, "pending":false, "user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -196,7 +224,8 @@ public function testPairingsGetByIdReturnsPairing(){ $this->compareToDefaultPairing($pairing); } - public function testAuthenticationRequestsGetByIdReturnsAuthenticationRequest(){ + public function testAuthenticationRequestsGetByIdReturnsAuthenticationRequest() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); $this->mock->addResponse($resp); @@ -207,7 +236,8 @@ public function testAuthenticationRequestsGetByIdReturnsAuthenticationRequest(){ $this->compareToDefaultAuthenticationRequest($authRequest); } - public function testUsersGetByIdReturnsUser(){ + public function testUsersGetByIdReturnsUser() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/1'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -218,18 +248,52 @@ public function testUsersGetByIdReturnsUser(){ $this->compareToDefaultUser($user); } - public function testUsersGetByNameReturnsUser(){ + public function testUsersGetByNameReturnsUser() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users'); $resp->appendBody('[{"id":"1","name":"user","toopher_authentication_enabled":true}]'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); - $user = $toopher->advanced->users->getByName('paired user'); + $user = $toopher->advanced->users->getByName('user'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->compareToDefaultUser($user); } - public function testUsersCreateReturnsUser(){ + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Multiple users with name + */ + public function testUsersGetByNameWithMultipleUsersRaisesToopherRequestException() + { + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users'); + $resp->appendBody('[{"id":"1","name":"user","toopher_authentication_enabled":true}, {"id":"2","name":"user","toopher_authentication_enabled":true}]'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $user = $toopher->advanced->users->getByName('user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultUser($user); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage No users with name + */ + public function testUsersGetByNameWithNoUsersRaisesToopherRequestException() + { + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users'); + $resp->appendBody('[]'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $user = $toopher->advanced->users->getByName('user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); + $this->compareToDefaultUser($user); + } + + public function testUsersCreateReturnsUser() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/create'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -240,7 +304,8 @@ public function testUsersCreateReturnsUser(){ $this->compareToDefaultUser($user); } - public function testUsersCreateWithExtrasReturnsUser(){ + public function testUsersCreateWithExtrasReturnsUser() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/users/create'); $resp->appendBody('{"id":"1","name":"user","toopher_authentication_enabled":true}'); $this->mock->addResponse($resp); @@ -251,7 +316,8 @@ public function testUsersCreateWithExtrasReturnsUser(){ $this->compareToDefaultUser($user); } - public function testUserTerminalsGetByIdReturnsUserTerminal(){ + public function testUserTerminalsGetByIdReturnsUserTerminal() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/1'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -262,7 +328,8 @@ public function testUserTerminalsGetByIdReturnsUserTerminal(){ $this->compareToDefaultUserTerminal($userTerminal); } - public function testUserTerminalCreateReturnsUserTerminal(){ + public function testUserTerminalCreateReturnsUserTerminal() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/create'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -273,7 +340,8 @@ public function testUserTerminalCreateReturnsUserTerminal(){ $this->compareToDefaultUserTerminal($userTerminal); } - public function testUserTerminalCreateWithExtrasReturnsUserTerminal(){ + public function testUserTerminalCreateWithExtrasReturnsUserTerminal() + { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/user_terminals/create'); $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); @@ -284,24 +352,12 @@ public function testUserTerminalCreateWithExtrasReturnsUserTerminal(){ $this->compareToDefaultUserTerminal($userTerminal); } - /** - * @expectedException InvalidArgumentException - */ - public function testEmptyKeyThrowsException() { - $toopher = new ToopherApi('', 'secret'); - } - - /** - * @expectedException InvalidArgumentException - */ - public function testEmptySecretThrowsException() { - $toopher = new ToopherApi('key', ''); - } - /** * @expectedException ToopherRequestException + * @expectedExceptionMessage Not a valid OAuth signed request */ - public function testToopherRequestException(){ + public function test401RaisesToopherRequestEception() + { $resp = new HTTP_Request2_Response('HTTP/1.1 401 Unauthorized', false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp->appendBody('{"error_code":401, "error_message":"Not a valid OAuth signed request"}'); $this->mock->addResponse($resp); @@ -312,7 +368,8 @@ public function testToopherRequestException(){ /** * @expectedException ToopherRequestException */ - public function test400WithEmptyBodyRaisesToopherRequestException(){ + public function test403WithEmptyBodyRaisesToopherRequestException() + { $resp = new HTTP_Request2_Response('HTTP/1.1 403 Forbidden', false, 'https://api.toopher.com/v1/authentication_requests/1'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); @@ -322,7 +379,8 @@ public function test400WithEmptyBodyRaisesToopherRequestException(){ /** * @expectedException ToopherRequestException */ - public function test400WithUnprintableBodyRaisesToopherRequestException(){ + public function test403WithUnprintableBodyRaisesToopherRequestException() + { $resp = new HTTP_Request2_Response('HTTP/1.1 403 Forbidden', false, 'https://api.toopher.com/v1/authentication_requests/1'); $resp->appendBody(sprintf("{'error_code':403, 'error_message':'%c'}", chr(5))); $this->mock->addResponse($resp); From b45917bd5e807b9c7ac41cefe6c8a22493bf658a Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 19 Mar 2015 14:01:54 -0500 Subject: [PATCH 082/114] Refactor validatePostback --- lib/ToopherIframe.php | 100 +++++++++++++++++++++---------------- test/ToopherIframeTest.php | 83 ++++++++++++++++-------------- 2 files changed, 102 insertions(+), 81 deletions(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 8c2fe8b..45f7a5d 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -29,6 +29,7 @@ class SignatureValidationError extends Exception class ToopherIframe { const VERSION = '2'; + const TTL = '300'; function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') { @@ -90,7 +91,7 @@ public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) $ttl = $kwargs['ttl']; unset($kwargs['ttl']); } else { - $ttl = 300; + $ttl = ToopherIframe::TTL; } $params = array( @@ -103,56 +104,69 @@ public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $params); } - public function validatePostback($parameters, $sessionToken, $ttl) + public function validateData($data, $requestToken = '', $kwargs = array()) { try { - $data = array(); - - foreach ($parameters as $key => $value) { - $data[$key] = $value[0]; - } - - $missingKeys = array(); - if (!array_key_exists('toopher_sig', $data)) { - $missingKeys[] = 'toopher_sig'; - } - if (!array_key_exists('timestamp', $data)) { - $missingKeys[] = 'timestamp'; - } - if (!array_key_exists('session_token', $data)) { - $missingKeys[] = 'session_token'; - } - if (count($missingKeys) > 0) { - $keys = implode(',', $missingKeys); - throw new SignatureValidationError('Missing required keys: ' . $keys); - } - - if ($data['session_token'] != $sessionToken) { - throw new SignatureValidationError('Session token does not match expected value'); - } + $this->checkForMissingKeys($data); + $this->verifySessionToken($data['session_token'], $requestToken); + $this->checkIfSignatureIsExpired($data['timestamp'], $kwargs); + $this->validateSignature($data); + return $data; + } catch (Exception $e) { + throw new SignatureValidationError ('Exception while validating toopher signature: ' . $e); + } + } - $maybeSignature = $data['toopher_sig']; - unset($data['toopher_sig']); - $signatureValid = false; - try { - $computedSignature = $this->signature($this->consumerSecret, $data); - $signatureValid = $maybeSignature == $computedSignature; - } catch (Exception $e) { - throw new SignatureValidationError('Error while calculating signature: ' . $e); + private function checkForMissingKeys($data) + { + $missingKeys = array(); + $requiredKeys = array('toopher_sig', 'timestamp', 'session_token'); + foreach ($requiredKeys as &$key) { + if (!array_key_exists($key, $data)) { + $missingKeys[] = $key; } + } + if (count($missingKeys) > 0) { + $keys = implode(',', $missingKeys); + throw new SignatureValidationError('Missing required keys: ' . $keys); + } + } - if (!$signatureValid) { - throw new SignatureValidationError('Computed signature does not match'); - } + private function verifySessionToken($sessionToken, $requestToken) + { + if ($sessionToken != $requestToken) { + throw new SignatureValidationError('Session token does not match expected value'); + } + } - $ttlValid = ($this->getUnixTimestamp() - $ttl) < $data['timestamp']; - if (!$ttlValid) { - throw new SignatureValidationError('TTL Expired'); - } + private function checkIfSignatureIsExpired($timestamp, $kwargs) + { + if (array_key_exists('ttl', $kwargs)) { + $ttl = $kwargs['ttl']; + unset($kwargs['ttl']); + } else { + $ttl = 300; + } + $ttlValid = ($this->getUnixTimestamp() - $ttl) < $timestamp; + if (!$ttlValid) { + throw new SignatureValidationError('TTL Expired'); + } + } - return $data; + private function validateSignature($data) + { + $maybeSignature = $data['toopher_sig']; + unset($data['toopher_sig']); + $signatureValid = false; + try { + $computedSignature = $this->signature($this->consumerSecret, $data); + $signatureValid = $maybeSignature == $computedSignature; } catch (Exception $e) { - throw new SignatureValidationError ('Exception while validating toopher signature: ' . $e); + throw new SignatureValidationError('Error while calculating signature: ' . $e); + } + + if (!$signatureValid) { + throw new SignatureValidationError('Computed signature does not match'); } } diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 099df34..da09879 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -100,17 +100,18 @@ public function testToopherIframeGetUserManagementUrlWithExtrasReturnsValidUrl() $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } - public function testToopherIframeValidatePostbackWithGoodSignatureIsSuccessful() + public function testToopherIframevalidateDataWithGoodSignatureIsSuccessful() { $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $data = array( - 'foo' => array('bar'), - 'timestamp' => array($this->getOauthTimestamp()), - 'session_token' => array('s9s7vsb'), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + 'foo' => 'bar', + 'timestamp' => $this->getOauthTimestamp(), + 'session_token' => 's9s7vsb', + 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' ); + $extras = array('ttl' => '5'); try { - $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + $this->toopherIframe->validateData($data, 's9s7vsb', $extras); } catch (Exception $e) { $this->fail('Valid signature, timestamp, and session token did not return validated data'); } @@ -120,92 +121,98 @@ public function testToopherIframeValidatePostbackWithGoodSignatureIsSuccessful() * @expectedException SignatureValidationError * @expectedExceptionMessage Computed signature does not match */ - public function testToopherIframeValidatePostbackWithBadSignatureFails() + public function testToopherIframevalidateDataWithBadSignatureFails() { $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $data = array( - 'foo' => array('bar'), - 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), - 'session_token' => array('s9s7vsb'), - 'toopher_sig' => array('invalid') + 'foo' => 'bar', + 'timestamp' => mktime(0, 16, 40, 1, 1, 1970), + 'session_token' => 's9s7vsb', + 'toopher_sig' => 'invalid' ); - $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + $extras = array('ttl' => '5'); + $this->toopherIframe->validateData($data, 's9s7vsb', $extras); } /** * @expectedException SignatureValidationError * @expectedExceptionMessage TTL Expired */ - public function testToopherIframeValidatePostbackWithExpiredSignatureFails() + public function testToopherIframevalidateDataWithExpiredSignatureFails() { $this->toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 2, 1, 1970)); $data = array( - 'foo' => array('bar'), - 'timestamp' => array($this->getOauthTimestamp()), - 'session_token' => array('s9s7vsb'), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + 'foo' => 'bar', + 'timestamp' => $this->getOauthTimestamp(), + 'session_token' => 's9s7vsb', + 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' ); - $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + $extras = array('ttl' => '5'); + $this->toopherIframe->validateData($data, 's9s7vsb', $extras); } /** * @expectedException SignatureValidationError * @expectedExceptionMessage Session token does not match expected value */ - public function testToopherIframeValidatePostbackWithInvalidSessionTokenFails() + public function testToopherIframevalidateDataWithInvalidSessionTokenFails() { $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); $data = array( - 'foo' => array('bar'), - 'timestamp' => array(mktime(0, 16, 40, 1, 1, 1970)), - 'session_token' => array('invalid token'), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + 'foo' => 'bar', + 'timestamp' => mktime(0, 16, 40, 1, 1, 1970), + 'session_token' => 'invalid token', + 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' ); - $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + $extras = array('ttl' => '5'); + $this->toopherIframe->validateData($data, 's9s7vsb', $extras); } /** * @expectedException SignatureValidationError * @expectedExceptionMessage Missing required keys: timestamp */ - public function testToopherIframeValidatePostbackMissingTimestampFails() + public function testToopherIframevalidateDataMissingTimestampFails() { $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); $data = array( - 'foo' => array('bar'), - 'session_token' => array('s9s7vsb'), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + 'foo' => 'bar', + 'session_token' => 's9s7vsb', + 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' ); - $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + $extras = array('ttl' => '5'); + $this->toopherIframe->validateData($data, 's9s7vsb', $extras); } /** * @expectedException SignatureValidationError * @expectedExceptionMessage Missing required keys: toopher_sig */ - public function testToopherIframeValidatePostbackMissingSignatureFails() + public function testToopherIframevalidateDataMissingSignatureFails() { $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); $data = array( - 'foo' => array('bar'), - 'session_token' => array('s9s7vsb'), + 'foo' => 'bar', + 'session_token' => 's9s7vsb', 'timestamp' => mktime(0, 16, 40, 1, 1, 1970) ); - $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + $extras = array('ttl' => '5'); + $this->toopherIframe->validateData($data, 's9s7vsb', $extras); } /** * @expectedException SignatureValidationError * @expectedExceptionMessage Missing required keys: session_token */ - public function testToopherIframeValidatePostbackMissingSessionTokenFails() + public function testToopherIframevalidateDataMissingSessionTokenFails() { $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); $data = array( - 'foo' => array('bar'), - 'timestamp' => array($this->getOauthTimestamp()), - 'toopher_sig' => array('6d2c7GlQssGmeYYGpcf+V/kirOI=') + 'foo' => 'bar', + 'timestamp' => $this->getOauthTimestamp(), + 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' ); - $this->toopherIframe->validatePostback($data, 's9s7vsb', 5); + $extras = array('ttl' => '5'); + $this->toopherIframe->validateData($data, 's9s7vsb', $extras); } } From 5396084eef50e03e7d0dd56f82a3e874b0ca65e3 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Mar 2015 10:56:57 -0500 Subject: [PATCH 083/114] Reorder getOauthSignedUrl methods --- lib/ToopherIframe.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 45f7a5d..c306a89 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -188,14 +188,6 @@ private function getOauthSignedUrl($url, $queryParams) return $this->buildUrl($url, $queryParams, $oauthParams); } - private function encodeParamsForSignature($params) - { - foreach ($params as $key => $value) { - $params[$key] = oauth_urlencode($value); - } - return $params; - } - private function getOauthParams() { $oauthParams = array( @@ -217,6 +209,14 @@ private function getOauthParams() return $oauthParams; } + private function encodeParamsForSignature($params) + { + foreach ($params as $key => $value) { + $params[$key] = oauth_urlencode($value); + } + return $params; + } + private function buildUrl($url, $queryParams, $oauthParams) { $query = http_build_query($queryParams); From 89d66e023583a7baae160525d4b61b6d4a3c79f1 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Mar 2015 11:27:53 -0500 Subject: [PATCH 084/114] Replace validatePostback with processPostback --- lib/ToopherIframe.php | 85 ++++++++++++- test/ToopherIframeTest.php | 238 +++++++++++++++++++++++++------------ 2 files changed, 241 insertions(+), 82 deletions(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index c306a89..f1fc279 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -104,7 +104,29 @@ public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $params); } - public function validateData($data, $requestToken = '', $kwargs = array()) + public function processPostback($data, $requestToken = '', $kwargs = array()) + { + parse_str($data["toopher_iframe_data"], $toopherData); + + if (array_key_exists('error_code', $toopherData)) { + throw new ToopherRequestException($toopherData['error_message'], $toopherData['error_code']); + } else { + $this->validateData($toopherData, $requestToken, $kwargs); + $api = new ToopherApi($this->consumerKey, $this->consumerSecret); + $resourceType = $toopherData['resource_type']; + if ($resourceType == 'authentication_request') { + return new AuthenticationRequest($this->createAuthenticationRequestArray($toopherData), $api); + } else if ($resourceType == 'pairing') { + return new Pairing($this->createPairingArray($toopherData), $api); + } else if ($resourceType == 'requester_user') { + return new User($this->createUserArray($toopherData), $api); + } else { + throw new ToopherRequestException('The postback resource type is not valid: ' . $resourceType); + } + } + } + + private function validateData($data, $requestToken, $kwargs) { try { $this->checkForMissingKeys($data); @@ -134,7 +156,7 @@ private function checkForMissingKeys($data) private function verifySessionToken($sessionToken, $requestToken) { - if ($sessionToken != $requestToken) { + if ($requestToken != '' && $sessionToken != $requestToken) { throw new SignatureValidationError('Session token does not match expected value'); } } @@ -172,13 +194,66 @@ private function validateSignature($data) private function signature($secret, $parameters) { - $oauthConsumer = new HTTP_OAuth_Consumer($this->consumerKey, $this->consumerSecret); - $params = $oauthConsumer->buildHttpQuery($parameters); - $key = mb_convert_encoding($secret, 'UTF-8'); + ksort($parameters); + $params = http_build_query($parameters); $sig = hash_hmac('sha1', $params, $secret, true); return base64_encode($sig); } + private function createAuthenticationRequestArray($data) + { + return array( + 'id' => $data['id'], + 'pending'=>$data['pending'] == 'true', + 'granted'=>$data['granted'] == 'true', + 'automated'=>$data['automated'] == 'true', + 'reason'=>$data['reason'], + 'reason_code'=>$data['reason_code'], + 'terminal'=>array( + 'id'=>$data['terminal_id'], + 'name'=>$data['terminal_name'], + 'requester_specified_id'=>$data['terminal_requester_specified_id'], + 'user'=>array( + 'id'=>$data['pairing_user_id'], + 'name'=>$data['user_name'], + 'toopher_authentication_enabled'=>$data['user_toopher_authentication_enabled'] == 'true' + ) + ), + 'user'=>array( + 'id'=>$data['pairing_user_id'], + 'name'=>$data['user_name'], + 'toopher_authentication_enabled'=>$data['user_toopher_authentication_enabled'] == 'true' + ), + 'action'=>array( + 'id'=>$data['action_id'], + 'name'=>$data['action_name'] + ) + ); + } + + private function createPairingArray($data) + { + return array( + 'id' => $data['id'], + 'enabled' => $data['enabled'] == 'true', + 'pending' => $data['pending'] == 'true', + 'user' => array( + 'id' => $data['pairing_user_id'], + 'name' => $data['user_name'], + 'toopher_authentication_enabled' => $data['user_toopher_authentication_enabled'] + ) + ); + } + + private function createUserArray($data) + { + return array( + 'id' => $data['id'], + 'name' => $data['name'], + 'toopher_authentication_enabled' => $data['toopher_authentication_enabled'] == 'true' + ); + } + private function getOauthSignedUrl($url, $queryParams) { $oauthParams = $this->getOauthParams(); diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index da09879..afd2419 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -31,6 +31,64 @@ class ToopherIframeTests extends PHPUnit_Framework_TestCase { const IFRAME_SECRET = 'hijklmnop'; const REQUEST_TOKEN = 's9s7vsb'; + protected function getAuthenticationRequestData() + { + return array( + 'id' => '1', + 'pending' => 'false', + 'granted' => 'true', + 'automated' => 'false', + 'reason_code' => '100', + 'reason' => 'it is a test', + 'terminal_id' => '1', + 'terminal_name' => 'terminal name', + 'terminal_requester_specified_id' => 'requester specified id', + 'pairing_user_id' => '1', + 'user_name' => 'user name', + 'user_toopher_authentication_enabled' => 'true', + 'action_id' => '1', + 'action_name' => 'action name', + 'toopher_sig' => 's+fYUtChrNMjES5Xa+755H7BQKE=', + 'session_token' => $this->getRequestToken(), + 'timestamp' => '1000', + 'resource_type' => 'authentication_request' + ); + } + + protected function getPairingData() + { + return array( + 'id' => '1', + 'enabled' => 'true', + 'pending' => 'false', + 'pairing_user_id' => '1', + 'user_name' => 'user name', + 'user_toopher_authentication_enabled' => 'true', + 'toopher_sig' => 'ucwKhkPpN4VxNbx3dMypWzi4tBg=', + 'session_token' => $this->getRequestToken(), + 'timestamp' => '1000', + 'resource_type' => 'pairing' + ); + } + + protected function getUserData() + { + return array( + 'id' => '1', + 'name' => 'user name', + 'toopher_authentication_enabled' => 'true', + 'toopher_sig' => 'RszgG9QE1rF9t7DVTGg+1I25yHM=', + 'session_token' => $this->getRequestToken(), + 'timestamp' => '1000', + 'resource_type' => 'requester_user' + ); + } + + protected function getUrlencodedData($data) + { + return array('toopher_iframe_data'=>utf8_encode(http_build_query($data))); + } + public static function getOauthTimestamp() { date_default_timezone_set('UTC'); @@ -60,11 +118,11 @@ public static function getRequestToken() protected function setUp() { $this->toopherIframe = new ToopherIframe($this->getIframeKey(), $this->getIframeSecret(), 'https://api.toopher.test/v1/'); + $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); } public function testToopherIframeGetAuthenticationUrlReturnsValidUrl() { - $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D'; $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); @@ -74,7 +132,6 @@ public function testToopherIframeGetAuthenticationUrlReturnsValidUrl() public function testToopherIframeGetAuthenticationUrlWithExtrasReturnsValidUrl() { $extras = array('allow_inline_pairing' => 'false'); - $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D'; $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'None', $extras); @@ -83,7 +140,6 @@ public function testToopherIframeGetAuthenticationUrlWithExtrasReturnsValidUrl() public function testToopherIframeGetUserManagementUrlReturnsValidUrl() { - $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D'; $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com'); @@ -93,126 +149,154 @@ public function testToopherIframeGetUserManagementUrlReturnsValidUrl() public function testToopherIframeGetUserManagementUrlWithExtrasReturnsValidUrl() { $extras = array('ttl' => '100'); - $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D'; $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com', $extras); $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } - public function testToopherIframevalidateDataWithGoodSignatureIsSuccessful() + public function testProcessPostbackReturnsAuthenticationRequest() + { + $authData = $this->getUrlencodedData($this->getAuthenticationRequestData()); + $authRequest = $this->toopherIframe->processPostback($authData, $this->getRequestToken()); + $this->assertTrue($authRequest->id == '1', 'Authentication request id was incorrect'); + $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); + $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); + $this->assertTrue($authRequest->automated == false, 'Authentication request should not be automated'); + $this->assertTrue($authRequest->reason_code == '100', 'Authentication request reason code was incorrect'); + $this->assertTrue($authRequest->reason == 'it is a test', 'Authentication request reason was incorrect'); + $this->assertTrue($authRequest->terminal->id == '1', 'Terminal id was incorrect'); + $this->assertTrue($authRequest->terminal->name == 'terminal name', 'Terminal name was incorrect'); + $this->assertTrue($authRequest->terminal->requester_specified_id == 'requester specified id', 'Terminal requester specified id was incorrect'); + $this->assertTrue($authRequest->user->id == '1', 'User id was incorrect'); + $this->assertTrue($authRequest->user->name == 'user name', 'User name was incorrect'); + $this->assertTrue($authRequest->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + $this->assertTrue($authRequest->action->id == '1', 'Action id was incorrect'); + $this->assertTrue($authRequest->action->name == 'action name', 'Action name was incorrect'); + } + + public function testProcessPostbackReturnsPairing() + { + $pairingData = $this->getUrlencodedData($this->getPairingData()); + $pairing = $this->toopherIframe->processPostback($pairingData, $this->getRequestToken()); + $this->assertTrue($pairing->id == '1', 'Pairing id was incorrect'); + $this->assertTrue($pairing->enabled == true, 'Pairing should be enabled'); + $this->assertTrue($pairing->pending == false, 'Pairing should not be pending'); + $this->assertTrue($pairing->user->id == '1', 'User id was incorrect'); + $this->assertTrue($pairing->user->name == 'user name', 'User name was incorrect'); + $this->assertTrue($pairing->user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + } + + public function testProcessPostbackReturnsUser() + { + $userData = $this->getUrlencodedData($this->getUserData()); + $user = $this->toopherIframe->processPostback($userData, $this->getRequestToken()); + $this->assertTrue($user->id == '1', 'User id was incorrect'); + $this->assertTrue($user->name == 'user name', 'User name was incorrect'); + $this->assertTrue($user->toopher_authentication_enabled == true, 'User should be toopher_authentication_enabled'); + } + + public function testProcessPostbackWithExtrasReturnsAuthenticationRequest() { - $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => 'bar', - 'timestamp' => $this->getOauthTimestamp(), - 'session_token' => 's9s7vsb', - 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' - ); $extras = array('ttl' => '5'); - try { - $this->toopherIframe->validateData($data, 's9s7vsb', $extras); - } catch (Exception $e) { - $this->fail('Valid signature, timestamp, and session token did not return validated data'); - } + $authRequest = $this->toopherIframe->processPostback($this->getUrlencodedData($this->getAuthenticationRequestData()), $this->getRequestToken(), $extras); + $this->assertTrue(is_a($authRequest, 'AuthenticationRequest'), 'AuthenticationRequest should be returned'); + } + + public function testProcessPostbackWithoutRequestTokenReturnsAuthenticationRequest() + { + $authRequest = $this->toopherIframe->processPostback($this->getUrlencodedData($this->getAuthenticationRequestData())); + $this->assertTrue(is_a($authRequest, 'AuthenticationRequest'), 'AuthenticationRequest should be returned'); } /** * @expectedException SignatureValidationError * @expectedExceptionMessage Computed signature does not match */ - public function testToopherIframevalidateDataWithBadSignatureFails() + public function testProcessPostbackWithBadSignatureRaisesError() { - $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => 'bar', - 'timestamp' => mktime(0, 16, 40, 1, 1, 1970), - 'session_token' => 's9s7vsb', - 'toopher_sig' => 'invalid' - ); - $extras = array('ttl' => '5'); - $this->toopherIframe->validateData($data, 's9s7vsb', $extras); + $authData = $this->getAuthenticationRequestData(); + $authData['toopher_sig'] = 'invalid'; + $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } /** * @expectedException SignatureValidationError * @expectedExceptionMessage TTL Expired */ - public function testToopherIframevalidateDataWithExpiredSignatureFails() + public function testProcessPostbackWithExpiredSignatureRaisesError() { $this->toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 2, 1, 1970)); - $data = array( - 'foo' => 'bar', - 'timestamp' => $this->getOauthTimestamp(), - 'session_token' => 's9s7vsb', - 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' - ); - $extras = array('ttl' => '5'); - $this->toopherIframe->validateData($data, 's9s7vsb', $extras); + $authData = $this->getAuthenticationRequestData(); + $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } /** * @expectedException SignatureValidationError - * @expectedExceptionMessage Session token does not match expected value + * @expectedExceptionMessage Missing required keys: toopher_sig */ - public function testToopherIframevalidateDataWithInvalidSessionTokenFails() - { - $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => 'bar', - 'timestamp' => mktime(0, 16, 40, 1, 1, 1970), - 'session_token' => 'invalid token', - 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' - ); - $extras = array('ttl' => '5'); - $this->toopherIframe->validateData($data, 's9s7vsb', $extras); + public function testProcessPostbackMissingSignatureRaisesError() + { + $authData = $this->getAuthenticationRequestData(); + unset($authData['toopher_sig']); + $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } /** * @expectedException SignatureValidationError * @expectedExceptionMessage Missing required keys: timestamp */ - public function testToopherIframevalidateDataMissingTimestampFails() + public function testProcessPostbackMissingTimestampRaisesError() { - $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => 'bar', - 'session_token' => 's9s7vsb', - 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' - ); - $extras = array('ttl' => '5'); - $this->toopherIframe->validateData($data, 's9s7vsb', $extras); + $authData = $this->getAuthenticationRequestData(); + unset($authData['timestamp']); + $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } /** * @expectedException SignatureValidationError - * @expectedExceptionMessage Missing required keys: toopher_sig + * @expectedExceptionMessage Missing required keys: session_token */ - public function testToopherIframevalidateDataMissingSignatureFails() + public function testProcessPostbackMissingSessionTokenRaisesError() { - $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => 'bar', - 'session_token' => 's9s7vsb', - 'timestamp' => mktime(0, 16, 40, 1, 1, 1970) - ); - $extras = array('ttl' => '5'); - $this->toopherIframe->validateData($data, 's9s7vsb', $extras); + $authData = $this->getAuthenticationRequestData(); + unset($authData['session_token']); + $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } /** * @expectedException SignatureValidationError - * @expectedExceptionMessage Missing required keys: session_token + * @expectedExceptionMessage Session token does not match expected value */ - public function testToopherIframevalidateDataMissingSessionTokenFails() + public function testProcessPostbackWithInvalidSessionTokenRaisesError() { - $this->toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); - $data = array( - 'foo' => 'bar', - 'timestamp' => $this->getOauthTimestamp(), - 'toopher_sig' => '6d2c7GlQssGmeYYGpcf+V/kirOI=' - ); - $extras = array('ttl' => '5'); - $this->toopherIframe->validateData($data, 's9s7vsb', $extras); + $authData = $this->getAuthenticationRequestData(); + $authData['session_token'] = 'invalid'; + $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage The postback resource type is not valid: invalid + */ + public function testProcessPostbackWithInvalidResourceTypeRaisesError() + { + $authData = $this->getAuthenticationRequestData(); + $authData['resource_type'] = 'invalid'; + $authData['toopher_sig'] = 'xEY+oOtJcdMsmTLp6eOy9isO/xQ='; + $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage The specified user has disabled Toopher authentication + */ + public function testProcessPostbackWithErrorCodeRaisesError() + { + $authData = $this->getAuthenticationRequestData(); + $authData['error_code'] = '704'; + $authData['error_message'] = 'The specified user has disabled Toopher authentication'; + $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } + } From 6a097750cdfd780e5677909672945a2f4fd057f3 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Mar 2015 12:18:56 -0500 Subject: [PATCH 085/114] Add expires and iframe version to query params in getOauthSignedUrl --- lib/ToopherIframe.php | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index f1fc279..8b9f470 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -72,17 +72,14 @@ public function getAuthenticationUrl($username, $resetEmail, $requestToken = 'No } $params = array( - 'v' => ToopherIframe::VERSION, 'username' => $username, 'reset_email' => $resetEmail, 'action_name' => $actionName, 'session_token' => $requestToken, 'requester_metadata' => $requesterMetadata, - 'expires' => $this->getUnixTimestamp() + $ttl ); $params = array_merge($params, $kwargs); - - return $this->getOauthSignedUrl($this->baseUrl . 'web/authenticate', $params); + return $this->getOauthSignedUrl($this->baseUrl . 'web/authenticate', $ttl, $params); } public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) @@ -95,13 +92,11 @@ public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) } $params = array( - 'v' => ToopherIframe::VERSION, 'username' => $username, 'reset_email' => $resetEmail, - 'expires' => $this->getUnixTimestamp() + $ttl ); $params = array_merge($params, $kwargs); - return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $params); + return $this->getOauthSignedUrl($this->baseUrl . 'web/manage_user', $ttl, $params); } public function processPostback($data, $requestToken = '', $kwargs = array()) @@ -254,8 +249,11 @@ private function createUserArray($data) ); } - private function getOauthSignedUrl($url, $queryParams) + private function getOauthSignedUrl($url, $ttl, $queryParams) { + $queryParams['v'] = ToopherIframe::VERSION; + $queryParams['expires'] = $this->getUnixTimestamp() + $ttl; + $oauthParams = $this->getOauthParams(); $encodedParams = $this->encodeParamsForSignature(array_merge($queryParams, $oauthParams)); $signature = $this->oauthConsumer->generateSignature('GET', $url, $encodedParams); From defe9462cb795fe34a613335bc8b3c9ad71164bd Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Mar 2015 12:19:54 -0500 Subject: [PATCH 086/114] Refactor getAuthenticationUrl and add tests --- lib/ToopherIframe.php | 4 ++-- test/ToopherIframeTest.php | 27 ++++++++++++++++++++------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 8b9f470..8d68c1f 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -62,13 +62,13 @@ private function getUnixTimestamp() } } - public function getAuthenticationUrl($username, $resetEmail, $requestToken = 'None', $actionName = 'Log In', $requesterMetadata = 'None', $kwargs = array()) + public function getAuthenticationUrl($username, $resetEmail = '', $requestToken = '', $actionName = 'Log In', $requesterMetadata = '', $kwargs = array()) { if (array_key_exists('ttl', $kwargs)) { $ttl = $kwargs['ttl']; unset($kwargs['ttl']); } else { - $ttl = 300; + $ttl = ToopherIframe::TTL; } $params = array( diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index afd2419..0eb56c7 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -121,20 +121,33 @@ protected function setUp() $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); } - public function testToopherIframeGetAuthenticationUrlReturnsValidUrl() + public function testGetAuthenticationUrlOnlyUsernameReturnsValidUrl() { $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=Log+In&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D'; - $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken()); + $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?username=jdoe&reset_email=&action_name=Log+In&session_token=&requester_metadata=&v=2&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=NkaWUjEPRLwgsQMEJGsIQEpyRT4%3D'; + $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe'); $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } - public function testToopherIframeGetAuthenticationUrlWithExtrasReturnsValidUrl() + public function testGetAuthenticationUrlWithOptionalArgsReturnsValidUrl() { - $extras = array('allow_inline_pairing' => 'false'); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=None&expires=1300&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=W%2F2dcdsVc7YgdSCZuEo8ViHLlOo%3D'; - $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'None', $extras); + $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=metadata&v=2&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=2TydgMnUwWoiwfpljKpSaFg0Luo%3D'; + $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'metadata'); + $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); + } + + public function testGetAuthenticationUrlWithOptionalArgsAndExtrasReturnsValidUrl() + { + $extras = array( + 'allow_inline_pairing' => 'false', + 'automation_allowed' => 'false', + 'challenge_required' => 'true', + 'ttl' => '100' + ); + $this->toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = 'https://api.toopher.test/v1/web/authenticate?username=jdoe&reset_email=jdoe%40example.com&action_name=it+is+a+test&session_token=s9s7vsb&requester_metadata=metadata&allow_inline_pairing=false&automation_allowed=false&challenge_required=true&v=2&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=61dqeQNPFxNy8PyEFB9e5UfgN8s%3D'; + $authenticationUrl = $this->toopherIframe->getAuthenticationUrl('jdoe', 'jdoe@example.com', $this->getRequestToken(), 'it is a test', 'metadata', $extras); $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } From 13f0c1c05f6120df10a71f24ef2a38e6e69af8b0 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Mar 2015 12:26:11 -0500 Subject: [PATCH 087/114] Refactor getUserManagementUrl and add tests --- lib/ToopherIframe.php | 2 +- test/ToopherIframeTest.php | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 8d68c1f..d38ff1a 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -82,7 +82,7 @@ public function getAuthenticationUrl($username, $resetEmail = '', $requestToken return $this->getOauthSignedUrl($this->baseUrl . 'web/authenticate', $ttl, $params); } - public function getUserManagementUrl($username, $resetEmail, $kwargs = array()) + public function getUserManagementUrl($username, $resetEmail = '', $kwargs = array()) { if (array_key_exists('ttl', $kwargs)) { $ttl = $kwargs['ttl']; diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 0eb56c7..2d47902 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -151,19 +151,27 @@ public function testGetAuthenticationUrlWithOptionalArgsAndExtrasReturnsValidUrl $this->assertTrue($authenticationUrl == $expectedUrl, 'Authentication url was incorrect'); } - public function testToopherIframeGetUserManagementUrlReturnsValidUrl() + public function testGetUserManagementUrlOnlyUsernameReturnsValidUrl() { $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D'; + $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?username=jdoe&reset_email=&v=2&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=SA7CAUj%2B5QcGO%2BMmdPv9ubbaozk%3D'; + $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe'); + $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); + } + + public function testToopherIframeGetUserManagementUrlWithEmailReturnsValidUrl() + { + $this->toopherIframe->setNonceOverride($this->getOauthNonce()); + $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?username=jdoe&reset_email=jdoe%40example.com&v=2&expires=1300&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D'; $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com'); $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } - public function testToopherIframeGetUserManagementUrlWithExtrasReturnsValidUrl() + public function testToopherIframeGetUserManagementUrlWithEmailAndExtrasReturnsValidUrl() { $extras = array('ttl' => '100'); $this->toopherIframe->setNonceOverride($this->getOauthNonce()); - $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D'; + $expectedUrl = 'https://api.toopher.test/v1/web/manage_user?username=jdoe&reset_email=jdoe%40example.com&v=2&expires=1100&oauth_consumer_key=abcdefg&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_nonce=12345678&oauth_timestamp=1000&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D'; $userManagementUrl = $this->toopherIframe->getUserManagementUrl('jdoe', 'jdoe@example.com', $extras); $this->assertTrue($userManagementUrl == $expectedUrl, 'User management url was incorrect'); } From 061cb856e943ebcff40d6d27183876c575267e7c Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Mar 2015 14:22:23 -0500 Subject: [PATCH 088/114] Add ToopherIframe.isAuthenticationGranted and tests --- lib/ToopherIframe.php | 19 +++++++++++++ test/ToopherIframeTest.php | 56 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index d38ff1a..50758b8 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -121,6 +121,25 @@ public function processPostback($data, $requestToken = '', $kwargs = array()) } } + public function isAuthenticationGranted($data, $requestToken = '', $kwargs = array()) + { + try { + $authenticationRequest = $this->processPostback($data, $requestToken, $kwargs); + if (is_a($authenticationRequest, 'AuthenticationRequest')) { + return !$authenticationRequest->pending && $authenticationRequest->granted; + } else { + return false; + } + } catch (Exception $e) { + if ($e->getCode() == 704) { + error_log($e->getMessage()); + return true; + } else { + return false; + } + } + } + private function validateData($data, $requestToken, $kwargs) { try { diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 2d47902..0286d10 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -320,4 +320,60 @@ public function testProcessPostbackWithErrorCodeRaisesError() $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } + public function testIsAuthenticationGrantedWithAuthenticationRequestGrantedReturnsTrue() + { + $this->assertTrue($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($this->getAuthenticationRequestData()), $this->getRequestToken())); + } + + public function testIsAuthenticationGrantedWithAuthenticationRequestGrantedAndExtrasReturnsTrue() + { + $extras = array('ttl' => '100'); + $this->assertTrue($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($this->getAuthenticationRequestData()), $this->getRequestToken(), $extras)); + } + + public function testIsAuthenticationGrantedWithAuthenticationRequestGrantedWithoutRequestTokenReturnsTrue() + { + $this->assertTrue($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($this->getAuthenticationRequestData()))); + } + + public function testIsAuthenticationGrantedWithAuthenticationRequestNotGrantedReturnsFalse() + { + $authData = $this->getAuthenticationRequestData(); + $authData['granted'] = 'false'; + $authData['toopher_sig'] = 'nADNKdly9zA2IpczD6gvDumM48I='; + $this->assertFalse($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($authData), $this->getRequestToken())); + } + + public function testIsAuthenticationGrantedWithPairingReturnsFalse() + { + $this->assertFalse($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($this->getPairingData(), $this->getRequestToken()))); + } + + public function testIsAuthenticationGrantedWithUserReturnsFalse() + { + $this->assertFalse($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($this->getUserData(), $this->getRequestToken()))); + } + + public function testIsAuthenticationGrantedWithSignatureValidationErrorReturnsFalse() + { + $authData = $this->getAuthenticationRequestData(); + unset($authData['id']); + $this->assertFalse($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($authData), $this->getRequestToken())); + } + + public function testIsAuthenticationGrantedWithToopherRequestExceptionReturnsFalse() + { + $authData = $this->getAuthenticationRequestData(); + $authData['resource_type'] = 'invalid'; + $authData['toopher_sig'] = 'xEY+oOtJcdMsmTLp6eOy9isO/xQ='; + $this->assertFalse($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($authData), $this->getRequestToken())); + } + + public function testIsAuthenticationGrantedWithErrorCode704ReturnsTrue() + { + $authData = $this->getAuthenticationRequestData(); + $authData['error_code'] = '704'; + $authData['error_message'] = 'The specified user has disabled Toopher authentication'; + $this->assertTrue($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($authData))); + } } From fec0d5d243a4f5d03f926ac9c5fe9b7bbc81b1cf Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 20 Mar 2015 16:58:32 -0500 Subject: [PATCH 089/114] Improve tests for ToopherApi.authenticate --- test/ToopherApiTest.php | 43 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 19eb985..6fed8d7 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -154,11 +154,31 @@ public function testAuthenticateWithPairingIdReturnsAuthenticationRequest() $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->authenticate($id, 'term name'); + $authRequest = $toopher->authenticate($id); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultAuthenticationRequest($authRequest, $id); } + public function testAuthenticateWithPairingIdOptionalArgsAndExtrasReturnsAuthenticationRequest() + { + $extras = array('foo' => 'bar'); + $id = Uuid::uuid4()->toString(); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"' . $id . '","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->authenticate($id, 'term name', '1', 'it is a test', $extras); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($parameters['pairing_id'] == $id, sprintf("Last called parameters should include key-value pair: 'pairing_id'=> %s", $id)); + $this->assertTrue($parameters['action_name'] == 'it is a test', "Last called parameters should include key-value pair: 'action_name'=>'it is a test'"); + $this->assertTrue($parameters['terminal_name'] == 'term name', "Last called parameters should include key-value pair: 'terminal_name'=>'term name'"); + $this->assertTrue($parameters['requester_specified_terminal_id'] == '1', "Last called parameters should include key-value pair: 'requester_specified_terminal_id'=>'1'"); + $this->assertTrue($parameters['foo'] == 'bar', "Last called parameters should include key-value pair: 'foo'=>'bar'"); + $this->compareToDefaultAuthenticationRequest($authRequest, $id); + } + public function testAuthenticateWithUsernameReturnsAuthenticationRequest() { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); @@ -166,8 +186,27 @@ public function testAuthenticateWithUsernameReturnsAuthenticationRequest() $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); - $authRequest = $toopher->authenticate('user', 'term name', '1'); + $authRequest = $toopher->authenticate('user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->compareToDefaultAuthenticationRequest($authRequest); + } + + public function testAuthentiateWithUsernameOptionalArgsAndExtrasReturnsAuthenticationRequest() + { + $extras = array('foo' => 'bar'); + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); + $resp->appendBody('{"id":"1","pending":false,"granted":true,"automated":true,"reason_code":"1","reason":"some reason","terminal":{"id":"1","name":"term name","requester_specified_id":"1","user":{"id":"1","name":"user", "toopher_authentication_enabled":true}},"user":{"id":"1","name":"user", "toopher_authentication_enabled":true},"action":{"id":"1","name":"test"}}'); + $this->mock->addResponse($resp); + + $toopher = $this->getToopherApi($this->mock); + $authRequest = $toopher->authenticate('user', 'term name', '1', 'it is a test', $extras); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($parameters['user_name'] == 'user', "Last called parameters should include key-value pair: 'user_name'=>'user'"); + $this->assertTrue($parameters['action_name'] == 'it is a test', "Last called parameters should include key-value pair: 'action_name'=>'it is a test'"); + $this->assertTrue($parameters['terminal_name'] == 'term name', "Last called parameters should include key-value pair: 'terminal_name'=>'term name'"); + $this->assertTrue($parameters['requester_specified_terminal_id'] == '1', "Last called parameters should include key-value pair: 'requester_specified_terminal_id'=>'1'"); + $this->assertTrue($parameters['foo'] == 'bar', "Last called parameters should include key-value pair: 'foo'=>'bar'"); $this->compareToDefaultAuthenticationRequest($authRequest); } From 88416eb6b044d2f8d77b87831f58edac1b3233a6 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 23 Mar 2015 17:41:10 -0500 Subject: [PATCH 090/114] Add js for ToopherIframe --- assets/js/toopher-web.js | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 assets/js/toopher-web.js diff --git a/assets/js/toopher-web.js b/assets/js/toopher-web.js new file mode 100644 index 0000000..deb2209 --- /dev/null +++ b/assets/js/toopher-web.js @@ -0,0 +1,43 @@ +(function(window, $){ + var postToUrl = function (path, params, method){ + method = method || 'POST'; + var form = $('
').attr('method', method).attr('action', path); + for (var key in params){ + if (params.hasOwnProperty(key)){ + var hiddenField = $('').attr('type', 'hidden').attr('name', key).attr('value', params[key]); + form.append(hiddenField); + } + } + $('body').append(form); + form.submit(); + } + + var handleMessage = function(e){ + var msgData = JSON.parse(e.data); + if (msgData.status === 'toopher-api-complete'){ + var iframe = $('#toopher_iframe'); + var frameworkPostArgsJSON = iframe.attr('framework_post_args'); + var frameworkPostArgs = {}; + if(frameworkPostArgsJSON){ + frameworkPostArgs = $.parseJSON(frameworkPostArgsJSON); + } + var postData = $.extend({}, msgData.payload, frameworkPostArgs); + var toopherData = {'toopher_iframe_data': $.param(postData)}; + + if(iframe.attr('use_ajax_postback')){ + $.post(iframe.attr('toopher_postback'), toopherData) + .done(function(data){ + data = $.parseJSON(data); + }); + } else { + postToUrl(iframe.attr('toopher_postback'), toopherData, 'POST'); + } + } + } + + if (window.addEventListener) { + window.addEventListener('message', handleMessage, false); + } else { + window.attachEvent('onmessage', handleMessage); + } +})(window, jQuery); From 2cf03ed785b4984882140232c8e91dba290c35a6 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 14:45:32 -0500 Subject: [PATCH 091/114] Update demo to match toopher-python --- demo/toopher_demo.php | 51 +++++++++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/demo/toopher_demo.php b/demo/toopher_demo.php index f8a5d69..2576211 100644 --- a/demo/toopher_demo.php +++ b/demo/toopher_demo.php @@ -26,6 +26,9 @@ $stdin = fopen('php://stdin', 'r'); +const DEFAULT_USERNAME = 'demo@toopher.com'; +const DEFAULT_TERMINAL_NAME = 'my computer'; + function printHorizontalLine($character = '-') { echo(str_repeat($character, 40) . "\n"); @@ -43,20 +46,20 @@ function initializeApi() $key = getenv('TOOPHER_CONSUMER_KEY'); $secret = getenv('TOOPHER_CONSUMER_SECRET'); + if(empty($key) || empty($secret)){ echo("Enter your requester credentials (from https://dev.toopher.com).\n"); echo("Hint: Set the TOOPHER_CONSUMER_SECRET and TOOPHER_CONSUMER_SECRET environment variables to avoid this prompt.\n"); - echo('Consumer Key:'); + echo('TOOPHER_CONSUMER_KEY:'); $key = rtrim(fgets($stdin)); - echo('Consumer Secret:'); + echo('TOOPHER_CONSUMER_SECRET:'); $secret = rtrim(fgets($stdin)); } - echo ("\nUsing Consumer Key=$key, Consumer Secret=$secret\n"); - return new ToopherApi($key, $secret); + return new ToopherApi($key, $secret, getenv('TOOPHER_BASE_URL')); } -function pair($toopher) +function pairDeviceWithToopher($toopher) { global $stdin; @@ -69,16 +72,19 @@ function pair($toopher) $phrase = rtrim(fgets($stdin)); } while (empty($phrase)); - do { - echo('Enter user name: '); - $userName = rtrim(fgets($stdin)); - } while (empty($userName)); + + echo(sprintf('Enter a username for this pairing [%s]: ', DEFAULT_USERNAME)); + $userName = rtrim(fgets($stdin)); + + if (empty($userName)) { + $userName = DEFAULT_USERNAME; + } try { $pairing = $toopher->pair($userName, $phrase); break; } catch (Exception $e) { - echo ("The pairing phrase was not accepted. Please try pairing again.\n"); + echo (sprintf("The pairing phrase was not accepted (Reason: %s) \n", $e->getMessage())); } } @@ -99,39 +105,42 @@ function pair($toopher) break; } } catch (Exception $e) { - echo ("Could not check pairing status. Please try authorizing again.)\n"); + echo (sprintf("Could not check pairing status (Reason: %s)\n", $e->getMessage())); } } } -function authenticate($pairing, $toopher) +function authenticateWithToopher($pairing, $toopher) { global $stdin; while(true) { printTextWithUnderline('STEP 2: Authenticate log in'); - do { - echo('Enter a terminal name for this authentication request [my computer]:'); - $terminalName = rtrim(fgets($stdin)); - } while (empty($terminalName)); + echo(sprintf('Enter a terminal name for this authentication request [%s]: ', DEFAULT_TERMINAL_NAME)); + $terminalName = rtrim(fgets($stdin)); + + if (empty($terminalName)) { + $terminalName = DEFAULT_TERMINAL_NAME; + } echo("Sending authentication request...\n"); try { $auth = $toopher->authenticate($pairing->user->name, $terminalName); } catch (Exception $e) { - echo ('Error initiating authentication (Reason: $e)'); + echo (sprintf('Error initiating authentication (Reason: %s)', $e->getMessage())); + break; } while(true) { echo ('Respond to authentication request on phone and then press return to continue.'); rtrim(fgets($stdin)); - echo ("\nChecking status of authenticationr request...\n"); + echo ("\nChecking status of authentication request...\n"); try { $auth->refreshFromServer(); } catch (Exception $e) { - echo ('Could not check authentication status (Reason: $e)'); + echo (sprintf('Could not check authentication status (Reason: %s)', $e->getMessage())); } if ($auth->pending) { @@ -155,10 +164,10 @@ function demo() $toopher = initializeApi(); do { - $pairing = pair($toopher); + $pairing = pairDeviceWithToopher($toopher); } while (!$pairing); - authenticate($pairing, $toopher); + authenticateWithToopher($pairing, $toopher); } demo() From 69724182ed80dcdd40af1dabfbfc4f683cbd7e5c Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 15:52:55 -0500 Subject: [PATCH 092/114] Simplify AuthenticationRequest.grantWithOtp --- lib/AuthenticationRequest.php | 5 ++--- test/AuthenticationRequestTest.php | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/AuthenticationRequest.php b/lib/AuthenticationRequest.php index 2a52304..0ee78ca 100644 --- a/lib/AuthenticationRequest.php +++ b/lib/AuthenticationRequest.php @@ -55,9 +55,8 @@ public function refreshFromServer() public function grantWithOtp($otp, $kwargs = array()) { $url = 'authentication_requests/' . $this->id . '/otp_auth'; - $params = array('otp' => $otp); - $params = array_merge($params, $kwargs); - $result = $this->api->advanced->raw->post($url, $params); + $kwargs['otp'] = $otp; + $result = $this->api->advanced->raw->post($url, $kwargs); $this->update($result); } diff --git a/test/AuthenticationRequestTest.php b/test/AuthenticationRequestTest.php index 38dc3d1..8665ed6 100644 --- a/test/AuthenticationRequestTest.php +++ b/test/AuthenticationRequestTest.php @@ -116,9 +116,9 @@ public function testGrantAuthenticationRequestPostsOtp(){ $toopher = $this->getToopherApi($this->mock); $authRequest = $this->getAuthenticationRequest($toopher); - $authRequest->grantWithOtp('otp'); + $authRequest->grantWithOtp('foo'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == 'otp=otp', "Post params should include 'otp=otp'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == 'otp=foo', "Post params should include 'otp=foo'"); $this->assertTrue($authRequest->pending == false, 'Authentication request should not be pending'); $this->assertTrue($authRequest->granted == true, 'Authentication request should be granted'); From cd3bd5099ef5adbfde03498a54b9cc0340a8cfb5 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 16:12:03 -0500 Subject: [PATCH 093/114] Simplify Pairing.emailResetLink --- lib/Pairing.php | 5 ++--- test/PairingTest.php | 1 + 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/Pairing.php b/lib/Pairing.php index 4b07584..7ad5023 100644 --- a/lib/Pairing.php +++ b/lib/Pairing.php @@ -63,10 +63,9 @@ public function getResetLink($kwargs = array()) public function emailResetLink($email, $kwargs = array()) { - $params = array('reset_email' => $email); - $params = array_merge($params, $kwargs); + $kwargs['reset_email'] = $email; $url = 'pairings/' . $this->id . '/send_reset_link'; - $this->api->advanced->raw->post($url, $params); + $this->api->advanced->raw->post($url, $kwargs); } public function getQrCodeImage() diff --git a/test/PairingTest.php b/test/PairingTest.php index 59258c0..5bfaea0 100644 --- a/test/PairingTest.php +++ b/test/PairingTest.php @@ -102,6 +102,7 @@ public function testEmailPairingResetLinkShouldPostToCorrectUrl(){ $pairing->emailResetLink('jdoe@example.com'); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getBody() == 'reset_email=jdoe%40example.com', "Post params should include 'reset_email=jdoe%40example.com'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == 'https://api.toopher.com/v1/pairings/1/send_reset_link', "Last called url should be 'https://api.toopher.com/v1/pairings/1/send_reset_link'"); } From 91cbb50d9bc440b5a0c0cdd87242b60529acfe9e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 16:22:24 -0500 Subject: [PATCH 094/114] Make default base url a constant --- lib/ToopherApi.php | 3 ++- test/ToopherApiTest.php | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/ToopherApi.php b/lib/ToopherApi.php index 8173b77..e756059 100644 --- a/lib/ToopherApi.php +++ b/lib/ToopherApi.php @@ -29,6 +29,7 @@ class ToopherRequestException extends Exception class ToopherApi { const VERSION = '2.0.0'; + const DEFAULT_BASE_URL = 'https://api.toopher.com/v1/'; protected $baseUrl; protected $oauthConsumer; @@ -44,7 +45,7 @@ function __construct($key, $secret, $baseUrl = '', $httpAdapter = NULL) } $this->oauthConsumer = new HTTP_OAuth_Consumer($key, $secret); - $this->baseUrl = (!empty($baseUrl)) ? $baseUrl : 'https://api.toopher.com/v1/'; + $this->baseUrl = (!empty($baseUrl)) ? $baseUrl : ToopherApi::DEFAULT_BASE_URL; $this->httpAdapter = (!is_null($httpAdapter)) ? $httpAdapter : new HTTP_Request2_Adapter_Curl(); $this->advanced = new AdvancedApiUsageFactory($key, $secret, $baseUrl, $httpAdapter, $this); } diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 6fed8d7..88ea25b 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -113,6 +113,11 @@ public function testToopherVersionStringExists() $this->assertGreaterThanOrEqual(0, (int)$patch); } + public function testDefaultBaseUrl() + { + $this->assertTrue(ToopherApi::DEFAULT_BASE_URL == 'https://api.toopher.com/v1/', "Default base url should be 'https://api.toopher.com/v1/'"); + } + public function testPairReturnsPairing() { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/create'); From e674bb3a5f1301399d29ccdb9b96e6250679b418 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 16:43:22 -0500 Subject: [PATCH 095/114] Cleanup ToopherApi --- lib/ToopherApi.php | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/lib/ToopherApi.php b/lib/ToopherApi.php index e756059..97622c8 100644 --- a/lib/ToopherApi.php +++ b/lib/ToopherApi.php @@ -53,7 +53,6 @@ function __construct($key, $secret, $baseUrl = '', $httpAdapter = NULL) public function pair($username, $phraseOrNumber = NULL, $kwargs = array()) { $params = array('user_name' => $username); - $params = array_merge($params, $kwargs); if (!empty($phraseOrNumber)) { if (preg_match('/\d/', $phraseOrNumber, $match)) { $url = 'pairings/create/sms'; @@ -65,6 +64,7 @@ public function pair($username, $phraseOrNumber = NULL, $kwargs = array()) } else { $url = 'pairings/create/qr'; } + $params = array_merge($params, $kwargs); $result = $this->advanced->raw->post($url, $params); return new Pairing($result, $this); } @@ -123,15 +123,8 @@ class ApiRawRequester function __construct($key, $secret, $baseUrl, $httpAdapter) { - if (empty($key)) { - throw new InvalidArgumentException('Toopher consumer key cannot be empty'); - } - if (empty($secret)) { - throw new InvalidArgumentException('Toopher consumer secret cannot be empty'); - } - $this->oauthConsumer = new HTTP_OAuth_Consumer($key, $secret); - $this->baseUrl = (!empty($baseUrl)) ? $baseUrl : 'https://api.toopher.com/v1/'; + $this->baseUrl = (!empty($baseUrl)) ? $baseUrl : ToopherApi::DEFAULT_BASE_URL; $this->httpAdapter = (!is_null($httpAdapter)) ? $httpAdapter : new HTTP_Request2_Adapter_Curl(); } @@ -181,7 +174,7 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest if ($result->getStatus() >= 400) { error_log(sprintf('Toopher API call returned unexpected HTTP response: %d - %s', $result->getStatus(), $result->getReasonPhrase())); if (empty($resultBody)) { - error_log('empty response body'); + error_log('Empty response body'); throw new ToopherRequestException($result->getReasonPhrase(), $result->getStatus()); } @@ -191,7 +184,7 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest if (!empty($jsonError)) { error_log(sprintf('Error parsing response body JSON: %s', $jsonError)); - error_log(sprintf('response body: %s', $result->getBody())); + error_log(sprintf('Response body: %s', $result->getBody())); throw new ToopherRequestException(sprintf('JSON Parsing Error: %s', $jsonError)); } } else { @@ -212,7 +205,7 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest $jsonError = $this->json_error_to_string(json_last_error()); if (!empty($jsonError)) { error_log(sprintf('Error parsing response body JSON: %s', $jsonError)); - error_log(sprintf('response body: %s', $result->getBody())); + error_log(sprintf('Response body: %s', $result->getBody())); throw new ToopherRequestException(sprintf('JSON Parsing Error: %s', $jsonError)); } } @@ -286,9 +279,8 @@ public function getByName($username) public function create($username, $kwargs = array()) { $url = 'users/create'; - $params = array('name' => $username); - $params = array_merge($params, $kwargs); - $result = $this->api->advanced->raw->post($url, $params); + $kwargs ['name'] = $username; + $result = $this->api->advanced->raw->post($url, $kwargs); return new User($result, $this->api); } } From 64eaf75d954a927f1d2b4481b3ecc4016a580f11 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 16:44:36 -0500 Subject: [PATCH 096/114] Throw InvalidArgumentException if key or secret is missing for ToopherIframe --- lib/ToopherIframe.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 50758b8..ff50ec6 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -33,6 +33,13 @@ class ToopherIframe function __construct($key, $secret, $baseUrl = 'https://api.toopher.com/v1/') { + if (empty($key)) { + throw new InvalidArgumentException('Toopher consumer key cannot be empty'); + } + if (empty($secret)) { + throw new InvalidArgumentException('Toopher consumer secret cannot be empty'); + } + $this->consumerSecret = $secret; $this->consumerKey = $key; $this->oauthConsumer = new OAuth($key, $secret); From b00820c5b2e41a989e97e04977c91027fb14f6be Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 16:49:27 -0500 Subject: [PATCH 097/114] Use switch to evaluate resourceType in processPostback --- lib/ToopherIframe.php | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index ff50ec6..974dfc8 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -115,15 +115,16 @@ public function processPostback($data, $requestToken = '', $kwargs = array()) } else { $this->validateData($toopherData, $requestToken, $kwargs); $api = new ToopherApi($this->consumerKey, $this->consumerSecret); - $resourceType = $toopherData['resource_type']; - if ($resourceType == 'authentication_request') { - return new AuthenticationRequest($this->createAuthenticationRequestArray($toopherData), $api); - } else if ($resourceType == 'pairing') { - return new Pairing($this->createPairingArray($toopherData), $api); - } else if ($resourceType == 'requester_user') { - return new User($this->createUserArray($toopherData), $api); - } else { - throw new ToopherRequestException('The postback resource type is not valid: ' . $resourceType); + + switch ($toopherData['resource_type']) { + case 'authentication_request': + return new AuthenticationRequest($this->createAuthenticationRequestArray($toopherData), $api); + case 'pairing': + return new Pairing($this->createPairingArray($toopherData), $api); + case 'requester_user': + return new User($this->createUserArray($toopherData), $api); + default: + throw new ToopherRequestException('The postback resource type is not valid: ' . $toopherData['resource_type']); } } } From f361f09734fc5ed3a46b2cec000ab2c87b5a9aa0 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 16:50:25 -0500 Subject: [PATCH 098/114] Include baseUrl when creating new instance of ToopherApi --- lib/ToopherIframe.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 974dfc8..bc9138b 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -114,7 +114,7 @@ public function processPostback($data, $requestToken = '', $kwargs = array()) throw new ToopherRequestException($toopherData['error_message'], $toopherData['error_code']); } else { $this->validateData($toopherData, $requestToken, $kwargs); - $api = new ToopherApi($this->consumerKey, $this->consumerSecret); + $api = new ToopherApi($this->consumerKey, $this->consumerSecret, $this->baseUrl); switch ($toopherData['resource_type']) { case 'authentication_request': From 6ff26353deaf29173bb7a85228b0c516ca704222 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 24 Mar 2015 17:14:25 -0500 Subject: [PATCH 099/114] Cleanup ToopherIframe --- lib/ToopherIframe.php | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index bc9138b..5dec78f 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -155,7 +155,6 @@ private function validateData($data, $requestToken, $kwargs) $this->verifySessionToken($data['session_token'], $requestToken); $this->checkIfSignatureIsExpired($data['timestamp'], $kwargs); $this->validateSignature($data); - return $data; } catch (Exception $e) { throw new SignatureValidationError ('Exception while validating toopher signature: ' . $e); } @@ -178,7 +177,7 @@ private function checkForMissingKeys($data) private function verifySessionToken($sessionToken, $requestToken) { - if ($requestToken != '' && $sessionToken != $requestToken) { + if (!empty($requestToken) && $sessionToken != $requestToken) { throw new SignatureValidationError('Session token does not match expected value'); } } @@ -295,17 +294,8 @@ private function getOauthParams() 'oauth_signature_method' => $this->signatureMethod, 'oauth_version' => $this->oauthVersion ); - - if (!is_null($this->nonceOverride)) { - $oauthParams['oauth_nonce'] = $this->nonceOverride; - } else { - $oauthParams['oauth_nonce'] = uniqid() . '.' . time(); - } - if (!is_null($this->timestampOverride)) { - $oauthParams['oauth_timestamp'] = $this->timestampOverride; - } else { - $oauthParams['oauth_timestamp'] = time(); - } + $oauthParams['oauth_nonce'] = $this->nonceOverride ?: uniqid() . '.' . time(); + $oauthParams['oauth_timestamp'] = $this->timestampOverride ?: time(); return $oauthParams; } From 49c9e76a49830934a4d3cf9f283678720ec747f1 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 25 Mar 2015 08:58:33 -0500 Subject: [PATCH 100/114] Add MIT license --- LICENSE.txt | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LICENSE.txt diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..ac87d1c --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright (c) 2012 Toopher, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. From 6ae30c7fb742e80089c25fbd062bfc5ff50802be Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 25 Mar 2015 17:43:54 -0500 Subject: [PATCH 101/114] Include parameters in GET request --- lib/ToopherApi.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ToopherApi.php b/lib/ToopherApi.php index 97622c8..562ed8a 100644 --- a/lib/ToopherApi.php +++ b/lib/ToopherApi.php @@ -138,9 +138,9 @@ public function post($endpoint, $parameters) return $this->request('POST', $endpoint, $parameters); } - public function get($endpoint) + public function get($endpoint, $parameters = array()) { - return $this->request('GET', $endpoint); + return $this->request('GET', $endpoint, $parameters); } public function get_raw($endpoint) From 620ef88191323099eef7328d5b80a725e16dc557 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 25 Mar 2015 17:44:39 -0500 Subject: [PATCH 102/114] Improve tests by checking urls and parameters --- test/ToopherApiTest.php | 62 ++++++++++++++++++++++++++++++++++------- 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index 88ea25b..e832e28 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -26,6 +26,8 @@ class ToopherApiTests extends PHPUnit_Framework_TestCase { + const DEFAULT_BASE_URL = 'https://api.toopher.test/v1/'; + protected function setUp() { $this->mock = new HTTP_Request2_Adapter_Mock(); @@ -33,7 +35,7 @@ protected function setUp() protected function getToopherApi($mock = NULL) { - return new ToopherApi('key', 'secret', '', $mock); + return new ToopherApi('key', 'secret', ToopherApiTests::DEFAULT_BASE_URL, $mock); } public function compareToDefaultPairing($pairing) @@ -124,7 +126,11 @@ public function testPairReturnsPairing() $resp->appendBody('{"id":"1","enabled":true,"pending":false,"user":{"id":"1","name":"user", "toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); - $pairing = $toopher->pair('user', 'immediate_pair'); + $pairing = $toopher->pair('user', 'immediate pair'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'pairings/create', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'pairings/create')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['user_name'] == 'user', "Last called parameters should include key-value pair: 'user_name'=>'user'"); + $this->assertTrue($parameters['pairing_phrase'] == 'immediate pair', "Last called parameters should include key-value pair: 'pairing_phrase'=>'immediate pair'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultPairing($pairing); } @@ -136,6 +142,10 @@ public function testPairSmsReturnsPairing() $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); $pairing = $toopher->pair('user', '555-555-5555'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'pairings/create/sms', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'pairings/create/sms')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['user_name'] == 'user', "Last called parameters should include key-value pair: 'user_name'=>'user'"); + $this->assertTrue($parameters['phone_number'] == '555-555-5555', "Last called parameters should include key-value pair: 'phone_number'=>'555-555-5555'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultPairing($pairing); } @@ -147,6 +157,9 @@ public function testPairQrReturnsPairing() $this->mock->addResponse($resp); $toopher = $this->getToopherApi($this->mock); $pairing = $toopher->pair('user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'pairings/create/qr', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'pairings/create/qr')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['user_name'] == 'user', "Last called parameters should include key-value pair: 'user_name'=>'user'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultPairing($pairing); } @@ -160,6 +173,9 @@ public function testAuthenticateWithPairingIdReturnsAuthenticationRequest() $toopher = $this->getToopherApi($this->mock); $authRequest = $toopher->authenticate($id); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['pairing_id'] == $id, "Last called parameters should include key-value pair: 'pairing_id'=>" . $id); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultAuthenticationRequest($authRequest, $id); } @@ -174,6 +190,7 @@ public function testAuthenticateWithPairingIdOptionalArgsAndExtrasReturnsAuthent $toopher = $this->getToopherApi($this->mock); $authRequest = $toopher->authenticate($id, 'term name', '1', 'it is a test', $extras); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate')); $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->assertTrue($parameters['pairing_id'] == $id, sprintf("Last called parameters should include key-value pair: 'pairing_id'=> %s", $id)); @@ -192,11 +209,14 @@ public function testAuthenticateWithUsernameReturnsAuthenticationRequest() $toopher = $this->getToopherApi($this->mock); $authRequest = $toopher->authenticate('user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['user_name'] == 'user', "Last called parameters should include key-value pair: 'user_name'=>'user'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultAuthenticationRequest($authRequest); } - public function testAuthentiateWithUsernameOptionalArgsAndExtrasReturnsAuthenticationRequest() + public function testAuthenticateWithUsernameOptionalArgsAndExtrasReturnsAuthenticationRequest() { $extras = array('foo' => 'bar'); $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/initiate'); @@ -205,6 +225,7 @@ public function testAuthentiateWithUsernameOptionalArgsAndExtrasReturnsAuthentic $toopher = $this->getToopherApi($this->mock); $authRequest = $toopher->authenticate('user', 'term name', '1', 'it is a test', $extras); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate')); $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->assertTrue($parameters['user_name'] == 'user', "Last called parameters should include key-value pair: 'user_name'=>'user'"); @@ -224,6 +245,7 @@ public function testRawPost() $toopher = $this->getToopherApi($this->mock); $params = array('pairing_id' => '1', 'terminal_name' => 'term name'); $authRequest = $toopher->advanced->raw->post('authentication_requests/initiate', $params); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/initiate')); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); @@ -244,6 +266,7 @@ public function testRawGet() $toopher = $this->getToopherApi($this->mock); $authRequest = $toopher->advanced->raw->get('authentication_requests/1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/1', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/1')); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->assertTrue($authRequest['id'] == '1', 'Authentication request id was incorrect'); $this->assertTrue($authRequest['pending'] == false, 'Authentication request should not be pending'); @@ -264,6 +287,7 @@ public function testPairingsGetByIdReturnsPairing() $toopher = $this->getToopherApi($this->mock); $pairing = $toopher->advanced->pairings->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'pairings/1', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'pairings/1')); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->compareToDefaultPairing($pairing); } @@ -276,6 +300,7 @@ public function testAuthenticationRequestsGetByIdReturnsAuthenticationRequest() $toopher = $this->getToopherApi($this->mock); $authRequest = $toopher->advanced->authenticationRequests->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/1', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'authentication_requests/1')); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->compareToDefaultAuthenticationRequest($authRequest); } @@ -288,6 +313,7 @@ public function testUsersGetByIdReturnsUser() $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'users/1', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'users/1')); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->compareToDefaultUser($user); } @@ -300,6 +326,7 @@ public function testUsersGetByNameReturnsUser() $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->getByName('user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'users?user_name=user', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'users?user_name=user')); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->compareToDefaultUser($user); } @@ -316,8 +343,6 @@ public function testUsersGetByNameWithMultipleUsersRaisesToopherRequestException $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->getByName('user'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultUser($user); } /** @@ -332,8 +357,6 @@ public function testUsersGetByNameWithNoUsersRaisesToopherRequestException() $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->getByName('user'); - $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); - $this->compareToDefaultUser($user); } public function testUsersCreateReturnsUser() @@ -344,6 +367,9 @@ public function testUsersCreateReturnsUser() $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->create('paired user'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'users/create', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'users/create')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['name'] == 'paired user', "Last called parameters should include key-value pair: 'name'=>'paired user'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultUser($user); } @@ -356,6 +382,10 @@ public function testUsersCreateWithExtrasReturnsUser() $toopher = $this->getToopherApi($this->mock); $user = $toopher->advanced->users->create('paired user', array('foo'=>'bar')); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'users/create', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'users/create')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['name'] == 'paired user', "Last called parameters should include key-value pair: 'name'=>'paired user'"); + $this->assertTrue($parameters['foo'] == 'bar', "Last called parameters should include key-value pair: 'foo'=>'bar'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultUser($user); } @@ -366,8 +396,9 @@ public function testUserTerminalsGetByIdReturnsUserTerminal() $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $userTerminal = $toopher->advanced->userTerminals->getById('1'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'user_terminals/1', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'user_terminals/1')); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'GET', "Last called method should be 'GET'"); $this->compareToDefaultUserTerminal($userTerminal); } @@ -378,8 +409,13 @@ public function testUserTerminalCreateReturnsUserTerminal() $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id'); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'user_terminals/create', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'user_terminals/create')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['user_name'] == 'name', "Last called parameters should include key-value pair: 'user_name'=>'name'"); + $this->assertTrue($parameters['name'] == 'terminal one', "Last called parameters should include key-value pair: 'name'=>'terminal one'"); + $this->assertTrue($parameters['name_extra'] == 'requester specified id', "Last called parameters should include key-value pair: 'name_extra'=>'requester specified id'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultUserTerminal($userTerminal); } @@ -390,8 +426,14 @@ public function testUserTerminalCreateWithExtrasReturnsUserTerminal() $resp->appendBody('{"id":"1", "name":"terminal name", "requester_specified_id": "requester specified id", "user":{"id":"1","name":"user name","toopher_authentication_enabled":true}}'); $this->mock->addResponse($resp); - $toopher = new ToopherApi('key', 'secret', '', $this->mock); + $toopher = $this->getToopherApi($this->mock); $userTerminal = $toopher->advanced->userTerminals->create('name', 'terminal one', 'requester specified id', array('foo'=>'bar')); + $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getUrl() == ToopherApiTests::DEFAULT_BASE_URL . 'user_terminals/create', sprintf("Last called url should be '%s'", ToopherApiTests::DEFAULT_BASE_URL . 'user_terminals/create')); + $parameters = $toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getParameters(); + $this->assertTrue($parameters['user_name'] == 'name', "Last called parameters should include key-value pair: 'user_name'=>'name'"); + $this->assertTrue($parameters['name'] == 'terminal one', "Last called parameters should include key-value pair: 'name'=>'terminal one'"); + $this->assertTrue($parameters['name_extra'] == 'requester specified id', "Last called parameters should include key-value pair: 'name_extra'=>'requester specified id'"); + $this->assertTrue($parameters['foo'] == 'bar', "Last called parameters should include key-value pair: 'foo'=>'bar'"); $this->assertTrue($toopher->advanced->raw->getOauthConsumer()->getLastRequest()->getMethod() == 'POST', "Last called method should be 'POST'"); $this->compareToDefaultUserTerminal($userTerminal); } From 884e6a5a901d285c390a9b0da1921a288f64f0b2 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 26 Mar 2015 11:53:29 -0500 Subject: [PATCH 103/114] Add tests for ToopherRequestException in ToopherApi.request --- lib/ToopherApi.php | 2 +- test/ToopherApiTest.php | 49 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/lib/ToopherApi.php b/lib/ToopherApi.php index 562ed8a..4e13f1c 100644 --- a/lib/ToopherApi.php +++ b/lib/ToopherApi.php @@ -166,7 +166,7 @@ private function request($method, $endpoint, $parameters = array(), $rawRequest try { $result = $this->oauthConsumer->sendRequest($this->baseUrl . $endpoint, $parameters, $method); } catch (Exception $e) { - error_log($e); + error_log($e->getMessage()); throw new ToopherRequestException('Error making Toopher API request', $e->getCode(), $e); } diff --git a/test/ToopherApiTest.php b/test/ToopherApiTest.php index e832e28..122b854 100644 --- a/test/ToopherApiTest.php +++ b/test/ToopherApiTest.php @@ -279,6 +279,16 @@ public function testRawGet() $this->assertTrue($authRequest['action'] == array('id'=>'1', 'name'=>'test'), 'Action data was incorrect'); } + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Error making Toopher API request + */ + public function testGetWithoutHttpRequestMockRaisesToopherRequestException() + { + $toopher = $this->getToopherApi(); + $toopher->advanced->raw->get(''); + } + public function testPairingsGetByIdReturnsPairing() { $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/pairings/1'); @@ -473,6 +483,45 @@ public function test403WithUnprintableBodyRaisesToopherRequestException() $toopher = $this->getToopherApi($this->mock); $auth = $toopher->advanced->authenticationRequests->getById('1'); } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage Forbidden - {"error_code":401} + */ + public function test403WithEmptyMessageRaisesToopherRequestException() + { + $resp = new HTTP_Request2_Response('HTTP/1.1 403 Forbidden', false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('{"error_code":401}'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage JSON Parsing Error: Syntax error, malformed JSON + */ + public function test200WithEmptyMessageRaisesToopherRequestException() + { + $resp = new HTTP_Request2_Response('HTTP/1.1 200 OK', false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('stuff'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); + } + + /** + * @expectedException ToopherRequestException + * @expectedExceptionMessage JSON Parsing Error: Syntax error, malformed JSON + */ + public function test403WithBadJsonRaisesToopherRequestException() + { + $resp = new HTTP_Request2_Response('HTTP/1.1 403 Forbidden', false, 'https://api.toopher.com/v1/authentication_requests/1'); + $resp->appendBody('stuff'); + $this->mock->addResponse($resp); + $toopher = $this->getToopherApi($this->mock); + $auth = $toopher->advanced->authenticationRequests->getById('1'); + } } ?> From 89ae870950917933c647e47c4f4137b7661cd485 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 26 Mar 2015 16:40:29 -0500 Subject: [PATCH 104/114] Add license and cleanup intro --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 584538b..296810b 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,8 @@ -# ToopherApi PHP Client - -[![Build +# ToopherPHP [![Build Status](https://travis-ci.org/toopher/toopher-php.png?branch=master)](https://travis-ci.org/toopher/toopher-php) #### Introduction -ToopherApi PHP Client simplifies the task of interfacing with the Toopher API from PHP code. This project includes all the dependency libraries and handles the required OAuth and JSON functionality so you can focus on just using the API. +ToopherPHP is a Toopher API library that simplifies the task of interfacing with the Toopher API from PHP code. This project includes all the dependency libraries and handles the required OAuth and JSON functionality so you can focus on just using the API. #### Learn the Toopher API Make sure you visit [http://dev.toopher.com](http://dev.toopher.com) to get acquainted with the Toopher API fundamentals. The documentation there will tell you the details about the operations this API wrapper library provides. @@ -81,3 +79,6 @@ would be ```shell $ vendor/bin/phpunit test ``` + +#### License +ToopherPHP is licensed under the MIT License. See LICENSE.txt for the full license text. From d93de8f58f96ea6f99625683b19fbd891b8a7ed1 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 26 Mar 2015 16:40:46 -0500 Subject: [PATCH 105/114] Add tests for ToopherIframe creation InvalidArgumentException --- test/ToopherIframeTest.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 0286d10..539929b 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -121,6 +121,24 @@ protected function setUp() $this->toopherIframe->setTimestampOverride($this->getOauthTimestamp()); } + /** + * @expectedException InvalidArgumentException + * @expectedExceptionMessage Toopher consumer key cannot be empty + */ + public function testEmptyKeyThrowsException() + { + $toopher = new ToopherIframe('', 'secret'); + } + + /** + * @expectedException InvalidArgumentException + * @expectedExceptionMessage Toopher consumer secret cannot be empty + */ + public function testEmptySecretThrowsException() + { + $toopher = new ToopherIframe('key', ''); + } + public function testGetAuthenticationUrlOnlyUsernameReturnsValidUrl() { $this->toopherIframe->setNonceOverride($this->getOauthNonce()); From ee6b45865a97b0993980172b6c844e4a1c41161d Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 26 Mar 2015 16:53:21 -0500 Subject: [PATCH 106/114] Update processPostback test to use and test default timestamp --- test/ToopherIframeTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 539929b..799e805 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -265,7 +265,7 @@ public function testProcessPostbackWithBadSignatureRaisesError() */ public function testProcessPostbackWithExpiredSignatureRaisesError() { - $this->toopherIframe->setTimeStampOverride(mktime(0, 16, 40, 2, 1, 1970)); + $this->toopherIframe->setTimeStampOverride(null); $authData = $this->getAuthenticationRequestData(); $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } From a28b2807137da9920ba6262ba3c2cea2f4131150 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 26 Mar 2015 17:24:31 -0500 Subject: [PATCH 107/114] Add test for SignatureValidationError while calculating signature in ToopherIframe.processPostback --- lib/ToopherIframe.php | 2 +- test/ToopherIframeTest.php | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/ToopherIframe.php b/lib/ToopherIframe.php index 5dec78f..ef2266c 100644 --- a/lib/ToopherIframe.php +++ b/lib/ToopherIframe.php @@ -205,7 +205,7 @@ private function validateSignature($data) $computedSignature = $this->signature($this->consumerSecret, $data); $signatureValid = $maybeSignature == $computedSignature; } catch (Exception $e) { - throw new SignatureValidationError('Error while calculating signature: ' . $e); + throw new SignatureValidationError('Error while calculating signature: ' . $e->getMessage()); } if (!$signatureValid) { diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 799e805..304e7d2 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -338,6 +338,18 @@ public function testProcessPostbackWithErrorCodeRaisesError() $this->toopherIframe->processPostback($this->getUrlencodedData($authData), $this->getRequestToken()); } + /** + * @expectedException SignatureValidationError + * @expectedExceptionMessage Error while calculating signature: + */ + public function testProcessPostbackWithBadSecretRaisesError() + { + $toopherIframe = new ToopherIframe('key', array('hi'), 'https://api.toopher.test/v1/'); + $toopherIframe->setTimeStampOverride($this->getOauthTimestamp()); + $toopherIframe->setNonceOverride($this->getOauthNonce()); + $toopherIframe->processPostback($this->getUrlencodedData($this->getAuthenticationRequestData()), $this->getRequestToken()); + } + public function testIsAuthenticationGrantedWithAuthenticationRequestGrantedReturnsTrue() { $this->assertTrue($this->toopherIframe->isAuthenticationGranted($this->getUrlencodedData($this->getAuthenticationRequestData()), $this->getRequestToken())); From e3cc2be7ca712f85c91e1d0ff2c10b0f1470fc01 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 30 Mar 2015 17:03:06 -0500 Subject: [PATCH 108/114] Add processPostback test for keys with empty values --- test/ToopherIframeTest.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/ToopherIframeTest.php b/test/ToopherIframeTest.php index 304e7d2..fa8a2f5 100644 --- a/test/ToopherIframeTest.php +++ b/test/ToopherIframeTest.php @@ -248,6 +248,15 @@ public function testProcessPostbackWithoutRequestTokenReturnsAuthenticationReque $this->assertTrue(is_a($authRequest, 'AuthenticationRequest'), 'AuthenticationRequest should be returned'); } + public function testProcessPostbackWithKeyWithEmptyValueReturnsAuthenticationRequest() + { + $authData = $this->getAuthenticationRequestData(); + $authData['requester_metadata'] = ''; + $authData['toopher_sig'] = '2CQouLu8dL3OA8N/mgHK6eeYHm4='; + $authRequest = $this->toopherIframe->processPostback($this->getUrlEncodedData($authData)); + $this->assertTrue(is_a($authRequest, 'AuthenticationRequest'), 'AuthenticationRequest should be returned'); + } + /** * @expectedException SignatureValidationError * @expectedExceptionMessage Computed signature does not match From d7a7dcc5d67e13c3068c9442b6fbf6c3924554df Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 31 Mar 2015 11:04:21 -0500 Subject: [PATCH 109/114] Simplify README and add iframe info --- README.md | 105 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 296810b..7aed739 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,17 @@ -# ToopherPHP [![Build -Status](https://travis-ci.org/toopher/toopher-php.png?branch=master)](https://travis-ci.org/toopher/toopher-php) +# ToopherPHP [![Build Status](https://travis-ci.org/toopher/toopher-php.png?branch=master)](https://travis-ci.org/toopher/toopher-php) -#### Introduction ToopherPHP is a Toopher API library that simplifies the task of interfacing with the Toopher API from PHP code. This project includes all the dependency libraries and handles the required OAuth and JSON functionality so you can focus on just using the API. -#### Learn the Toopher API -Make sure you visit [http://dev.toopher.com](http://dev.toopher.com) to get acquainted with the Toopher API fundamentals. The documentation there will tell you the details about the operations this API wrapper library provides. +### PHP Version +\>=5.3.0 -#### OAuth Authentication +### Documentation +Make sure you visit [https://dev.toopher.com](https://dev.toopher.com) to get acquainted with the Toopher API fundamentals. The documentation there will tell you the details about the operations this API wrapper library provides. -The first step to accessing the Toopher API is to sign up for an account at the development portal [http://dev.toopher.com](http://dev.toopher.com) and create a "requester". When that process is complete, your requester is issued OAuth 1.0a credentials in the form of a consumer key and secret. Your key is used to identify your requester when Toopher interacts with your customers, and the secret is used to sign each request so that we know it is generated by you. This library properly formats each request with your credentials automatically. +## ToopherApi Workflow -#### The Toopher Two-Step -Interacting with the Toopher web service involves two steps: pairing, and authenticating. - -##### Pair -Before you can enhance your website's actions with Toopher, your customers will need to pair their phone's Toopher app with your website. To do this, they generate a unique, nonsensical "pairing phrase" from within the app on their phone. You will need to prompt them for a pairing phrase as part of the Toopher enrollment process. Once you have a pairing phrase, just send it to the Toopher API along with your requester credentials and we'll return a pairing ID that you can use whenever you want to authenticate an action for that user. - -##### Authenticate -You have complete control over what actions you want to authenticate using Toopher (for example: logging in, changing account information, making a purchase, etc.). Just send us the user's pairing ID, a name for the terminal they're using, and a description of the action they're trying to perform and we'll make sure they actually want it to happen. - -#### Librarified -This library makes it super simple to do the Toopher two-step. Check it out: +### Step 1: Pair +Before you can enhance your website's actions with Toopher, your customers will need to pair their mobile device's Toopher app with your website. To do this, they generate a unique pairing phrase from within the app on their mobile device. You will need to prompt them for a pairing phrase as part of the Toopher enrollment process. Once you have a pairing phrase, just send it to the Toopher web service along with your requester credentials and we'll return a pairing ID that you can use whenever you want to authenticate an action for that user. ```php require_once("toopher_api.php"); @@ -29,21 +19,16 @@ require_once("toopher_api.php"); // Create an API object using your credentials $toopherApi = new ToopherApi("", ""); -// Step 1 - Pair with their phone's Toopher app -// With pairing phrase +// Step 1 - Pair with their mobile device's Toopher app $pairing = $toopherApi->pair("username@yourservice.com", "pairing phrase"); -// With SMS -$pairing = $toopherApi->pair("username@yourservice.com", "555-555-5555"); -// With QR code -$pairing = $toopherApi->pair("username@yourservice.com"); +``` +### Step 2: Authenticate +You have complete control over what actions you want to authenticate using Toopher (logging in, changing account information, making a purchase, etc.). Just send us the username or pairing ID and we'll make sure they actually want it to happen. You can also choose to provide the following optional parameters: terminal name, requester specified ID and action name (*default: "Log in"*). +```php // Step 2 - Authenticate a log in -// With a pairing id and terminal name -$authRequest = $toopherApi->authenticate($pairing->id, "my computer"); -// With a username, terminal name and requester specified terminal id -$authRequest = $toopherApi->authenticate("username", "my computer", "requester specified id"); - +$authRequest = $toopherApi->authenticate("username", "my computer"); // Once they've responded you can then check the status $authRequest->refreshFromServer(); @@ -52,33 +37,65 @@ if ($authRequest->pending == false && $authRequest->granted == true) { } ``` -#### Dependencies -Toopher manages dependencies with [composer](http://getcomposer.org). To ensure all dependencies are up-to-date, execute the following command: -```shell -$ composer install +## ToopherIframe Workflow + +### Step 1: Embed a request in an IFRAME +1. Generate an authentication URL by providing a username. +2. Display a webapage to your user that embeds this URL within an `