]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - tests/service/OAuthTest.php
Release 6.4.0
[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-2011 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     }
77
78     public static function tearDownAfterClass()
79         {
80             unset($GLOBALS['beanList']);
81                 unset($GLOBALS['beanFiles']);
82                 unset($GLOBALS['app_list_strings']);
83             unset($GLOBALS['app_strings']);
84             unset($GLOBALS['mod_strings']);
85             unset($GLOBALS['current_user']);
86             $GLOBALS['db']->query("DELETE FROM oauth_consumer where c_key='TESTCUSTOMER'");
87             $GLOBALS['db']->query("DELETE FROM oauth_nonce where conskey='TESTCUSTOMER'");
88             $GLOBALS['db']->query("DELETE FROM oauth_tokens where consumer='".self::$_consumer->id."'");
89             SugarTestUserUtilities::removeAllCreatedAnonymousUsers();
90         }
91
92         public function setUp()
93         {
94             if(!SugarOAuthServer::enabled() || !extension_loaded('oauth')) {
95             $this->markTestSkipped("No OAuth support");
96         }
97         $this->oauth = new OAuth('TESTCUSTOMER','TESTSECRET',OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
98         $this->url = rtrim($GLOBALS['sugar_config']['site_url'],'/').'/service/v4/rest.php';
99             $GLOBALS['current_user'] = self::$_user;
100         }
101
102     protected function _returnLastRawResponse()
103     {
104         return "Error in web services call. Response was: {$this->_lastRawResponse}";
105     }
106
107     public function testOauthRequestToken()
108     {
109         $request_token_info = $this->oauth->getRequestToken($this->url."?method=oauth_request_token");
110         $this->assertEquals(rtrim($GLOBALS['sugar_config']['site_url'],'/').'/index.php?module=OAuthTokens&action=authorize', $request_token_info["authorize_url"]);
111         $this->assertEquals("true", $request_token_info["oauth_callback_confirmed"]);
112         $this->assertNotEmpty($request_token_info['oauth_token']);
113         $this->assertNotEmpty($request_token_info['oauth_token_secret']);
114         $rtoken = OAuthToken::load($request_token_info['oauth_token']);
115         $this->assertInstanceOf('OAuthToken', $rtoken);
116         $this->assertEquals(OAuthToken::REQUEST, $rtoken->tstate);
117     }
118
119     public function testOauthAccessToken()
120     {
121         global $current_user;
122         $request_token_info = $this->oauth->getRequestToken($this->url."?method=oauth_request_token");
123         $this->assertNotEmpty($request_token_info['oauth_token']);
124         $this->assertNotEmpty($request_token_info['oauth_token_secret']);
125         $token = $request_token_info['oauth_token'];
126         $secret = $request_token_info['oauth_token_secret'];
127
128         $c_token = OAuthToken::load($token);
129         $this->assertInstanceOf('OAuthToken', $c_token);
130         // check token is in the right state
131         $this->assertEquals(OAuthToken::REQUEST, $c_token->tstate, "Request token has wrong state");
132         $verify = $c_token->authorize(array("user" => $current_user->id));
133
134         $this->oauth->setToken($token, $secret);
135         $access_token_info = $this->oauth->getAccessToken($this->url."?method=oauth_access_token&oauth_verifier=$verify");
136         $this->assertNotEmpty($access_token_info['oauth_token']);
137         $this->assertNotEmpty($access_token_info['oauth_token_secret']);
138
139         $atoken = OAuthToken::load($access_token_info['oauth_token']);
140         $this->assertInstanceOf('OAuthToken', $atoken);
141         $this->assertEquals($current_user->id, $atoken->assigned_user_id);
142         // check this is an access token
143         $this->assertEquals(OAuthToken::ACCESS, $atoken->tstate, "Access token has wrong state");
144         // check old token was invalidated
145         $rtoken = OAuthToken::load($token);
146         $this->assertInstanceOf('OAuthToken', $rtoken);
147         $this->assertEquals(OAuthToken::INVALID, $rtoken->tstate, "Request token was not invalidated");
148     }
149
150     protected function _makeRESTCall($method,$parameters)
151     {
152         // specify the REST web service to interact with
153         $url = $GLOBALS['sugar_config']['site_url'].'/service/v4/rest.php';
154         // Open a curl session for making the call
155         $curl = curl_init($url);
156         // set URL and other appropriate options
157         curl_setopt($curl, CURLOPT_URL, $url);
158         curl_setopt($curl, CURLOPT_POST, 1);
159         curl_setopt($curl, CURLOPT_HEADER, 0);
160         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
161         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
162         curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
163         curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
164         // build the request URL
165         $json = json_encode($parameters);
166         $postArgs = "method=$method&input_type=JSON&response_type=JSON&rest_data=$json";
167         curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
168         // Make the REST call, returning the result
169         $response = curl_exec($curl);
170         // Close the connection
171         curl_close($curl);
172
173         $this->_lastRawResponse = $response;
174
175         // Convert the result from JSON format to a PHP array
176         return json_decode($response,true);
177     }
178
179     public function testOauthServiceAccess()
180     {
181         global $current_user;
182         $request_token_info = $this->oauth->getRequestToken($this->url."?method=oauth_request_token");
183         $token = $request_token_info['oauth_token'];
184         $secret = $request_token_info['oauth_token_secret'];
185
186         $c_token = OAuthToken::load($token);
187         $verify = $c_token->authorize(array("user" => $current_user->id));
188
189         $this->oauth->setToken($token, $secret);
190         $access_token_info = $this->oauth->getAccessToken($this->url."?method=oauth_access_token&oauth_verifier=$verify");
191         $token = $access_token_info['oauth_token'];
192         $secret = $access_token_info['oauth_token_secret'];
193         $this->oauth->setToken($token, $secret);
194
195         $res = $this->oauth->fetch($this->url."?method=oauth_access&input_type=JSON&response_type=JSON");
196         $this->assertTrue($res);
197         $session = json_decode($this->oauth->getLastResponse(), true);
198         $this->assertNotEmpty($session["id"]);
199
200         // test fetch through OAuth
201         $res = $this->oauth->fetch($this->url."?method=get_user_id&input_type=JSON&response_type=JSON");
202         $this->assertTrue($res);
203         $id = json_decode($this->oauth->getLastResponse(), true);
204         $this->assertEquals($current_user->id, $id);
205         // test fetch through session initiated by OAuth
206         $id2 = $this->_makeRESTCall('get_user_id', array("session" => $session["id"]));
207         $this->assertEquals($current_user->id, $id2);
208     }
209 }