http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/src/Native/Facades/Usergrid.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/src/Native/Facades/Usergrid.php b/sdks/other/php5/apache-usergrid/src/Native/Facades/Usergrid.php new file mode 100644 index 0000000..fbfcffe --- /dev/null +++ b/sdks/other/php5/apache-usergrid/src/Native/Facades/Usergrid.php @@ -0,0 +1,118 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Native\Facades; + + +use Apache\Usergrid\Native\UsergridBootstrapper; + +/** + * Class Usergrid + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class Usergrid +{ + /** + * The Native Bootstrap instance. + * + * @var \Apache\Usergrid\Native\UsergridBootstrapper + */ + protected static $instance; + /** + * The Usergrid API instance. + * + * @var \Apache\Usergrid\Api\Usergrid + */ + protected $usergrid; + + /** + * Constructor. + * + * @param \Apache\Usergrid\Native\UsergridBootstrapper $bootstraper + * @return \Apache\Usergrid\Native\Facades\Usergrid + */ + public function __construct(UsergridBootstrapper $bootstraper = null) + { + if (!$bootstraper) { + $bootstraper = new UsergridBootstrapper; + } + + $this->usergrid = $bootstraper->createUsergrid(); + } + + /** + * Handle dynamic, static calls to the object. + * + * @param string $method + * @param array $args + * @return mixed + */ + public static function __callStatic($method, $args) + { + $instance = static::instance()->getUsergrid(); + + switch (count($args)) { + case 0: + return $instance->{$method}(); + + case 1: + return $instance->{$method}($args[0]); + + case 2: + return $instance->{$method}($args[0], $args[1]); + + case 3: + return $instance->{$method}($args[0], $args[1], $args[2]); + + case 4: + return $instance->{$method}($args[0], $args[1], $args[2], $args[3]); + + default: + return call_user_func_array([$instance, $method], $args); + } + } + + /** + * Creates a new Native Bootstraper instance. + * + * @param \Apache\Usergrid\Native\UsergridBootstrapper $bootstrapper + * @return static + */ + public static function instance(UsergridBootstrapper $bootstrapper = null) + { + if (static::$instance === null) { + static::$instance = new static($bootstrapper); + } + + return static::$instance; + } + + /** + * Returns the Usergrid API instance. + * + * @return \Apache\Usergrid\Api\Usergrid + */ + public function getUsergrid() + { + return $this->usergrid; + } +} \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/src/Native/UsergridBootstrapper.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/src/Native/UsergridBootstrapper.php b/sdks/other/php5/apache-usergrid/src/Native/UsergridBootstrapper.php new file mode 100644 index 0000000..0f71b78 --- /dev/null +++ b/sdks/other/php5/apache-usergrid/src/Native/UsergridBootstrapper.php @@ -0,0 +1,150 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Native; + + +use Apache\Usergrid\Api\Usergrid; +use Apache\Usergrid\Guzzle\Plugin\Oauth2\GrantType\ClientCredentials; +use Apache\Usergrid\Guzzle\Plugin\Oauth2\GrantType\PasswordCredentials; +use Apache\Usergrid\Guzzle\Plugin\Oauth2\GrantType\RefreshToken; +use Apache\Usergrid\Guzzle\Plugin\Oauth2\Oauth2Plugin; +use Guzzle\Http\Client; + +/** + * Class UsergridBootstrapper + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class UsergridBootstrapper +{ + /** + * The Usergrid configuration. + * + * @var array + */ + protected $config; + + /** + * The Oauth2 Plugin. + * + * @var \Apache\Usergrid\Guzzle\Plugin\Oauth2\Oauth2Plugin + */ + protected $oauth2Plugin = null; + + /** + * Constructor. + * + * @param mixed $config + * @return \Apache\Usergrid\Native\UsergridBootstrapper + */ + public function __construct($config = null) + { + $this->config = $config ?: new ConfigRepository($config); + } + + /** + * Creates the Usergrid instance. + * + * @return \Apache\Usergrid\Api\Usergrid + */ + public function createUsergrid() + { + $baseUrl = array_get($this->config, 'usergrid.url'); + + $orgName = array_get($this->config, 'usergrid.orgName'); + + $appName = array_get($this->config, 'usergrid.appName'); + + $manifestPath = array_get($this->config, 'usergrid.manifestPath'); + + $version = array_get($this->config, 'usergrid.version'); + + $enable_oauth2_plugin = array_get($this->config, 'usergrid.enable_oauth2_plugin'); + + //check if user wants to manage there own Oauth 2 auth flow + if ($enable_oauth2_plugin) { + + $this->createOauth2Plugin(); + + return new Usergrid($orgName, $appName, $manifestPath, $version, $baseUrl, $this->oauth2Plugin); + } else { + return new Usergrid($orgName, $appName, $manifestPath, $version, $baseUrl); + } + + } + + private function createOauth2Plugin() + { + $base_url = array_get($this->config, 'usergrid.url'); + + $client_id = array_get($this->config, 'usergrid.clientId'); + + $client_secret = array_get($this->config, 'usergrid.clientSecret'); + + $grant_type = array_get($this->config, 'usergrid.grant_type'); + + $auth_type = array_get($this->config, 'usergrid.auth_type'); + + $username = array_get($this->config, 'usergrid.username'); + + $password = array_get($this->config, 'usergrid.password'); + + + $org_name = array_get($this->config, 'usergrid.orgName'); + + $app_name = array_get($this->config, 'usergrid.appName'); + + if ($auth_type == 'organization') { + + $url = $base_url . '/management/token'; + + } elseif ($auth_type == 'application') { + $url = $base_url . '/' . $org_name . '/' . $app_name . '/token'; + } + + $oauth2Client = new Client($url); + + + if ($grant_type == 'client_credentials') { + $config = [ + 'client_id' => $client_id, + 'client_secret' => $client_secret, + + ]; + $grantType = new ClientCredentials($oauth2Client, $config); + $refreshTokenGrantType = new RefreshToken($oauth2Client, $config); + $this->oauth2Plugin = new Oauth2Plugin($grantType, $refreshTokenGrantType); + + } elseif ($grant_type == 'password') { + $config = [ + 'username' => $username, + 'password' => $password, + 'client_id' => $client_id, + 'client_secret' => $client_secret + ]; + $grantType = new PasswordCredentials($oauth2Client, $config); + $refreshTokenGrantType = new RefreshToken($oauth2Client, $config); + $this->oauth2Plugin = new Oauth2Plugin($grantType, $refreshTokenGrantType); + } + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/src/config/config.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/src/config/config.php b/sdks/other/php5/apache-usergrid/src/config/config.php new file mode 100644 index 0000000..75a886f --- /dev/null +++ b/sdks/other/php5/apache-usergrid/src/config/config.php @@ -0,0 +1,53 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +return [ + + 'usergrid' => [ + + 'url' => 'https://api.usergrid.com', + 'version' => '1.0.0', + 'orgName' => null, + 'appName' => null, + 'manifestPath' => null, + //its better not to set the real values here if using laravel set them in a .env file or + // if your not using Laravel set them as environment variable and include them here using $_ENV global. + // so that way you can be sure not to commit privates ID to a public repo + 'clientId' => null, + 'clientSecret' => null, + 'username' => null, + 'password' => null, + /** + * The Auth Type setting is the Oauth 2 end point you want to get the OAuth 2 + * Token from. You have two options here one is 'application' the other is 'organization' + * + * organization will get the the token from http://example.com/management using client_credentials or password grant type + * application will get the token from http://example.com/managment/org_name/app_name using client_credentials or password grant type + */ + 'auth_type' => 'organization', + /** The Grant Type to use + * + * This has to be set to one of the 2 grant types that Apache Usergrid + * supports which at the moment is client_credentials or password but at + * 2 level organization or application + */ + 'grant_type' => 'client_credentials', + /** + * if you want to manage your own auth flow by calling the token api and setting the token your self just set this to false + * */ + 'enable_oauth2_plugin' => true + ] +]; http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/ApplicationTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/ApplicationTest.php b/sdks/other/php5/apache-usergrid/tests/Api/ApplicationTest.php new file mode 100644 index 0000000..d25a205 --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/ApplicationTest.php @@ -0,0 +1,72 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api; + + +use Apache\Usergrid\Api\Exception\UsergridException; +use PHPUnit_Framework_TestCase; + +/** + * Class ApplicationTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class ApplicationTest extends PHPUnit_Framework_TestCase +{ + + /** + * Usergrid client + * + * @var Usergrid $usergrid + */ + protected $usergrid; + + protected $config; + + /** + * + */ + public function setUp() + { + $this->usergrid = $GLOBALS['usergrid']; + } + + /** + * @test + * @group internet + */ + public function it_can_get_entity() + { + + $error = null; + + try { + $this->usergrid->application()->EntityGet(['collection' => 'users']); + } catch (UsergridException $e) { + $error = $e; + } + + $this->assertNull($error, 'Exception should be null'); + } + + +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/AttributeTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/AttributeTest.php b/sdks/other/php5/apache-usergrid/tests/Api/AttributeTest.php new file mode 100644 index 0000000..cc1f29e --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/AttributeTest.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api; + + +use PHPUnit_Framework_TestCase; + +/** + * Class AttributeTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class AttributeTest extends PHPUnit_Framework_TestCase +{ + /** @var Usergrid Api Client */ + protected $usergrid; + + + /** + * Setup resources and dependencies + * + * @return void + */ + public function setup() + { + $this->usergrid = $GLOBALS['usergrid']; + } + + /** + * @test + * @group internet + */ + public function it_should_have_attribute() + { + $this->assertTrue(method_exists('Apache\Usergrid\Api\Models\User', 'deviceAttribute'), + 'Class does not have method Attribute Method' + ); + } +} + \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/Exception/BadRequestExceptionTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/Exception/BadRequestExceptionTest.php b/sdks/other/php5/apache-usergrid/tests/Api/Exception/BadRequestExceptionTest.php new file mode 100644 index 0000000..b716e3d --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/Exception/BadRequestExceptionTest.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api\Exception; + +use Apache\Usergrid\Api\Exception\BadRequestException; +use Guzzle\Http\Message\Response; +use PHPUnit_Framework_TestCase; + +/** + * Class BadRequestExceptionTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class BadRequestExceptionTest extends PHPUnit_Framework_TestCase +{ + + /** @test */ + public function it_can_create_the_exception() + { + $command = $this->getMock('Guzzle\Service\Command\CommandInterface'); + $command + ->expects($this->once()) + ->method('getRequest') + ->will($this->returnValue( + $this->getMock('Guzzle\Http\Message\Request', [], [], '', false) + )); + + $response = new Response(400); + $response->setBody(''); + + /** @noinspection PhpParamsInspection */ + $exception = BadRequestException::fromCommand($command, $response); + + $this->assertInstanceOf( + 'Apache\Usergrid\Api\Exception\BadRequestException', + $exception + ); + } + +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/Exception/InvalidIdExceptionTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/Exception/InvalidIdExceptionTest.php b/sdks/other/php5/apache-usergrid/tests/Api/Exception/InvalidIdExceptionTest.php new file mode 100644 index 0000000..b74aa64 --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/Exception/InvalidIdExceptionTest.php @@ -0,0 +1,58 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api\Exception; + +use Apache\Usergrid\Api\Exception\InvalidIdException; +use Guzzle\Http\Message\Response; +use PHPUnit_Framework_TestCase; + +/** + * Class InvalidIdExceptionTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class InvalidIdExceptionTest extends PHPUnit_Framework_TestCase +{ + /** @test */ + public function it_can_create_the_exception() + { + $command = $this->getMock('Guzzle\Service\Command\CommandInterface'); + $command + ->expects($this->once()) + ->method('getRequest') + ->will($this->returnValue( + $this->getMock('Guzzle\Http\Message\Request', [], [], '', false) + )); + + $response = new Response(400); + $response->setBody(''); + + /** @noinspection PhpParamsInspection */ + $exception = InvalidIdException::fromCommand($command, $response); + + $this->assertInstanceOf( + 'Apache\Usergrid\Api\Exception\InvalidIdException', + $exception + ); + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/Exception/NotFoundExceptionTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/Exception/NotFoundExceptionTest.php b/sdks/other/php5/apache-usergrid/tests/Api/Exception/NotFoundExceptionTest.php new file mode 100644 index 0000000..c264751 --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/Exception/NotFoundExceptionTest.php @@ -0,0 +1,57 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api\Exception; + +use Apache\Usergrid\Api\Exception\NotFoundException; +use Guzzle\Http\Message\Response; +use PHPUnit_Framework_TestCase; + +/** + * Class UnauthorizedExceptionTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class NotFoundExceptionTest extends PHPUnit_Framework_TestCase +{ + /** @test */ + public function it_can_create_the_exception() + { + $command = $this->getMock('Guzzle\Service\Command\CommandInterface'); + $command + ->expects($this->once()) + ->method('getRequest') + ->will($this->returnValue( + $this->getMock('Guzzle\Http\Message\Request', [], [], '', false) + )); + + $response = new Response(404); + $response->setBody(''); + + /** @noinspection PhpParamsInspection */ + $exception = NotFoundException::fromCommand($command, $response); + + $this->assertInstanceOf( + 'Apache\Usergrid\Api\Exception\NotFoundException', + $exception + ); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/Exception/ServerErrorExceptionTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/Exception/ServerErrorExceptionTest.php b/sdks/other/php5/apache-usergrid/tests/Api/Exception/ServerErrorExceptionTest.php new file mode 100644 index 0000000..514288f --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/Exception/ServerErrorExceptionTest.php @@ -0,0 +1,58 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api\Exception; + +use Apache\Usergrid\Api\Exception\ServerErrorException; +use Guzzle\Http\Message\Response; +use PHPUnit_Framework_TestCase; + +/** + * Class ServerErrorException + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class ServerErrorExceptionTest extends PHPUnit_Framework_TestCase +{ + /** @test */ + public function it_can_create_the_exception() + { + $command = $this->getMock('Guzzle\Service\Command\CommandInterface'); + $command + ->expects($this->once()) + ->method('getRequest') + ->will($this->returnValue( + $this->getMock('Guzzle\Http\Message\Request', [], [], '', false) + )); + + $response = new Response(400); + $response->setBody(''); + + /** @noinspection PhpParamsInspection */ + $exception = ServerErrorException::fromCommand($command, $response); + + $this->assertInstanceOf( + 'Apache\Usergrid\Api\Exception\ServerErrorException', + $exception + ); + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/Exception/UnauthorizedExceptionTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/Exception/UnauthorizedExceptionTest.php b/sdks/other/php5/apache-usergrid/tests/Api/Exception/UnauthorizedExceptionTest.php new file mode 100644 index 0000000..889e7de --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/Exception/UnauthorizedExceptionTest.php @@ -0,0 +1,58 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api\Exception; + + +use Apache\Usergrid\Api\Exception\UnauthorizedException; +use Guzzle\Http\Message\Response; +use PHPUnit_Framework_TestCase; + +/** + * Class UnauthorizedExceptionTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class UnauthorizedExceptionTest extends PHPUnit_Framework_TestCase +{ + /** @test */ + public function it_can_create_the_exception() + { + $command = $this->getMock('Guzzle\Service\Command\CommandInterface'); + $command + ->expects($this->once()) + ->method('getRequest') + ->will($this->returnValue( + $this->getMock('Guzzle\Http\Message\Request', [], [], '', false) + )); + + $response = new Response(401); + $response->setBody(''); + + /** @noinspection PhpParamsInspection */ + $exception = UnauthorizedException::fromCommand($command, $response); + + $this->assertInstanceOf( + 'Apache\Usergrid\Api\Exception\UnauthorizedException', + $exception + ); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/Filters/BooleanTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/Filters/BooleanTest.php b/sdks/other/php5/apache-usergrid/tests/Api/Filters/BooleanTest.php new file mode 100644 index 0000000..1550a55 --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/Filters/BooleanTest.php @@ -0,0 +1,45 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api\Filters; + + +use Apache\Usergrid\Api\Filters\Boolean; +use PHPUnit_Framework_TestCase; + +/** + * Class BooleanTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class BooleanTest extends PHPUnit_Framework_TestCase +{ + + /** @test */ + public function it_can_convert_booleans() + { + $this->assertEquals('true', Boolean::convert(1)); + $this->assertEquals('true', Boolean::convert(true)); + + $this->assertEquals('false', Boolean::convert(0)); + $this->assertEquals('false', Boolean::convert(false)); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/Filters/DateTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/Filters/DateTest.php b/sdks/other/php5/apache-usergrid/tests/Api/Filters/DateTest.php new file mode 100644 index 0000000..13d37f6 --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/Filters/DateTest.php @@ -0,0 +1,41 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api\Filters; + + +use Apache\Usergrid\Api\Filters\Date; +use PHPUnit_Framework_TestCase; + +/** + * Class DateTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class DateTest extends PHPUnit_Framework_TestCase +{ + /** @test */ + public function it_can_convert_dates() + { + + $this->assertEquals('Tue, Oct 14, 2014 3:55 AM', Date::convert(1413258923819)); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/ManagementTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/ManagementTest.php b/sdks/other/php5/apache-usergrid/tests/Api/ManagementTest.php new file mode 100644 index 0000000..46ea21c --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/ManagementTest.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api; + + +use Apache\Usergrid\Api\Exception\UsergridException; +use PHPUnit_Framework_TestCase; + +/** + * Class ManagementTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class ManagementTest extends PHPUnit_Framework_TestCase +{ + protected $usergrid; + protected $config; + + public function setUp() + { + $this->usergrid = $GLOBALS['usergrid']; + } + + /** + * @test + * @group internet + */ + public function it_can_make_management_call() + { + $error = null; + + try { + $this->usergrid->management()->OrgAppsGet(); + } catch (UsergridException $e) { + $error = $e; + } + + $this->assertNull($error, "Should be no exception if manifest files exits and sdk can make management calls"); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/QueryAggregatorTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/QueryAggregatorTest.php b/sdks/other/php5/apache-usergrid/tests/Api/QueryAggregatorTest.php new file mode 100644 index 0000000..eaa7b0b --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/QueryAggregatorTest.php @@ -0,0 +1,40 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api; + + +use PHPUnit_Framework_TestCase; + +/** + * Class QueryAggregatorTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class QueryAggregatorTest extends PHPUnit_Framework_TestCase +{ + + /** @test */ + public function it_can_test_the_aggregate_method() + { + } + +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Api/UsergridTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Api/UsergridTest.php b/sdks/other/php5/apache-usergrid/tests/Api/UsergridTest.php new file mode 100644 index 0000000..0c7a340 --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Api/UsergridTest.php @@ -0,0 +1,153 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace Apache\Usergrid\Tests\Api; + +use Apache\Usergrid\Api\Exception\UnauthorizedException; +use PHPUnit_Framework_TestCase; + +/** + * Class UsergridTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class UsergridTest extends PHPUnit_Framework_TestCase +{ + + /** @var Usergrid Api Client */ + protected $usergrid; + + protected $config; + + /** + * Setup resources and dependencies + * + * @return void + */ + public function setup() + { + $this->usergrid = $GLOBALS['usergrid']; + } + + /** + * @test + * @group internet + */ + public function it_can_retrieve_oauth2_token() + { + $error = null; + + try { + $this->usergrid->application()->EntityGet(['collection' => 'roles']); + } catch (UnauthorizedException $e) { + $error = $e; + } + + $this->assertNull($error, 'Exception should be null if authorized'); + } + + /** @test */ + public function it_can_set_the_oauth2_token() + { + $this->usergrid->setToken('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'); + + $this->assertEquals('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', $this->usergrid->getToken()); + } + + /** @test */ + public function it_can_retrieve_user_agent() + { + + $this->assertEquals('BaaS-Usergrid/1.0.0', $this->usergrid->getUserAgent()); + } + + /** @test */ + public function it_can_set_the_user_agent() + { + + $this->usergrid->setUserAgent('Foo/Bar'); + + $this->assertEquals('Foo/Bar', $this->usergrid->getUserAgent()); + } + + /** @test */ + public function it_can_retrieve_the_manifest_path() + { + + $this->assertEquals($this->usergrid->getManifestPath(), $this->usergrid->getManifestPath()); + } + + /** @test */ + public function it_can_set_the_manifest_path() + { + $this->usergrid->setManifestPath('/usr/foo/bar'); + + $this->assertEquals('/usr/foo/bar', $this->usergrid->getManifestPath()); + } + + /** @test */ + public function it_can_retrieve_api_version() + { + $this->assertEquals('1.0.1', $this->usergrid->getVersion()); + } + + /** @test */ + public function it_can_set_api_version() + { + $this->usergrid->setVersion('1.0.1'); + + $this->assertEquals('1.0.1', $this->usergrid->getVersion()); + } + + + /** @test */ + public function it_can_retrieve_the_client_header() + { + $headers = $this->usergrid->getHeaders(); + + $expected = [ + 'Usergrid-Version' => '1.0.1', + 'Authorization' => 'Bearer ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' + ]; + + $this->assertEquals($headers, $expected); + } + + /** @test */ + public function it_can_set_client_headers() + { + $this->usergrid->setHeaders([ + 'some-header' => 'foo-bar', + ]); + + $headers = $this->usergrid->getHeaders(); + + $expected = [ + 'Usergrid-Version' => '1.0.1', + 'Authorization' => 'Bearer ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', + 'some-header' => 'foo-bar', + ]; + + $this->assertEquals($headers, $expected); + } + + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/Laravel/Facades/UsergridTest.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/Laravel/Facades/UsergridTest.php b/sdks/other/php5/apache-usergrid/tests/Laravel/Facades/UsergridTest.php new file mode 100644 index 0000000..3362bfc --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/Laravel/Facades/UsergridTest.php @@ -0,0 +1,53 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ +namespace Apache\Usergrid\Tests\Laravel\Facades; + +use PHPUnit_Framework_TestCase; +use ReflectionClass; + +/** + * Class UsergridTest + * + * @package Apache/Usergrid + * @version 1.0.0 + * @author Jason Kristian <jasonkrist...@gmail.com> + * @license Apache License, Version 2.0 + * @copyright (c) 2008-2014, Baas Platform Pty. Ltd + * @link http://baas-platform.com + */ +class UsergridTest extends PHPUnit_Framework_TestCase +{ + /** @test */ + public function it_can_test_it_is_a_facade() + { + $facade = new ReflectionClass('Illuminate\Support\Facades\Facade'); + + $reflection = new ReflectionClass('Apache\Usergrid\Laravel\Facades\Usergrid'); + + $this->assertTrue($reflection->isSubclassOf($facade)); + } + + /** @test */ + public function it_can_test_it_is_a_facade_accessor() + { + $reflection = new ReflectionClass('Apache\Usergrid\Laravel\Facades\Usergrid'); + + $method = $reflection->getMethod('getFacadeAccessor'); + $method->setAccessible(true); + + + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/php5/apache-usergrid/tests/bootstrap.php ---------------------------------------------------------------------- diff --git a/sdks/other/php5/apache-usergrid/tests/bootstrap.php b/sdks/other/php5/apache-usergrid/tests/bootstrap.php new file mode 100644 index 0000000..edc11d1 --- /dev/null +++ b/sdks/other/php5/apache-usergrid/tests/bootstrap.php @@ -0,0 +1,61 @@ +<?php +/** + * Copyright 2010-2014 baas-platform.com, Pty Ltd. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +include('vendor/autoload.php'); + +use Apache\Usergrid\Native\UsergridBootstrapper; + +$config = [ + + 'usergrid' => [ + + 'url' => 'https://api.usergrid.com', + 'version' => '1.0.1', + 'orgName' => null, + 'appName' => null, + 'manifestPath' => null, + //its better not to set the real values here if using laravel set them in a .env file or + // if your not using Laravel set them as environment variable and include them here using $_ENV global. + // so that way you can be sure not to commit privates ID to a public repo + 'clientId' => null, + 'clientSecret' => null, + 'username' => null, + 'password' => null, + /** + * The Auth Type setting is the Oauth 2 end point you want to get the OAuth 2 + * Token from. You have two options here one is 'application' the other is 'organization' + * + * organization will get the the token from http://example.com/management using client_credentials or password grant type + * application will get the token from http://example.com/managment/org_name/app_name using client_credentials or password grant type + */ + 'auth_type' => 'organization', + /** The Grant Type to use + * + * This has to be set to one of the 2 grant types that Apache Usergrid + * supports which at the moment is client_credentials or password but at + * 2 level organization or application + */ + 'grant_type' => 'client_credentials', + /** + * if you want to manage your own auth flow by calling the token api and setting the token your self just set this to false + * */ + 'enable_oauth2_plugin' => true + ] +]; + +$boot = new UsergridBootstrapper($config); +$usergrid = $boot->createUsergrid(); + http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/ruby-on-rails/Gemfile ---------------------------------------------------------------------- diff --git a/sdks/other/ruby-on-rails/Gemfile b/sdks/other/ruby-on-rails/Gemfile new file mode 100644 index 0000000..60aff2b --- /dev/null +++ b/sdks/other/ruby-on-rails/Gemfile @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +source 'https://rubygems.org' + +# Specify your gem's dependencies in usergrid_ironhorse.gemspec +gemspec http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/ruby-on-rails/LICENSE.txt ---------------------------------------------------------------------- diff --git a/sdks/other/ruby-on-rails/LICENSE.txt b/sdks/other/ruby-on-rails/LICENSE.txt new file mode 100644 index 0000000..ae1e83e --- /dev/null +++ b/sdks/other/ruby-on-rails/LICENSE.txt @@ -0,0 +1,14 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/ruby-on-rails/README.md ---------------------------------------------------------------------- diff --git a/sdks/other/ruby-on-rails/README.md b/sdks/other/ruby-on-rails/README.md new file mode 100644 index 0000000..dce855b --- /dev/null +++ b/sdks/other/ruby-on-rails/README.md @@ -0,0 +1,212 @@ +# Apache Usergrid_ironhorse + +Usergrid_ironhorse is based on Usergrid_iron and enables Ruby or Rails applications +native Rails-style access to Apigee's App Services (aka Usergrid) REST API. + +## Compatibility + +**Usergrid_ironhorse is currently only compatible with Ruby on Rails 3.2.** + +Thus, if you are using Rails 4.x, you must use Usergrid_iron (the low-level API for Ruby). +Alternatively, we would welcome your contributions to make Usergrid_ironhorse compatible with Rails 4.x. Thanks! + +## Installation + +Add this line to your application's Gemfile: + + gem 'usergrid_ironhorse' + +And then execute: + + $ bundle + +Or install it yourself as: + + $ gem install usergrid_ironhorse + + +## Usage + +### Not familiar with Usergrid's App Services? + +#### It's great stuff! Check it out, here: + + Docs: <https://usergrid.apache.org/docs/> + Open source: <https://github.com/usergrid/usergrid/> + +### Getting started with the Usergrid_ironhorse SDK is super simple! + +#### Setup + +* Add 'gem usergrid_ironhorse' to your Gemfile +* Create a 'config/usergrid.yml' file that looks something like this (the +auth_token is your application token): + +``` +development: + application_url: http://localhost:8080/my-organization/my-application + client_id: YXA6BVYasLdNEeKBd1A2yYstg + client_secret: YXA60Dnbzaxg1ObkE8ffsIxsGzsSo8 + require_login: false + +test: + application_url: http://localhost:8080/my-organization/my-application + client_id: YXA6BVYasLdNEeKBd1A2yYstg + client_secret: YXA60Dnbzaxg1ObkE8ffsIxsGzsSo8 + require_login: false + +production: + application_url: http://api.usergrid.com/my-organization/my-application + client_id: YXA6BVYasLdNEeKBd1A2yYstg + client_secret: YXA60Dnbzaxg1ObkE8ffsIxsGzsSo8 + require_login: false +``` + +#### Get going! + +* Subclass Usergrid::Ironhorse::Base for your models. +Your models will automatically be stored in a collection according to the name of your +class as defined by Rails' ActiveModel::Naming module. (Which you may override by +implementing model_name if desired.) + +``` +class Developer < Usergrid::Ironhorse::Base + validates :name, :presence => true # Yes, of course you can use validation + +end +``` + +* Now just use the Rails methods you're already familiar with: + +``` + + dev = Developer.new language: 'Ruby' + dev.valid? # nope! + dev.errors # {:name=>["can't be blank"]} + dev.name = 'Scott' + dev.save! + + dev = Developer.find_or_create_by_name 'Scott' + dev.favorite_color = 'green' # assign new attributes automatically + + dev = Developer.find_by_name 'Scott' +``` + +* BTW: If you need to do management tasks, wrapping the work in an as_admin block +will use the auth_token from your settings: + +``` +User.as_admin do + # do protected task +end +``` + + +#### (Optional) Need to have user-specific logins to UserGrid? + +* Create a User model and subclass `Usergrid::Ironhorse::Base` and `extend +Usergrid::Ironhorse::UserContext` like so: + +``` +class User < Usergrid::Ironhorse::Base + extend Usergrid::Ironhorse::UserContext + ... +end +``` + +* Set up your authentication + * Use `User.authenticate(username, password, session)` to login. + * Use `User.clear_authentication(session)` to log out. +* Propogate the authentication in your ApplicationController: + +``` +before_filter :set_user_context +def set_user_context + User.set_context session +end +``` + +* Optionally, if you need to access the User from your view, you may add something +like the following to your ApplicationController: + +``` +helper_method :current_user +def current_user + User.current_user +end +``` + +## Contributing + +We welcome your enhancements! + +1. Fork it +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Write some broken rspecs. +4. Fix the rspecs with your new code. +3. Commit your changes (`git commit -am 'Added some feature'`) +4. Push your changes to the upstream branch (`git push origin my-new-feature`) +5. Create new Pull Request + +We're shooting for 100% rspec coverage, so keep that in mind! + +In order to run the tests, check out the Usergrid open source project +(https://github.com/usergrid/usergrid/), build, and launch it locally. + +(Note: If you change your local Usergrid settings from the default, be sure to update +usergrid_ironhorse/spec/spec_settings.yaml to match.) + + +## Release notes + +### 0.1.1 +* New Features + 1. Now prefer application client_id and client_secret (instead of auth_token) in usergrid.yml. + +### 0.1.0 +* New Features + 1. next_page() added to return the next page of results from the server. An example of this used in conjunction + with to_a() is in base_spec.rb (see "should be able to page through results"). +* Incompatible changes + 1. each() iteration will now transparently cross page boundaries (as generally expected by Rails users). + You may use limit(n) to restrict the result set, but note that limit will retrieve the number of entities + specified as a single batch (no paging). + +### 0.0.5 +* New Features + 1. support MassAssignmentSecurity (attr_accessible & attr_protected) + +### 0.0.4 +* New Features + 1. add require_login to config (with ability to skip individual logins) + +### 0.0.3 +* Internal + 1. Improve authentication and user propagation + +### 0.0.2 +* New Features + 1. Authentication and user propagation features + +### 0.0.1 +* Initial commit + 1. Support for most ActiveModel stuff including Validations + 1. No scoping support + + +## License +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +the ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/ruby-on-rails/Rakefile ---------------------------------------------------------------------- diff --git a/sdks/other/ruby-on-rails/Rakefile b/sdks/other/ruby-on-rails/Rakefile new file mode 100644 index 0000000..632aa48 --- /dev/null +++ b/sdks/other/ruby-on-rails/Rakefile @@ -0,0 +1,22 @@ +#!/usr/bin/env rake +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require "bundler/gem_tasks" + +require 'rspec/core/rake_task' +RSpec::Core::RakeTask.new(:spec) + +RSpec::Core::RakeTask.new("spec:coverage") http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/ruby-on-rails/lib/extensions/hash.rb ---------------------------------------------------------------------- diff --git a/sdks/other/ruby-on-rails/lib/extensions/hash.rb b/sdks/other/ruby-on-rails/lib/extensions/hash.rb new file mode 100644 index 0000000..a82062a --- /dev/null +++ b/sdks/other/ruby-on-rails/lib/extensions/hash.rb @@ -0,0 +1,23 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +class Hash + + def nested_under_indifferent_access + self + end + +end http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/ruby-on-rails/lib/extensions/resource.rb ---------------------------------------------------------------------- diff --git a/sdks/other/ruby-on-rails/lib/extensions/resource.rb b/sdks/other/ruby-on-rails/lib/extensions/resource.rb new file mode 100644 index 0000000..b858b92 --- /dev/null +++ b/sdks/other/ruby-on-rails/lib/extensions/resource.rb @@ -0,0 +1,66 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# overrides methods dealing with auth_token to operate on a thread basis +module Usergrid + class Resource + + def options + options = @options.clone + require_login = Ironhorse::Base.settings[:require_login] != false + if require_login + auth_token = Thread.current[:usergrid_auth_token] + else + unless Ironhorse::Base.settings[:auth_token] + as_admin {} + end + auth_token = Ironhorse::Base.settings[:auth_token] + end + options[:headers].delete :Authorization + options[:headers][:Authorization] = "Bearer #{auth_token}" if auth_token + options + end + + def as_admin(&block) + save_auth_token = Thread.current[:usergrid_auth_token] + begin + unless Ironhorse::Base.settings[:auth_token] + resource = RestClient::Resource.new Ironhorse::Base.settings[:application_url] + response = resource['token'].post grant_type: 'client_credentials', client_id: Ironhorse::Base.settings[:client_id], client_secret: Ironhorse::Base.settings[:client_secret] + Ironhorse::Base.settings[:auth_token] = MultiJson.load(response)['access_token'] + end + Thread.current[:usergrid_auth_token] = Ironhorse::Base.settings[:auth_token] + yield block + ensure + Thread.current[:usergrid_auth_token] = save_auth_token + end + end + + # gets user token and automatically set auth header for future requests on this Thread + # precondition: resource must already be set to the correct context (application or management) + def login(username, password) + params = { grant_type: "password", username: username, password: password } + response = self['token'].get({ params: params }) + user_uuid = response.data['user']['uuid'] + user_access_token = response.data['access_token'] + Thread.current[:usergrid_user_id] = user_uuid + Thread.current[:usergrid_auth_token] = user_access_token + @current_user = self["/users/#{user_uuid}"].get.entity + response + end + + end +end http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/ruby-on-rails/lib/usergrid_ironhorse.rb ---------------------------------------------------------------------- diff --git a/sdks/other/ruby-on-rails/lib/usergrid_ironhorse.rb b/sdks/other/ruby-on-rails/lib/usergrid_ironhorse.rb new file mode 100644 index 0000000..0dde1d1 --- /dev/null +++ b/sdks/other/ruby-on-rails/lib/usergrid_ironhorse.rb @@ -0,0 +1,39 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require 'logger' +require 'active_model' +require 'rest-client' +require 'active_support' +require 'usergrid_iron' +require 'active_record/errors' + +module Usergrid + module Ironhorse + + Dir[Pathname.new(File.dirname(__FILE__)).join("extensions/**/*.rb")].each { |f| require f } + + USERGRID_PATH = File.join File.dirname(__FILE__), 'usergrid_ironhorse' + + def self.usergrid_path *path + File.join USERGRID_PATH, *path + end + + require usergrid_path('base') + require usergrid_path('query') + + autoload :UserContext, usergrid_path('user_context') + end +end http://git-wip-us.apache.org/repos/asf/usergrid/blob/867060fa/sdks/other/ruby-on-rails/lib/usergrid_ironhorse/base.rb ---------------------------------------------------------------------- diff --git a/sdks/other/ruby-on-rails/lib/usergrid_ironhorse/base.rb b/sdks/other/ruby-on-rails/lib/usergrid_ironhorse/base.rb new file mode 100644 index 0000000..aa6f4d9 --- /dev/null +++ b/sdks/other/ruby-on-rails/lib/usergrid_ironhorse/base.rb @@ -0,0 +1,370 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require 'active_record/validations' +require 'active_record/errors' +require 'active_record/callbacks' + +module Usergrid + module Ironhorse + + class Base + include ActiveModel::AttributeMethods + include ActiveModel::Conversion + include ActiveModel::Validations + include ActiveModel::Dirty + include ActiveModel::Serialization + include ActiveModel::MassAssignmentSecurity + extend ActiveModel::Naming + extend ActiveModel::Callbacks + + RESERVED_ATTRIBUTES = %w(metadata created modified uuid type uri) + + define_model_callbacks :create, :destroy, :save, :update + + # todo: determine the subset to support... + # unsupported: :group, :joins, :preload, :eager_load, :includes, :from, :lock, + # :having, :create_with, :uniq, :references, :none, :count, + # :average, :minimum, :maximum, :sum, :calculate, :ids + # :find_each, :find_in_batches, :offset, :readonly + + #delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :to => :all + #delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :all + #delegate :find_by, :find_by!, :to => :all + #delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :all + #delegate :find_each, :find_in_batches, :to => :all + #delegate :select, :group, :order, :except, :reorder, :limit, :offset, + # :where, :preload, :eager_load, :includes, :from, :lock, :readonly, + # :having, :create_with, :uniq, :references, :none, :to => :all + #delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :ids, :to => :all + + @@settings ||= nil + + attr_accessor :attributes + + HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess + RecordNotSaved = ActiveRecord::RecordNotSaved + + def initialize(attrs=nil) + @attributes = HashWithIndifferentAccess.new + assign_attributes attrs if attrs + end + + def self.configure!(application_url, auth_token) + @@settings = HashWithIndifferentAccess.new application_url: application_url, auth_token: auth_token + end + + def self.settings + return @@settings if @@settings + path = "config/usergrid.yml" + environment = defined?(Rails) && Rails.respond_to?(:env) ? Rails.env : ENV['RACK_ENV'] + @@settings = HashWithIndifferentAccess.new YAML.load(ERB.new(File.new(path).read).result)[environment] + end + + # forward to all + def self.method_missing(method, *args, &block) + all.send method, *args, &block + end + + # forward to all + def method_missing(method, *args, &block) + if args.size == 0 + attributes[method] + elsif args.size == 1 && method[-1] == '=' + attr = method[0..-2] + if attributes[attr] != args[0] + attribute_will_change!(attr) + attributes[attr] = args[0] + end + else + all.send method, *args, &block + end + end + + # todo: scopes + def self.all + unscoped + end + + #def self.scope(symbol, scope) + # @scopes[symbol] = scope + #end + + #def self.current_scope + # @current_scope ||= default_scope + #end + # + #def self.current_scope=(scope) + # @current_scope = scope + #end + # + #def self.default_scope + # @default_scope ||= unscoped + #end + + def self.unscoped + Query.new(self) + end + + def self.create(attributes=nil, options=nil, &block) + if attributes.is_a?(Array) + attributes.collect { |attr| create(attr, options, &block) } + else + object = new(attributes, &block) + object.save + object + end + end + + def self.create!(attributes=nil, options=nil, &block) + if attributes.is_a?(Array) + attributes.collect {|attr| create!(attr, options, &block)} + else + object = new(attributes) + yield(object) if block_given? + object.save! + object + end + end + + def self.class_attributes + @class_attributes ||= {} + end + + # Returns true if the record is persisted, i.e. it's not a new record and it was + # not destroyed, otherwise returns false. + def persisted? + !(new_record? || destroyed?) + end + + def new_record? + !self.uuid + end + + def self.group + model_name.plural.downcase + end + + # Creates a Usergrid::Resource + def self.resource + app = Usergrid::Application.new settings[:application_url] + #app.auth_token = Thread.current[:usergrid_auth_token] + app[group] + end + + # Saves the model. + # + # If the model is new a record gets created in the database, otherwise + # the existing record gets updated. + # + # By default, save always run validations. If any of them fail the action + # is cancelled and +save+ returns +false+. However, if you supply + # :validate => false, validations are bypassed altogether. See + # ActiveRecord::Validations for more information. + # + # There's a series of callbacks associated with +save+. If any of the + # <tt>before_*</tt> callbacks return +false+ the action is cancelled and + # +save+ returns +false+. See ActiveRecord::Callbacks for further + # details. + def save + begin + create_or_update + rescue ActiveRecord::RecordInvalid + false + end + end + + # Saves the model. + # + # If the model is new a record gets created in the database, otherwise + # the existing record gets updated. + # + # With <tt>save!</tt> validations always run. If any of them fail + # ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations + # for more information. + # + # There's a series of callbacks associated with <tt>save!</tt>. If any of + # the <tt>before_*</tt> callbacks return +false+ the action is cancelled + # and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See + # ActiveRecord::Callbacks for further details. + def save! + create_or_update or raise RecordNotSaved + end + + # Deletes the record in the database and freezes this instance to + # reflect that no changes should be made (since they can't be + # persisted). Returns the frozen instance. + # + # The row is simply removed with a +DELETE+ statement on the + # record's primary key, and no callbacks are executed. + # + # To enforce the object's +before_destroy+ and +after_destroy+ + # callbacks, Observer methods, or any <tt>:dependent</tt> association + # options, use <tt>#destroy</tt>. + def delete + self.class.delete(id) if persisted? + @destroyed = true + freeze + end + + # Deletes the record in the database and freezes this instance to reflect + # that no changes should be made (since they can't be persisted). + # + # There's a series of callbacks associated with <tt>destroy</tt>. If + # the <tt>before_destroy</tt> callback return +false+ the action is cancelled + # and <tt>destroy</tt> returns +false+. See + # ActiveRecord::Callbacks for further details. + def destroy + raise ReadOnlyRecord if readonly? + # todo: callbacks? + instance_resource.delete if persisted? + @destroyed = true + freeze + end + + # Deletes the record in the database and freezes this instance to reflect + # that no changes should be made (since they can't be persisted). + # + # There's a series of callbacks associated with <tt>destroy!</tt>. If + # the <tt>before_destroy</tt> callback return +false+ the action is cancelled + # and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See + # ActiveRecord::Callbacks for further details. + def destroy! + destroy || raise(ActiveRecord::RecordNotDestroyed) + end + + # Returns true if this object has been destroyed, otherwise returns false. + def destroyed? + !!@destroyed + end + + # Reloads the attributes of this object from the database. + def reload + return false if !persisted? + fresh_object = self.class.find(id) + refresh_data fresh_object.instance_variable_get('@attributes') + self + end + + # Updates the attributes of the model from the passed-in hash and saves the + # record, all wrapped in a transaction. If the object is invalid, the saving + # will fail and false will be returned. + def update_attributes(attributes) + assign_attributes attributes + save + end + + # Updates its receiver just like +update_attributes+ but calls <tt>save!</tt> instead + # of +save+, so an exception is raised if the record is invalid. + def update_attributes!(attributes) + assign_attributes attributes + save! + end + + # Note that whenever you include ActiveModel::AttributeMethods in your class, + # it requires you to implement an +attributes+ method which returns a hash + # with each attribute name in your model as hash key and the attribute value as + # hash value. + # + # Hash keys must be strings. + def attributes + @attributes ||= self.class.class_attributes.clone + end + + def id; self.uuid end + def created_at; self.created end + def updated_at; self.modified end + + + protected + + + def assign_attributes(attrs) + attrs = sanitize_for_mass_assignment(attrs) + attrs.each do |attr,value| + attr = attr.to_s + unless attributes[attr] == value + attribute_will_change!(attr) unless RESERVED_ATTRIBUTES.include? attr + attributes[attr] = value + end + end + end + + def create_or_update + raise ReadOnlyRecord if readonly? + if valid? + run_callbacks :save do + return new_record? ? do_create : do_update + end + end + false + end + + def do_create + group_resource.post(unsaved_attributes) do |resp, req, res, &block| + if resp.code.to_s == "200" || resp.code.to_s == "201" + refresh_data resp.entity_data + return true + else + errors.add(resp.code.to_s, resp) + return false + end + end + end + + def do_update + return false unless changed? + + instance_resource.put(unsaved_attributes) do |resp, req, res, &block| + if resp.code.to_s == "200" || resp.code.to_s == "201" + refresh_data resp.entity_data + return true + else + errors.add(resp.code, resp) + return false + end + end + end + + def unsaved_attributes + HashWithIndifferentAccess[changed.collect {|k| [k, attributes[k]]}] + end + + def group_resource + self.class.resource + end + + def instance_resource + self.class.resource["#{self.id}"] + end + + def refresh_data(entity_data) + @previously_changed = changes + @changed_attributes.clear + @attributes = HashWithIndifferentAccess.new entity_data + end + + def attribute_will_change!(attr) + begin + value = __send__(attr) + value = value.duplicable? ? value.clone : value + rescue TypeError, NoMethodError + end + + changed_attributes[attr] = value unless changed_attributes.include?(attr) + end + end + end +end