]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - tests/service/OAuthTest.php
Release 6.5.16
[Github/sugarcrm.git] / tests / service / OAuthTest.php
1 <?php
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
5  * 
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of the GNU Affero General Public License version 3 as published by the
8  * Free Software Foundation with the addition of the following permission added
9  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12  * 
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
16  * details.
17  * 
18  * You should have received a copy of the GNU Affero General Public License along with
19  * this program; if not, see http://www.gnu.org/licenses or write to the Free
20  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  * 02110-1301 USA.
22  * 
23  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25  * 
26  * The interactive user interfaces in modified source and object code versions
27  * of this program must display Appropriate Legal Notices, as required under
28  * Section 5 of the GNU Affero General Public License version 3.
29  * 
30  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31  * these Appropriate Legal Notices must retain the display of the "Powered by
32  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33  * technical reasons, the Appropriate Legal Notices must display the words
34  * "Powered by SugarCRM".
35  ********************************************************************************/
36
37
38 require_once('tests/service/APIv3Helper.php');
39 require_once 'include/SugarOAuthServer.php';
40
41 class OAuthTest extends Sugar_PHPUnit_Framework_TestCase
42 {
43     protected static $_user;
44     protected static $_consumer;
45     protected $_admin_user;
46     protected $_lastRawResponse;
47
48     private static $helperObject;
49
50     protected $aclRole;
51     protected $aclField;
52
53     public static function setUpBeforeClass()
54     {
55         $beanList = array();
56                 $beanFiles = array();
57                 require('include/modules.php');
58                 $GLOBALS['beanList'] = $beanList;
59                 $GLOBALS['beanFiles'] = $beanFiles;
60
61         //Reload langauge strings
62         $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
63         $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
64         $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], 'Accounts');
65         //Create an anonymous user for login purposes/
66         $GLOBALS['current_user'] = self::$_user = SugarTestUserUtilities::createAnonymousUser();
67
68         self::$helperObject = new APIv3Helper();
69         // create our own customer key
70         $GLOBALS['db']->query("DELETE FROM oauth_consumer where c_key='TESTCUSTOMER'");
71             $GLOBALS['db']->query("DELETE FROM oauth_nonce where conskey='TESTCUSTOMER'");
72         self::$_consumer = new OAuthKey();
73             self::$_consumer->c_key = "TESTCUSTOMER";
74         self::$_consumer->c_secret = "TESTSECRET";
75         self::$_consumer->save();
76         self::$_consumer->db->commit();
77     }
78
79     public static function tearDownAfterClass()
80         {
81             unset($GLOBALS['beanList']);
82                 unset($GLOBALS['beanFiles']);
83                 unset($GLOBALS['app_list_strings']);
84             unset($GLOBALS['app_strings']);
85             unset($GLOBALS['mod_strings']);
86             unset($GLOBALS['current_user']);
87             $GLOBALS['db']->query("DELETE FROM oauth_consumer where c_key='TESTCUSTOMER'");
88             $GLOBALS['db']->query("DELETE FROM oauth_nonce where conskey='TESTCUSTOMER'");
89             $GLOBALS['db']->query("DELETE FROM oauth_tokens where consumer='".self::$_consumer->id."'");
90             SugarTestUserUtilities::removeAllCreatedAnonymousUsers();
91         }
92
93         public function setUp()
94         {
95             if(!SugarOAuthServer::enabled() || !extension_loaded('oauth')) {
96             $this->markTestSkipped("No OAuth support");
97         }
98         $this->oauth = new OAuth('TESTCUSTOMER','TESTSECRET',OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
99         $this->url = rtrim($GLOBALS['sugar_config']['site_url'],'/').'/service/v4/rest.php';
100             $GLOBALS['current_user'] = self::$_user;
101         }
102
103     protected function _returnLastRawResponse()
104     {
105         return "Error in web services call. Response was: {$this->_lastRawResponse}";
106     }
107
108     public function testOauthRequestToken()
109     {
110         $request_token_info = $this->oauth->getRequestToken($this->url."?method=oauth_request_token");
111         $this->assertEquals(rtrim($GLOBALS['sugar_config']['site_url'],'/').'/index.php?module=OAuthTokens&action=authorize', $request_token_info["authorize_url"]);
112         $this->assertEquals("true", $request_token_info["oauth_callback_confirmed"]);
113         $this->assertNotEmpty($request_token_info['oauth_token']);
114         $this->assertNotEmpty($request_token_info['oauth_token_secret']);
115         $rtoken = OAuthToken::load($request_token_info['oauth_token']);
116         $this->assertInstanceOf('OAuthToken', $rtoken);
117         $this->assertEquals(OAuthToken::REQUEST, $rtoken->tstate);
118     }
119
120     public function testOauthAccessToken()
121     {
122         global $current_user;
123         $request_token_info = $this->oauth->getRequestToken($this->url."?method=oauth_request_token");
124         $this->assertNotEmpty($request_token_info['oauth_token']);
125         $this->assertNotEmpty($request_token_info['oauth_token_secret']);
126         $token = $request_token_info['oauth_token'];
127         $secret = $request_token_info['oauth_token_secret'];
128
129         $c_token = OAuthToken::load($token);
130         $this->assertInstanceOf('OAuthToken', $c_token);
131         // check token is in the right state
132         $this->assertEquals(OAuthToken::REQUEST, $c_token->tstate, "Request token has wrong state");
133         $verify = $c_token->authorize(array("user" => $current_user->id));
134         $c_token->db->commit();
135
136         $this->oauth->setToken($token, $secret);
137         $access_token_info = $this->oauth->getAccessToken($this->url."?method=oauth_access_token&oauth_verifier=$verify");
138         $this->assertNotEmpty($access_token_info['oauth_token']);
139         $this->assertNotEmpty($access_token_info['oauth_token_secret']);
140
141         $atoken = OAuthToken::load($access_token_info['oauth_token']);
142         $this->assertInstanceOf('OAuthToken', $atoken);
143         $this->assertEquals($current_user->id, $atoken->assigned_user_id);
144         // check this is an access token
145         $this->assertEquals(OAuthToken::ACCESS, $atoken->tstate, "Access token has wrong state");
146         // check old token was invalidated
147         $rtoken = OAuthToken::load($token);
148         $this->assertInstanceOf('OAuthToken', $rtoken);
149         $this->assertEquals(OAuthToken::INVALID, $rtoken->tstate, "Request token was not invalidated");
150     }
151
152     protected function _makeRESTCall($method,$parameters)
153     {
154         // specify the REST web service to interact with
155         $url = $GLOBALS['sugar_config']['site_url'].'/service/v4/rest.php';
156         // Open a curl session for making the call
157         $curl = curl_init($url);
158         // set URL and other appropriate options
159         curl_setopt($curl, CURLOPT_URL, $url);
160         curl_setopt($curl, CURLOPT_POST, 1);
161         curl_setopt($curl, CURLOPT_HEADER, 0);
162         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
163         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
164         curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
165         curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
166         // build the request URL
167         $json = json_encode($parameters);
168         $postArgs = "method=$method&input_type=JSON&response_type=JSON&rest_data=$json";
169         curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
170         // Make the REST call, returning the result
171         $response = curl_exec($curl);
172         // Close the connection
173         curl_close($curl);
174
175         $this->_lastRawResponse = $response;
176
177         // Convert the result from JSON format to a PHP array
178         return json_decode($response,true);
179     }
180
181     public function testOauthServiceAccess()
182     {
183         global $current_user;
184         $request_token_info = $this->oauth->getRequestToken($this->url."?method=oauth_request_token");
185         $token = $request_token_info['oauth_token'];
186         $secret = $request_token_info['oauth_token_secret'];
187
188         $c_token = OAuthToken::load($token);
189         $this->assertInstanceOf('OAuthToken', $c_token, 'Token not loaded');
190         $verify = $c_token->authorize(array("user" => $current_user->id));
191         $c_token->db->commit();
192
193         $this->oauth->setToken($token, $secret);
194         $access_token_info = $this->oauth->getAccessToken($this->url."?method=oauth_access_token&oauth_verifier=$verify");
195         $token = $access_token_info['oauth_token'];
196         $secret = $access_token_info['oauth_token_secret'];
197         $this->oauth->setToken($token, $secret);
198
199         $res = $this->oauth->fetch($this->url."?method=oauth_access&input_type=JSON&response_type=JSON");
200         $this->assertTrue($res);
201         $session = json_decode($this->oauth->getLastResponse(), true);
202         $this->assertNotEmpty($session["id"]);
203
204         // test fetch through OAuth
205         $res = $this->oauth->fetch($this->url."?method=get_user_id&input_type=JSON&response_type=JSON");
206         $this->assertTrue($res);
207         $id = json_decode($this->oauth->getLastResponse(), true);
208         $this->assertEquals($current_user->id, $id);
209         // test fetch through session initiated by OAuth
210         $id2 = $this->_makeRESTCall('get_user_id', array("session" => $session["id"]));
211         $this->assertEquals($current_user->id, $id2);
212     }
213 }