Skip to content

Commit

Permalink
Merge pull request #322 from Fruitware/bitrix24-service
Browse files Browse the repository at this point in the history
Add bitrix24 service
  • Loading branch information
David Desberg authored and David Desberg committed Sep 11, 2015
2 parents b617831 + da95262 commit 26fdd6b
Show file tree
Hide file tree
Showing 5 changed files with 357 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ Included service implementations
- OAuth2
- Amazon
- BitLy
- Bitrix24
- Box
- Dailymotion
- DeviantArt
Expand Down
56 changes: 56 additions & 0 deletions examples/bitrix24.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

/**
* Example of retrieving an authentication token of the Bitrix24 service
*
* PHP version 5.4
*
* @author David Desberg <david@daviddesberg.com>
* @author Pieter Hordijk <info@pieterhordijk.com>
* @copyright Copyright (c) 2012 The authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/

use OAuth\OAuth2\Service\GitHub;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;

/**
* Bootstrap the example
*/
require_once __DIR__ . '/bootstrap.php';

// Session storage
$storage = new Session();

// Setup the credentials for the requests
$credentials = new Credentials(
$servicesCredentials['bitrix24']['key'],
$servicesCredentials['bitrix24']['secret'],
$currentUri->getAbsoluteUri()
);

// Instantiate the GitHub service using the credentials, http client and storage mechanism for the token

$yourDomain = new \OAuth\Common\Http\Uri\Uri('https://'.$servicesCredentials['bitrix24']['domain']);
/** @var $bitrix24 \OAuth\OAuth2\Service\Bitrix24 */
$bitrix24 = $serviceFactory->createService('Bitrix24', $credentials, $storage, array('user'), $yourDomain);

if (!empty($_GET['code'])) {
// This was a callback request from bitrix24, get the token
$bitrix24->requestAccessToken($_GET['code']);

$response = json_decode($bitrix24->request('user.current'), true);
$userInfo = $response['result'];

// Show some of the resultant data
echo 'Your email on your bitrix24 account is ' . $userInfo['EMAIL'];

} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') {
$url = $bitrix24->getAuthorizationUri();
header('Location: ' . $url);

} else {
$url = $currentUri->getRelativeUri() . '?go=go';
echo "<a href='$url'>Login with Bitrix24!</a>";
}
4 changes: 4 additions & 0 deletions examples/init.example.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
'key' => '',
'secret' => '',
),
'bitrix24' => array(
'key' => '',
'secret' => '',
),
'box' => array(
'key' => '',
'secret' => '',
Expand Down
118 changes: 118 additions & 0 deletions src/OAuth/OAuth2/Service/Bitrix24.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php

namespace OAuth\OAuth2\Service;

use OAuth\OAuth2\Token\StdOAuth2Token;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\Uri;
use OAuth\Common\Consumer\CredentialsInterface;
use OAuth\Common\Http\Client\ClientInterface;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\Common\Http\Uri\UriInterface;

class Bitrix24 extends AbstractService
{
const SCOPE_DEPARTMENT = 'department';
const SCOPE_CRM = 'crm';
const SCOPE_CALENDAR = 'calendar';
const SCOPE_USER = 'user';
const SCOPE_ENTITY = 'entity';
const SCOPE_TASK = 'task';
const SCOPE_TASKS_EXTENDED = 'tasks_extended';
const SCOPE_IM = 'im';
const SCOPE_LOG = 'log';
const SCOPE_SONET_GROUP = 'sonet_group';

/**
* {@inheritdoc}
*/
public function getAuthorizationEndpoint()
{
return new Uri(sprintf('%s/oauth/authorize/', $this->baseApiUri));
}

/**
* {@inheritdoc}
*/
public function getAccessTokenEndpoint()
{
return new Uri(sprintf('%s/oauth/token/', $this->baseApiUri));
}

/**
* {@inheritdoc}
*/
public function requestAccessToken($code, $state = null)
{
if (null !== $state) {
$this->validateAuthorizationState($state);
}

$responseBody = $this->httpClient->retrieveResponse(
$this->getAccessTokenUri($code),
array(),
$this->getExtraOAuthHeaders(),
'GET'
);

$token = $this->parseAccessTokenResponse($responseBody);
$this->storage->storeAccessToken($this->service(), $token);

return $token;
}

/**
* {@inheritdoc}
*/
public function getAccessTokenUri($code)
{
$parameters = array(
'code' => $code,
'client_id' => $this->credentials->getConsumerId(),
'client_secret' => $this->credentials->getConsumerSecret(),
'redirect_uri' => $this->credentials->getCallbackUrl(),
'grant_type' => 'authorization_code',
'scope' => $this->scopes
);

$parameters['scope'] = implode(' ', $this->scopes);

// Build the url
$url = $this->getAccessTokenEndpoint();
foreach ($parameters as $key => $val) {
$url->addToQuery($key, $val);
}

return $url;
}

/**
* {@inheritdoc}
*/
protected function parseAccessTokenResponse($responseBody)
{
$data = json_decode($responseBody, true);

if (null === $data || !is_array($data)) {
throw new TokenResponseException('Unable to parse response.');
} elseif (isset($data['error'])) {
throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
}

$token = new StdOAuth2Token();
$token->setAccessToken($data['access_token']);
$token->setLifetime($data['expires_in']);

if (isset($data['refresh_token'])) {
$token->setRefreshToken($data['refresh_token']);
unset($data['refresh_token']);
}

unset($data['access_token']);
unset($data['expires_in']);

$token->setExtraParams($data);

return $token;
}
}
178 changes: 178 additions & 0 deletions tests/Unit/OAuth2/Service/Bitrix24.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
<?php

namespace OAuthTest\Unit\OAuth2\Service;

use OAuth\OAuth2\Service\Bitrix24;
use OAuth\Common\Token\TokenInterface;

class Bitrix24Test extends \PHPUnit_Framework_TestCase
{
/**
* @covers OAuth\OAuth2\Service\Bitrix24::__construct
*/
public function testConstructCorrectInstanceWithCustomUri()
{
$service = new Bitrix24(
$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
$this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
array(),
$this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
);

$this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service);
}

/**
* @covers OAuth\OAuth2\Service\Bitrix24::__construct
* @covers OAuth\OAuth2\Service\Bitrix24::getAuthorizationEndpoint
*/
public function testGetAuthorizationEndpoint()
{
$service = new Bitrix24(
$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
$this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
array(),
$this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
);

$this->assertSame('https://bitrix24.com/oauth/authorize/', $service->getAuthorizationEndpoint()->getAbsoluteUri());
}

/**
* @covers OAuth\OAuth2\Service\Bitrix24::__construct
* @covers OAuth\OAuth2\Service\Bitrix24::getAccessTokenEndpoint
*/
public function testGetAccessTokenEndpoint()
{
$service = new Bitrix24(
$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
$this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'),
$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
array(),
$this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
);

$this->assertSame('https://bitrix24.com/oauth/token/', $service->getAccessTokenEndpoint()->getAbsoluteUri());
}

/**
* @covers OAuth\OAuth2\Service\Bitrix24::__construct
* @covers OAuth\OAuth2\Service\Bitrix24::getAuthorizationMethod
*/
public function testGetAuthorizationMethod()
{
$client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
$client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0));

$token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface');
$token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES));
$token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo'));

$storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface');
$storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token));

$service = new Bitrix24(
$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
$client,
$storage,
array(),
$this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
);

$uri = $service->request('https://pieterhordijk.com/my/awesome/path');
$absoluteUri = parse_url($uri->getAbsoluteUri());

$this->assertSame('access_token=foo', $absoluteUri['query']);
}

/**
* @covers OAuth\OAuth2\Service\Bitrix24::__construct
* @covers OAuth\OAuth2\Service\Bitrix24::parseAccessTokenResponse
*/
public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse()
{
$client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
$client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null));

$service = new Bitrix24(
$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
$client,
$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
array(),
$this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
);

$this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException');

$service->requestAccessToken('foo');
}

/**
* @covers OAuth\OAuth2\Service\Bitrix24::__construct
* @covers OAuth\OAuth2\Service\Bitrix24::parseAccessTokenResponse
*/
public function testParseAccessTokenResponseThrowsExceptionOnError()
{
$client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
$client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"error":"some_error"}'));

$service = new Bitrix24(
$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
$client,
$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
array(),
$this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
);

$this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException');

$service->requestAccessToken('foo');
}

/**
* @covers OAuth\OAuth2\Service\Bitrix24::__construct
* @covers OAuth\OAuth2\Service\Bitrix24::parseAccessTokenResponse
*/
public function testParseAccessTokenResponseValidWithoutRefreshToken()
{
$client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
$client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}'));

$service = new Bitrix24(
$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
$client,
$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
array(),
$this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
);

$this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo'));
}

/**
* @covers OAuth\OAuth2\Service\Bitrix24::__construct
* @covers OAuth\OAuth2\Service\Bitrix24::getExtraOAuthHeaders
*/
public function testGetExtraOAuthHeaders()
{
$client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface');
$client->expects($this->once())->method('retrieveResponse')->will($this->returnCallback(function($uri, $params, $extraHeaders) {
\PHPUnit_Framework_Assert::assertTrue(array_key_exists('Accept', $extraHeaders));
\PHPUnit_Framework_Assert::assertTrue(in_array('application/json', $extraHeaders, true));

return '{"access_token":"foo","expires_in":"bar"}';
}));

$service = new Bitrix24(
$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
$client,
$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
array(),
$this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')
);

$this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo'));
}
}

0 comments on commit 26fdd6b

Please sign in to comment.