AuthComponentTest.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller\Component;
  16. use Cake\Controller\ComponentRegistry;
  17. use Cake\Controller\Component\AuthComponent;
  18. use Cake\Controller\Controller;
  19. use Cake\Core\App;
  20. use Cake\Core\Configure;
  21. use Cake\Event\Event;
  22. use Cake\Network\Exception\ForbiddenException;
  23. use Cake\Network\Exception\UnauthorizedException;
  24. use Cake\Network\Request;
  25. use Cake\Network\Response;
  26. use Cake\Network\Session;
  27. use Cake\ORM\Entity;
  28. use Cake\ORM\TableRegistry;
  29. use Cake\Routing\Router;
  30. use Cake\TestSuite\TestCase;
  31. use Cake\Utility\Security;
  32. use TestApp\Controller\AuthTestController;
  33. use TestApp\Controller\Component\TestAuthComponent;
  34. /**
  35. * AuthComponentTest class
  36. *
  37. */
  38. class AuthComponentTest extends TestCase
  39. {
  40. /**
  41. * name property
  42. *
  43. * @var string
  44. */
  45. public $name = 'Auth';
  46. /**
  47. * fixtures property
  48. *
  49. * @var array
  50. */
  51. public $fixtures = ['core.auth_users', 'core.users'];
  52. /**
  53. * setUp method
  54. *
  55. * @return void
  56. */
  57. public function setUp()
  58. {
  59. parent::setUp();
  60. Security::salt('YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
  61. Configure::write('App.namespace', 'TestApp');
  62. Router::scope('/', function ($routes) {
  63. $routes->fallbacks('InflectedRoute');
  64. });
  65. $request = new Request();
  66. $response = $this->getMock('Cake\Network\Response', ['stop']);
  67. $this->Controller = new AuthTestController($request, $response);
  68. $this->Auth = new TestAuthComponent($this->Controller->components());
  69. $Users = TableRegistry::get('AuthUsers');
  70. $Users->updateAll(['password' => password_hash('cake', PASSWORD_BCRYPT)], []);
  71. }
  72. /**
  73. * tearDown method
  74. *
  75. * @return void
  76. */
  77. public function tearDown()
  78. {
  79. parent::tearDown();
  80. $_SESSION = [];
  81. unset($this->Controller, $this->Auth);
  82. }
  83. /**
  84. * testNoAuth method
  85. *
  86. * @return void
  87. */
  88. public function testNoAuth()
  89. {
  90. $this->assertFalse($this->Auth->isAuthorized());
  91. }
  92. /**
  93. * testIsErrorOrTests
  94. *
  95. * @return void
  96. * @triggers Controller.startup $this->Controller
  97. */
  98. public function testIsErrorOrTests()
  99. {
  100. $event = new Event('Controller.startup', $this->Controller);
  101. $this->Controller->name = 'Error';
  102. $this->assertNull($this->Controller->Auth->startup($event));
  103. $this->Controller->name = 'Post';
  104. $this->Controller->request['action'] = 'thisdoesnotexist';
  105. $this->assertNull($this->Controller->Auth->startup($event));
  106. }
  107. /**
  108. * testIdentify method
  109. *
  110. * @return void
  111. */
  112. public function testIdentify()
  113. {
  114. $AuthLoginFormAuthenticate = $this->getMock(
  115. 'Cake\Controller\Component\Auth\FormAuthenticate',
  116. ['authenticate'],
  117. [],
  118. '',
  119. false
  120. );
  121. $this->Auth->authenticate = [
  122. 'AuthLoginForm' => [
  123. 'userModel' => 'AuthUsers'
  124. ]
  125. ];
  126. $this->Auth->setAuthenticateObject(0, $AuthLoginFormAuthenticate);
  127. $this->Auth->request->data = [
  128. 'AuthUsers' => [
  129. 'username' => 'mark',
  130. 'password' => Security::hash('cake', null, true)
  131. ]
  132. ];
  133. $user = [
  134. 'id' => 1,
  135. 'username' => 'mark'
  136. ];
  137. $AuthLoginFormAuthenticate->expects($this->once())
  138. ->method('authenticate')
  139. ->with($this->Auth->request)
  140. ->will($this->returnValue($user));
  141. $result = $this->Auth->identify();
  142. $this->assertEquals($user, $result);
  143. $this->assertSame($AuthLoginFormAuthenticate, $this->Auth->authenticationProvider());
  144. }
  145. /**
  146. * testRedirectVarClearing method
  147. *
  148. * @return void
  149. * @triggers Controller.startup $this->Controller
  150. */
  151. public function testRedirectVarClearing()
  152. {
  153. $this->Controller->request['controller'] = 'auth_test';
  154. $this->Controller->request['action'] = 'add';
  155. $this->Controller->request->here = '/auth_test/add';
  156. $this->assertNull($this->Auth->session->read('Auth.redirect'));
  157. $this->Auth->config('authenticate', ['Form']);
  158. $event = new Event('Controller.startup', $this->Controller);
  159. $this->Auth->startup($event);
  160. $this->assertEquals('/auth_test/add', $this->Auth->session->read('Auth.redirect'));
  161. $this->Auth->storage()->write(['username' => 'admad']);
  162. $this->Auth->startup($event, $this->Controller);
  163. $this->assertNull($this->Auth->session->read('Auth.redirect'));
  164. }
  165. /**
  166. * testAuthorizeFalse method
  167. *
  168. * @return void
  169. * @triggers Controller.startup $this->Controller
  170. */
  171. public function testAuthorizeFalse()
  172. {
  173. $event = new Event('Controller.startup', $this->Controller);
  174. $Users = TableRegistry::get('Users');
  175. $user = $Users->find('all')->hydrate(false)->first();
  176. $this->Controller->Auth->storage()->write($user);
  177. $this->Controller->Auth->config('userModel', 'Users');
  178. $this->Controller->Auth->config('authorize', false);
  179. $this->Controller->request->addParams(Router::parse('auth_test/add'));
  180. $result = $this->Controller->Auth->startup($event);
  181. $this->assertNull($result);
  182. $this->Controller->Auth->storage()->delete();
  183. $result = $this->Controller->Auth->startup($event);
  184. $this->assertTrue($event->isStopped());
  185. $this->assertInstanceOf('Cake\Network\Response', $result);
  186. $this->assertTrue($this->Auth->session->check('Flash.auth'));
  187. $this->Controller->request->addParams(Router::parse('auth_test/camelCase'));
  188. $result = $this->Controller->Auth->startup($event);
  189. $this->assertInstanceOf('Cake\Network\Response', $result);
  190. }
  191. /**
  192. * testIsAuthorizedMissingFile function
  193. *
  194. * @expectedException \Cake\Core\Exception\Exception
  195. * @return void
  196. */
  197. public function testIsAuthorizedMissingFile()
  198. {
  199. $this->Controller->Auth->config('authorize', 'Missing');
  200. $this->Controller->Auth->isAuthorized(['User' => ['id' => 1]]);
  201. }
  202. /**
  203. * test that isAuthorized calls methods correctly
  204. *
  205. * @return void
  206. */
  207. public function testIsAuthorizedDelegation()
  208. {
  209. $AuthMockOneAuthorize = $this->getMock(
  210. 'Cake\Controller\Component\BaseAuthorize',
  211. ['authorize'],
  212. [],
  213. '',
  214. false
  215. );
  216. $AuthMockTwoAuthorize = $this->getMock(
  217. 'Cake\Controller\Component\Auth\BaseAuthorize',
  218. ['authorize'],
  219. [],
  220. '',
  221. false
  222. );
  223. $AuthMockThreeAuthorize = $this->getMock(
  224. 'Cake\Controller\Component\Auth\BaseAuthorize',
  225. ['authorize'],
  226. [],
  227. '',
  228. false
  229. );
  230. $this->Auth->setAuthorizeObject(0, $AuthMockOneAuthorize);
  231. $this->Auth->setAuthorizeObject(1, $AuthMockTwoAuthorize);
  232. $this->Auth->setAuthorizeObject(2, $AuthMockThreeAuthorize);
  233. $request = $this->Auth->request;
  234. $AuthMockOneAuthorize->expects($this->once())
  235. ->method('authorize')
  236. ->with(['User'], $request)
  237. ->will($this->returnValue(false));
  238. $AuthMockTwoAuthorize->expects($this->once())
  239. ->method('authorize')
  240. ->with(['User'], $request)
  241. ->will($this->returnValue(true));
  242. $AuthMockThreeAuthorize->expects($this->never())
  243. ->method('authorize');
  244. $this->assertTrue($this->Auth->isAuthorized(['User'], $request));
  245. $this->assertSame($AuthMockTwoAuthorize, $this->Auth->authorizationProvider());
  246. }
  247. /**
  248. * test that isAuthorized will use the session user if none is given.
  249. *
  250. * @return void
  251. */
  252. public function testIsAuthorizedUsingUserInSession()
  253. {
  254. $AuthMockFourAuthorize = $this->getMock(
  255. 'Cake\Controller\Component\Auth\BaseAuthorize',
  256. ['authorize'],
  257. [],
  258. '',
  259. false
  260. );
  261. $this->Auth->config('authorize', ['AuthMockFour']);
  262. $this->Auth->setAuthorizeObject(0, $AuthMockFourAuthorize);
  263. $user = ['user' => 'mark'];
  264. $this->Auth->session->write('Auth.User', $user);
  265. $request = $this->Controller->request;
  266. $AuthMockFourAuthorize->expects($this->once())
  267. ->method('authorize')
  268. ->with($user, $request)
  269. ->will($this->returnValue(true));
  270. $this->assertTrue($this->Auth->isAuthorized(null, $request));
  271. }
  272. /**
  273. * test that loadAuthorize resets the loaded objects each time.
  274. *
  275. * @return void
  276. */
  277. public function testLoadAuthorizeResets()
  278. {
  279. $this->Controller->Auth->config('authorize', ['Controller']);
  280. $result = $this->Controller->Auth->constructAuthorize();
  281. $this->assertEquals(1, count($result));
  282. $result = $this->Controller->Auth->constructAuthorize();
  283. $this->assertEquals(1, count($result));
  284. }
  285. /**
  286. * testLoadAuthenticateNoFile function
  287. *
  288. * @expectedException \Cake\Core\Exception\Exception
  289. * @return void
  290. */
  291. public function testLoadAuthenticateNoFile()
  292. {
  293. $this->Controller->Auth->config('authenticate', 'Missing');
  294. $this->Controller->Auth->identify($this->Controller->request, $this->Controller->response);
  295. }
  296. /**
  297. * test the * key with authenticate
  298. *
  299. * @return void
  300. */
  301. public function testAllConfigWithAuthorize()
  302. {
  303. $this->Controller->Auth->config('authorize', [
  304. AuthComponent::ALL => ['actionPath' => 'controllers/'],
  305. 'Controller',
  306. ]);
  307. $objects = array_values($this->Controller->Auth->constructAuthorize());
  308. $result = $objects[0];
  309. $this->assertEquals('controllers/', $result->config('actionPath'));
  310. }
  311. /**
  312. * test that loadAuthorize resets the loaded objects each time.
  313. *
  314. * @return void
  315. */
  316. public function testLoadAuthenticateResets()
  317. {
  318. $this->Controller->Auth->config('authenticate', ['Form']);
  319. $result = $this->Controller->Auth->constructAuthenticate();
  320. $this->assertEquals(1, count($result));
  321. $result = $this->Controller->Auth->constructAuthenticate();
  322. $this->assertEquals(1, count($result));
  323. }
  324. /**
  325. * test the * key with authenticate
  326. *
  327. * @return void
  328. */
  329. public function testAllConfigWithAuthenticate()
  330. {
  331. $this->Controller->Auth->config('authenticate', [
  332. AuthComponent::ALL => ['userModel' => 'AuthUsers'],
  333. 'Form'
  334. ]);
  335. $objects = array_values($this->Controller->Auth->constructAuthenticate());
  336. $result = $objects[0];
  337. $this->assertEquals('AuthUsers', $result->config('userModel'));
  338. }
  339. /**
  340. * test defining the same Authenticate object but with different password hashers
  341. *
  342. * @return void
  343. */
  344. public function testSameAuthenticateWithDifferentHashers()
  345. {
  346. $this->Controller->Auth->config('authenticate', [
  347. 'FormSimple' => ['className' => 'Form', 'passwordHasher' => 'Default'],
  348. 'FormBlowfish' => ['className' => 'Form', 'passwordHasher' => 'Fallback'],
  349. ]);
  350. $objects = $this->Controller->Auth->constructAuthenticate();
  351. $this->assertEquals(2, count($objects));
  352. $this->assertInstanceOf('Cake\Auth\FormAuthenticate', $objects['FormSimple']);
  353. $this->assertInstanceOf('Cake\Auth\FormAuthenticate', $objects['FormBlowfish']);
  354. $this->assertInstanceOf('Cake\Auth\DefaultPasswordHasher', $objects['FormSimple']->passwordHasher());
  355. $this->assertInstanceOf('Cake\Auth\FallbackPasswordHasher', $objects['FormBlowfish']->passwordHasher());
  356. }
  357. /**
  358. * Tests that deny always takes precedence over allow
  359. *
  360. * @return void
  361. * @triggers Controller.startup $this->Controller
  362. */
  363. public function testAllowDenyAll()
  364. {
  365. $event = new Event('Controller.startup', $this->Controller);
  366. $this->Controller->Auth->allow();
  367. $this->Controller->Auth->deny(['add', 'camelCase']);
  368. $this->Controller->request['action'] = 'delete';
  369. $this->assertNull($this->Controller->Auth->startup($event));
  370. $this->Controller->request['action'] = 'add';
  371. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  372. $this->Controller->request['action'] = 'camelCase';
  373. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  374. $this->Controller->Auth->allow();
  375. $this->Controller->Auth->deny(['add', 'camelCase']);
  376. $this->Controller->request['action'] = 'delete';
  377. $this->assertNull($this->Controller->Auth->startup($event));
  378. $this->Controller->request['action'] = 'camelCase';
  379. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  380. $this->Controller->Auth->allow();
  381. $this->Controller->Auth->deny();
  382. $this->Controller->request['action'] = 'camelCase';
  383. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  384. $this->Controller->request['action'] = 'add';
  385. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  386. $this->Controller->Auth->allow('camelCase');
  387. $this->Controller->Auth->deny();
  388. $this->Controller->request['action'] = 'camelCase';
  389. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  390. $this->Controller->request['action'] = 'login';
  391. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  392. $this->Controller->Auth->deny();
  393. $this->Controller->Auth->allow(null);
  394. $this->Controller->request['action'] = 'camelCase';
  395. $this->assertNull($this->Controller->Auth->startup($event));
  396. $this->Controller->Auth->allow();
  397. $this->Controller->Auth->deny(null);
  398. $this->Controller->request['action'] = 'camelCase';
  399. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  400. }
  401. /**
  402. * test that deny() converts camel case inputs to lowercase.
  403. *
  404. * @return void
  405. * @triggers Controller.startup $this->Controller
  406. */
  407. public function testDenyWithCamelCaseMethods()
  408. {
  409. $event = new Event('Controller.startup', $this->Controller);
  410. $this->Controller->Auth->allow();
  411. $this->Controller->Auth->deny(['add', 'camelCase']);
  412. $url = '/auth_test/camelCase';
  413. $this->Controller->request->addParams(Router::parse($url));
  414. $this->Controller->request->query['url'] = Router::normalize($url);
  415. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  416. $url = '/auth_test/CamelCase';
  417. $this->Controller->request->addParams(Router::parse($url));
  418. $this->Controller->request->query['url'] = Router::normalize($url);
  419. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  420. }
  421. /**
  422. * test that allow() and allowedActions work with camelCase method names.
  423. *
  424. * @return void
  425. * @triggers Controller.startup $this->Controller
  426. */
  427. public function testAllowedActionsWithCamelCaseMethods()
  428. {
  429. $event = new Event('Controller.startup', $this->Controller);
  430. $url = '/auth_test/camelCase';
  431. $this->Controller->request->addParams(Router::parse($url));
  432. $this->Controller->request->query['url'] = Router::normalize($url);
  433. $this->Controller->Auth->loginAction = ['controller' => 'AuthTest', 'action' => 'login'];
  434. $this->Controller->Auth->userModel = 'AuthUsers';
  435. $this->Controller->Auth->allow();
  436. $result = $this->Controller->Auth->startup($event);
  437. $this->assertNull($result, 'startup() should return null, as action is allowed. %s');
  438. $url = '/auth_test/camelCase';
  439. $this->Controller->request->addParams(Router::parse($url));
  440. $this->Controller->request->query['url'] = Router::normalize($url);
  441. $this->Controller->Auth->loginAction = ['controller' => 'AuthTest', 'action' => 'login'];
  442. $this->Controller->Auth->userModel = 'AuthUsers';
  443. $this->Controller->Auth->allowedActions = ['delete', 'camelCase', 'add'];
  444. $result = $this->Controller->Auth->startup($event);
  445. $this->assertNull($result, 'startup() should return null, as action is allowed. %s');
  446. $this->Controller->Auth->allowedActions = ['delete', 'add'];
  447. $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
  448. $url = '/auth_test/delete';
  449. $this->Controller->request->addParams(Router::parse($url));
  450. $this->Controller->request->query['url'] = Router::normalize($url);
  451. $this->Controller->Auth->loginAction = ['controller' => 'AuthTest', 'action' => 'login'];
  452. $this->Controller->Auth->userModel = 'AuthUsers';
  453. $this->Controller->Auth->allow(['delete', 'add']);
  454. $result = $this->Controller->Auth->startup($event);
  455. $this->assertNull($result, 'startup() should return null, as action is allowed. %s');
  456. }
  457. /**
  458. * testAllowedActionsSetWithAllowMethod method
  459. *
  460. * @return void
  461. */
  462. public function testAllowedActionsSetWithAllowMethod()
  463. {
  464. $url = '/auth_test/action_name';
  465. $this->Controller->request->addParams(Router::parse($url));
  466. $this->Controller->request->query['url'] = Router::normalize($url);
  467. $this->Controller->Auth->allow(['action_name', 'anotherAction']);
  468. $this->assertEquals(['action_name', 'anotherAction'], $this->Controller->Auth->allowedActions);
  469. }
  470. /**
  471. * testLoginRedirect method
  472. *
  473. * @return void
  474. * @triggers Controller.startup $this->Controller
  475. */
  476. public function testLoginRedirect()
  477. {
  478. $url = '/auth_test/camelCase';
  479. $this->Auth->session->write('Auth', [
  480. 'AuthUsers' => ['id' => '1', 'username' => 'nate']
  481. ]);
  482. $this->Auth->request->addParams(Router::parse('users/login'));
  483. $this->Auth->request->url = 'users/login';
  484. $this->Auth->request->env('HTTP_REFERER', false);
  485. $this->Auth->config('loginRedirect', [
  486. 'controller' => 'pages',
  487. 'action' => 'display',
  488. 'welcome'
  489. ]);
  490. $event = new Event('Controller.startup', $this->Controller);
  491. $this->Auth->startup($event);
  492. $expected = Router::normalize($this->Auth->config('loginRedirect'));
  493. $this->assertEquals($expected, $this->Auth->redirectUrl());
  494. $this->Auth->session->delete('Auth');
  495. $url = '/posts/view/1';
  496. $this->Auth->session->write(
  497. 'Auth',
  498. ['AuthUsers' => ['id' => '1', 'username' => 'nate']]
  499. );
  500. $this->Controller->testUrl = null;
  501. $this->Auth->request->addParams(Router::parse($url));
  502. $this->Auth->request->env('HTTP_REFERER', false);
  503. $this->Auth->config('authorize', 'controller');
  504. $this->Auth->config('loginAction', [
  505. 'controller' => 'AuthTest', 'action' => 'login'
  506. ]);
  507. $event = new Event('Controller.startup', $this->Controller);
  508. $this->Auth->startup($event);
  509. $expected = Router::normalize('/auth_test/login');
  510. $this->assertEquals($expected, $this->Controller->testUrl);
  511. // Auth.redirect gets set when accessing a protected action without being authenticated
  512. $this->Auth->session->delete('Auth');
  513. $url = '/posts/view/1';
  514. $this->Auth->request->addParams(Router::parse($url));
  515. $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url);
  516. $this->Auth->config('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
  517. $event = new Event('Controller.startup', $this->Controller);
  518. $this->Auth->startup($event);
  519. $expected = Router::normalize('posts/view/1');
  520. $this->assertEquals($expected, $this->Auth->session->read('Auth.redirect'));
  521. // QueryString parameters are preserved when setting Auth.redirect
  522. $this->Auth->session->delete('Auth');
  523. $url = '/posts/view/29';
  524. $this->Auth->request->addParams(Router::parse($url));
  525. $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url);
  526. $this->Auth->request->query = [
  527. 'print' => 'true',
  528. 'refer' => 'menu'
  529. ];
  530. $this->Auth->config('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
  531. $event = new Event('Controller.startup', $this->Controller);
  532. $this->Auth->startup($event);
  533. $expected = Router::normalize('posts/view/29?print=true&refer=menu');
  534. $this->assertEquals($expected, $this->Auth->session->read('Auth.redirect'));
  535. // Different base urls.
  536. $appConfig = Configure::read('App');
  537. Configure::write('App', [
  538. 'dir' => APP_DIR,
  539. 'webroot' => 'webroot',
  540. 'base' => false,
  541. 'baseUrl' => '/cake/index.php'
  542. ]);
  543. $this->Auth->session->delete('Auth');
  544. $url = '/posts/add';
  545. $this->Auth->request = $this->Controller->request = new Request($url);
  546. $this->Auth->request->addParams(Router::parse($url));
  547. $this->Auth->request->url = Router::normalize($url);
  548. $this->Auth->config('loginAction', ['controller' => 'users', 'action' => 'login']);
  549. $event = new Event('Controller.startup', $this->Controller);
  550. $this->Auth->startup($event);
  551. $expected = Router::normalize('/posts/add');
  552. $this->assertEquals($expected, $this->Auth->session->read('Auth.redirect'));
  553. $this->Auth->session->delete('Auth');
  554. Configure::write('App', $appConfig);
  555. // External Authed Action
  556. $this->Auth->session->delete('Auth');
  557. $url = '/posts/view/1';
  558. $request = new Request($url);
  559. $request->env('HTTP_REFERER', 'http://webmail.example.com/view/message');
  560. $request->query = [];
  561. $this->Auth->request = $this->Controller->request = $request;
  562. $this->Auth->request->addParams(Router::parse($url));
  563. $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url);
  564. $this->Auth->config('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
  565. $event = new Event('Controller.startup', $this->Controller);
  566. $this->Auth->startup($event);
  567. $expected = Router::normalize('/posts/view/1');
  568. $this->assertEquals($expected, $this->Auth->session->read('Auth.redirect'));
  569. $this->Auth->session->delete('Auth');
  570. }
  571. /**
  572. * testNoLoginRedirectForAuthenticatedUser method
  573. *
  574. * @return void
  575. * @triggers Controller.startup $this->Controller
  576. */
  577. public function testNoLoginRedirectForAuthenticatedUser()
  578. {
  579. $this->Controller->request['controller'] = 'auth_test';
  580. $this->Controller->request['action'] = 'login';
  581. $this->Controller->here = '/auth_test/login';
  582. $this->Auth->request->url = 'auth_test/login';
  583. $this->Auth->session->write('Auth.User.id', '1');
  584. $this->Auth->config('authenticate', ['Form']);
  585. $this->getMock(
  586. 'Cake\Controller\Component\Auth\BaseAuthorize',
  587. ['authorize'],
  588. [],
  589. 'NoLoginRedirectMockAuthorize',
  590. false
  591. );
  592. $this->Auth->config('authorize', ['NoLoginRedirectMockAuthorize']);
  593. $this->Auth->config('loginAction', ['controller' => 'auth_test', 'action' => 'login']);
  594. $event = new Event('Controller.startup', $this->Controller);
  595. $return = $this->Auth->startup($event);
  596. $this->assertNull($return);
  597. $this->assertNull($this->Controller->testUrl);
  598. }
  599. /**
  600. * Default to loginRedirect, if set, on authError.
  601. *
  602. * @return void
  603. * @triggers Controller.startup $Controller
  604. */
  605. public function testDefaultToLoginRedirect()
  606. {
  607. $url = '/party/on';
  608. $this->Auth->request = $request = new Request($url);
  609. $request->env('HTTP_REFERER', false);
  610. $request->addParams(Router::parse($url));
  611. $request->addPaths([
  612. 'base' => 'dirname',
  613. 'webroot' => '/dirname/',
  614. ]);
  615. Router::pushRequest($request);
  616. $this->Auth->config('authorize', ['Controller']);
  617. $this->Auth->setUser(['username' => 'mariano', 'password' => 'cake']);
  618. $this->Auth->config('loginRedirect', [
  619. 'controller' => 'something',
  620. 'action' => 'else'
  621. ]);
  622. $response = new Response();
  623. $Controller = $this->getMock(
  624. 'Cake\Controller\Controller',
  625. ['on', 'redirect'],
  626. [$request, $response]
  627. );
  628. $event = new Event('Controller.startup', $Controller);
  629. // Should not contain basedir when redirect is called.
  630. $expected = '/something/else';
  631. $Controller->expects($this->once())
  632. ->method('redirect')
  633. ->with($this->equalTo($expected));
  634. $this->Auth->startup($event);
  635. }
  636. /**
  637. * testRedirectToUnauthorizedRedirect
  638. *
  639. * @return void
  640. * @triggers Controller.startup $Controller
  641. */
  642. public function testRedirectToUnauthorizedRedirect()
  643. {
  644. $url = '/party/on';
  645. $this->Auth->Flash = $this->getMock(
  646. 'Cake\Controller\Component\FlashComponent',
  647. ['set'],
  648. [$this->Controller->components()]
  649. );
  650. $this->Auth->request = $request = new Request([
  651. 'url' => $url,
  652. 'session' => $this->Auth->session
  653. ]);
  654. $this->Auth->request->addParams(Router::parse($url));
  655. $this->Auth->config('authorize', ['Controller']);
  656. $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
  657. $expected = ['controller' => 'no_can_do', 'action' => 'jack'];
  658. $this->Auth->config('unauthorizedRedirect', $expected);
  659. $response = new Response();
  660. $Controller = $this->getMock(
  661. 'Cake\Controller\Controller',
  662. ['on', 'redirect'],
  663. [$request, $response]
  664. );
  665. $Controller->expects($this->once())
  666. ->method('redirect')
  667. ->with($this->equalTo($expected));
  668. $this->Auth->Flash->expects($this->once())
  669. ->method('set');
  670. $event = new Event('Controller.startup', $Controller);
  671. $this->Auth->startup($event);
  672. }
  673. /**
  674. * test unauthorized redirect defaults to loginRedirect
  675. * which is a string URL.
  676. *
  677. * @return void
  678. */
  679. public function testRedirectToUnauthorizedRedirectLoginAction()
  680. {
  681. $url = '/party/on';
  682. $this->Auth->Flash = $this->getMock(
  683. 'Cake\Controller\Component\FlashComponent',
  684. ['set'],
  685. [$this->Controller->components()]
  686. );
  687. $this->Auth->request = $request = new Request([
  688. 'url' => $url,
  689. 'session' => $this->Auth->session
  690. ]);
  691. $this->Auth->request->addParams(Router::parse($url));
  692. $this->Auth->config('authorize', ['Controller']);
  693. $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
  694. $this->Auth->config('unauthorizedRedirect', true);
  695. $this->Auth->config('loginAction', '/users/login');
  696. $response = new Response();
  697. $Controller = $this->getMock(
  698. 'Cake\Controller\Controller',
  699. ['on', 'redirect'],
  700. [$request, $response]
  701. );
  702. // Uses referrer instead of loginAction.
  703. $Controller->expects($this->once())
  704. ->method('redirect')
  705. ->with($this->equalTo('/'));
  706. $event = new Event('Controller.startup', $Controller);
  707. $this->Auth->startup($event);
  708. }
  709. /**
  710. * testRedirectToUnauthorizedRedirectSuppressedAuthError
  711. *
  712. * @return void
  713. * @triggers Controller.startup $Controller
  714. */
  715. public function testRedirectToUnauthorizedRedirectSuppressedAuthError()
  716. {
  717. $url = '/party/on';
  718. $this->Auth->session = $this->getMock(
  719. 'Cake\Network\Session',
  720. ['flash']
  721. );
  722. $this->Auth->request = $Request = new Request($url);
  723. $this->Auth->request->addParams(Router::parse($url));
  724. $this->Auth->config('authorize', ['Controller']);
  725. $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
  726. $expected = ['controller' => 'no_can_do', 'action' => 'jack'];
  727. $this->Auth->config('unauthorizedRedirect', $expected);
  728. $this->Auth->config('authError', false);
  729. $Response = new Response();
  730. $Controller = $this->getMock(
  731. 'Cake\Controller\Controller',
  732. ['on', 'redirect'],
  733. [$Request, $Response]
  734. );
  735. $Controller->expects($this->once())
  736. ->method('redirect')
  737. ->with($this->equalTo($expected));
  738. $this->Auth->session->expects($this->never())
  739. ->method('flash');
  740. $event = new Event('Controller.startup', $Controller);
  741. $this->Auth->startup($event);
  742. }
  743. /**
  744. * Throw ForbiddenException if config `unauthorizedRedirect` is set to false
  745. *
  746. * @expectedException \Cake\Network\Exception\ForbiddenException
  747. * @return void
  748. * @triggers Controller.startup $Controller
  749. */
  750. public function testForbiddenException()
  751. {
  752. $url = '/party/on';
  753. $this->Auth->request = $request = new Request($url);
  754. $this->Auth->request->addParams(Router::parse($url));
  755. $this->Auth->config([
  756. 'authorize' => ['Controller'],
  757. 'unauthorizedRedirect' => false
  758. ]);
  759. $this->Auth->setUser(['username' => 'baker', 'password' => 'cake']);
  760. $response = new Response();
  761. $Controller = $this->getMock(
  762. 'Cake\Controller\Controller',
  763. ['on', 'redirect'],
  764. [$request, $response]
  765. );
  766. $event = new Event('Controller.startup', $Controller);
  767. $this->Auth->startup($event);
  768. }
  769. /**
  770. * Test that no redirects or authorization tests occur on the loginAction
  771. *
  772. * @return void
  773. * @triggers Controller.startup $this->Controller
  774. */
  775. public function testNoRedirectOnLoginAction()
  776. {
  777. $event = new Event('Controller.startup', $this->Controller);
  778. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  779. $controller->methods = ['login'];
  780. $url = '/AuthTest/login';
  781. $this->Auth->request = $controller->request = new Request($url);
  782. $this->Auth->request->addParams(Router::parse($url));
  783. $this->Auth->config([
  784. 'loginAction', ['controller' => 'AuthTest', 'action' => 'login'],
  785. 'authorize', ['Controller']
  786. ]);
  787. $controller->expects($this->never())
  788. ->method('redirect');
  789. $this->Auth->startup($event);
  790. }
  791. /**
  792. * Ensure that no redirect is performed when a 404 is reached
  793. * And the user doesn't have a session.
  794. *
  795. * @return void
  796. * @triggers Controller.startup $this->Controller
  797. */
  798. public function testNoRedirectOn404()
  799. {
  800. $event = new Event('Controller.startup', $this->Controller);
  801. $this->Auth->session->delete('Auth');
  802. $this->Auth->request->addParams(Router::parse('auth_test/something_totally_wrong'));
  803. $result = $this->Auth->startup($event);
  804. $this->assertNull($result, 'Auth redirected a missing action %s');
  805. }
  806. /**
  807. * testAdminRoute method
  808. *
  809. * @return void
  810. * @triggers Controller.startup $this->Controller
  811. */
  812. public function testAdminRoute()
  813. {
  814. $event = new Event('Controller.startup', $this->Controller);
  815. Router::reload();
  816. Router::prefix('admin', function ($routes) {
  817. $routes->fallbacks('InflectedRoute');
  818. });
  819. Router::scope('/', function ($routes) {
  820. $routes->fallbacks('InflectedRoute');
  821. });
  822. $url = '/admin/auth_test/add';
  823. $this->Auth->request->addParams(Router::parse($url));
  824. $this->Auth->request->query['url'] = ltrim($url, '/');
  825. $this->Auth->request->base = '';
  826. Router::setRequestInfo($this->Auth->request);
  827. $this->Auth->config('loginAction', [
  828. 'prefix' => 'admin',
  829. 'controller' => 'auth_test',
  830. 'action' => 'login'
  831. ]);
  832. $this->Auth->startup($event);
  833. $this->assertEquals('/admin/auth_test/login', $this->Controller->testUrl);
  834. }
  835. /**
  836. * testAjaxLogin method
  837. *
  838. * @return void
  839. * @triggers Controller.startup $this->Controller
  840. */
  841. public function testAjaxLogin()
  842. {
  843. $this->Controller->request = new Request([
  844. 'url' => '/ajax_auth/add',
  845. 'environment' => ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'],
  846. ]);
  847. $this->Controller->request->params['action'] = 'add';
  848. $event = new Event('Controller.startup', $this->Controller);
  849. $this->Auth->config('ajaxLogin', 'test_element');
  850. $this->Auth->RequestHandler->ajaxLayout = 'ajax2';
  851. $response = $this->Auth->startup($event);
  852. $this->assertTrue($event->isStopped());
  853. $this->assertEquals(403, $response->statusCode());
  854. $this->assertEquals(
  855. "Ajax!\nthis is the test element",
  856. str_replace("\r\n", "\n", $response->body())
  857. );
  858. }
  859. /**
  860. * test ajax unauthenticated
  861. *
  862. * @return void
  863. * @triggers Controller.startup $this->Controller
  864. */
  865. public function testAjaxUnauthenticated()
  866. {
  867. $this->Controller->request = new Request([
  868. 'url' => '/ajax_auth/add',
  869. 'environment' => ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'],
  870. ]);
  871. $this->Controller->request->params['action'] = 'add';
  872. $event = new Event('Controller.startup', $this->Controller);
  873. $response = $this->Auth->startup($event);
  874. $this->assertTrue($event->isStopped());
  875. $this->assertEquals(403, $response->statusCode());
  876. $this->assertArrayNotHasKey('Location', $response->header());
  877. }
  878. /**
  879. * testLoginActionRedirect method
  880. *
  881. * @return void
  882. * @triggers Controller.startup $this->Controller
  883. */
  884. public function testLoginActionRedirect()
  885. {
  886. $event = new Event('Controller.startup', $this->Controller);
  887. Router::reload();
  888. Router::prefix('admin', function ($routes) {
  889. $routes->fallbacks('InflectedRoute');
  890. });
  891. Router::scope('/', function ($routes) {
  892. $routes->fallbacks('InflectedRoute');
  893. });
  894. $url = '/admin/auth_test/login';
  895. $request = $this->Auth->request;
  896. $request->addParams([
  897. 'plugin' => null,
  898. 'controller' => 'auth_test',
  899. 'action' => 'login',
  900. 'prefix' => 'admin',
  901. 'pass' => [],
  902. ])->addPaths([
  903. 'base' => null,
  904. 'here' => $url,
  905. 'webroot' => '/',
  906. ]);
  907. $request->url = ltrim($url, '/');
  908. Router::setRequestInfo($request);
  909. $this->Auth->config('loginAction', [
  910. 'prefix' => 'admin',
  911. 'controller' => 'auth_test',
  912. 'action' => 'login'
  913. ]);
  914. $this->Auth->startup($event);
  915. $this->assertNull($this->Controller->testUrl);
  916. }
  917. /**
  918. * Stateless auth methods like Basic should populate data that can be
  919. * accessed by $this->user().
  920. *
  921. * @return void
  922. * @triggers Controller.startup $this->Controller
  923. */
  924. public function testStatelessAuthWorksWithUser()
  925. {
  926. $event = new Event('Controller.startup', $this->Controller);
  927. $url = '/auth_test/add';
  928. $this->Auth->request->addParams(Router::parse($url));
  929. $this->Auth->request->env('PHP_AUTH_USER', 'mariano');
  930. $this->Auth->request->env('PHP_AUTH_PW', 'cake');
  931. $this->Auth->config('authenticate', [
  932. 'Basic' => ['userModel' => 'AuthUsers']
  933. ]);
  934. $this->Auth->config('storage', 'Memory');
  935. $this->Auth->startup($event);
  936. $result = $this->Auth->user();
  937. $this->assertEquals('mariano', $result['username']);
  938. $this->assertInstanceOf(
  939. 'Cake\Auth\BasicAuthenticate',
  940. $this->Auth->authenticationProvider()
  941. );
  942. $result = $this->Auth->user('username');
  943. $this->assertEquals('mariano', $result);
  944. $this->assertFalse(isset($_SESSION));
  945. }
  946. /**
  947. * test $settings in Controller::$components
  948. *
  949. * @return void
  950. */
  951. public function testComponentSettings()
  952. {
  953. $this->Auth->config([
  954. 'loginAction' => ['controller' => 'people', 'action' => 'login'],
  955. 'logoutRedirect' => ['controller' => 'people', 'action' => 'login'],
  956. ]);
  957. $expected = [
  958. 'loginAction' => ['controller' => 'people', 'action' => 'login'],
  959. 'logoutRedirect' => ['controller' => 'people', 'action' => 'login'],
  960. ];
  961. $this->assertEquals(
  962. $expected['loginAction'],
  963. $this->Auth->config('loginAction')
  964. );
  965. $this->assertEquals(
  966. $expected['logoutRedirect'],
  967. $this->Auth->config('logoutRedirect')
  968. );
  969. }
  970. /**
  971. * test that logout deletes the session variables. and returns the correct URL
  972. *
  973. * @return void
  974. */
  975. public function testLogout()
  976. {
  977. $this->Auth->session->write('Auth.User.id', '1');
  978. $this->Auth->session->write('Auth.redirect', '/Users/login');
  979. $this->Auth->config('logoutRedirect', '/');
  980. $result = $this->Auth->logout();
  981. $this->assertEquals('/', $result);
  982. $this->assertNull($this->Auth->session->read('Auth.AuthUsers'));
  983. $this->assertNull($this->Auth->session->read('Auth.redirect'));
  984. }
  985. /**
  986. * Test that Auth.afterIdentify and Auth.logout events are triggered
  987. *
  988. * @return void
  989. */
  990. public function testEventTriggering()
  991. {
  992. $this->Auth->config('authenticate', [
  993. 'Test' => ['className' => 'TestApp\Auth\TestAuthenticate']
  994. ]);
  995. $user = $this->Auth->identify();
  996. $this->Auth->logout();
  997. $authObject = $this->Auth->authenticationProvider();
  998. $expected = ['afterIdentify', 'logout'];
  999. $this->assertEquals($expected, $authObject->callStack);
  1000. $expected = ['id' => 1, 'username' => 'admad'];
  1001. $this->assertEquals($expected, $user);
  1002. // Callback for Auth.afterIdentify returns a value
  1003. $authObject->modifiedUser = true;
  1004. $user = $this->Auth->identify();
  1005. $expected = ['id' => 1, 'username' => 'admad', 'extra' => 'foo'];
  1006. $this->assertEquals($expected, $user);
  1007. }
  1008. /**
  1009. * test setting user info to session.
  1010. *
  1011. * @return void
  1012. */
  1013. public function testSetUser()
  1014. {
  1015. $storage = $this->getMock(
  1016. 'Cake\Auth\Storage\SessionStorage',
  1017. ['write'],
  1018. [$this->Auth->request, $this->Auth->response]
  1019. );
  1020. $this->Auth->storage($storage);
  1021. $user = ['username' => 'mark', 'role' => 'admin'];
  1022. $storage->expects($this->once())
  1023. ->method('write')
  1024. ->with($user);
  1025. $this->Auth->setUser($user);
  1026. }
  1027. /**
  1028. * testGettingUserAfterSetUser
  1029. *
  1030. * @return void
  1031. */
  1032. public function testGettingUserAfterSetUser()
  1033. {
  1034. $this->assertFalse((bool)$this->Auth->user());
  1035. $user = [
  1036. 'username' => 'mariano',
  1037. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  1038. 'created' => new \DateTime('2007-03-17 01:16:23'),
  1039. 'updated' => new \DateTime('2007-03-17 01:18:31')
  1040. ];
  1041. $this->Auth->setUser($user);
  1042. $this->assertTrue((bool)$this->Auth->user());
  1043. $this->assertEquals($user['username'], $this->Auth->user('username'));
  1044. }
  1045. /**
  1046. * test flash settings.
  1047. *
  1048. * @return void
  1049. * @triggers Controller.startup $this->Controller)
  1050. */
  1051. public function testFlashSettings()
  1052. {
  1053. $this->Auth->Flash = $this->getMock(
  1054. 'Cake\Controller\Component\FlashComponent',
  1055. [],
  1056. [$this->Controller->components()]
  1057. );
  1058. $this->Controller->request->params['action'] = 'add';
  1059. $this->Auth->startup(new Event('Controller.startup', $this->Controller));
  1060. $this->Auth->Flash->expects($this->at(0))
  1061. ->method('set')
  1062. ->with(
  1063. 'Auth failure',
  1064. [
  1065. 'key' => 'auth-key',
  1066. 'element' => 'default',
  1067. 'params' => ['class' => 'error']
  1068. ]
  1069. );
  1070. $this->Auth->Flash->expects($this->at(1))
  1071. ->method('set')
  1072. ->with('Auth failure', ['key' => 'auth-key', 'element' => 'custom']);
  1073. $this->Auth->config('flash', [
  1074. 'key' => 'auth-key'
  1075. ]);
  1076. $this->Auth->flash('Auth failure');
  1077. $this->Auth->config('flash', [
  1078. 'key' => 'auth-key',
  1079. 'element' => 'custom'
  1080. ], false);
  1081. $this->Auth->flash('Auth failure');
  1082. }
  1083. /**
  1084. * test the various states of Auth::redirect()
  1085. *
  1086. * @return void
  1087. */
  1088. public function testRedirectSet()
  1089. {
  1090. $value = ['controller' => 'users', 'action' => 'home'];
  1091. $result = $this->Auth->redirectUrl($value);
  1092. $this->assertEquals('/users/home', $result);
  1093. $this->assertEquals($value, $this->Auth->session->read('Auth.redirect'));
  1094. $request = new Request();
  1095. $request->base = '/base';
  1096. Router::setRequestInfo($request);
  1097. $result = $this->Auth->redirectUrl($value);
  1098. $this->assertEquals('/users/home', $result);
  1099. }
  1100. /**
  1101. * test redirect using Auth.redirect from the session.
  1102. *
  1103. * @return void
  1104. */
  1105. public function testRedirectSessionRead()
  1106. {
  1107. $this->Auth->config('loginAction', ['controller' => 'users', 'action' => 'login']);
  1108. $this->Auth->session->write('Auth.redirect', '/users/home');
  1109. $result = $this->Auth->redirectUrl();
  1110. $this->assertEquals('/users/home', $result);
  1111. $this->assertFalse($this->Auth->session->check('Auth.redirect'));
  1112. }
  1113. /**
  1114. * test redirectUrl with duplicate base.
  1115. *
  1116. * @return void
  1117. */
  1118. public function testRedirectSessionReadDuplicateBase()
  1119. {
  1120. $this->Auth->request->webroot = '/waves/';
  1121. $this->Auth->request->base = '/waves';
  1122. Router::setRequestInfo($this->Auth->request);
  1123. $this->Auth->session->write('Auth.redirect', '/waves/add');
  1124. $result = $this->Auth->redirectUrl();
  1125. $this->assertEquals('/waves/add', $result);
  1126. }
  1127. /**
  1128. * test that redirect does not return loginAction if that is what's stored in Auth.redirect.
  1129. * instead loginRedirect should be used.
  1130. *
  1131. * @return void
  1132. */
  1133. public function testRedirectSessionReadEqualToLoginAction()
  1134. {
  1135. $this->Auth->config([
  1136. 'loginAction' => ['controller' => 'users', 'action' => 'login'],
  1137. 'loginRedirect' => ['controller' => 'users', 'action' => 'home']
  1138. ]);
  1139. $this->Auth->session->write('Auth.redirect', ['controller' => 'users', 'action' => 'login']);
  1140. $result = $this->Auth->redirectUrl();
  1141. $this->assertEquals('/users/home', $result);
  1142. $this->assertFalse($this->Auth->session->check('Auth.redirect'));
  1143. }
  1144. /**
  1145. * test that the returned URL doesn't contain the base URL.
  1146. *
  1147. * @see https://cakephp.lighthouseapp.com/projects/42648/tickets/3922-authcomponentredirecturl-prepends-appbaseurl
  1148. *
  1149. * @return void This test method doesn't return anything.
  1150. */
  1151. public function testRedirectUrlWithBaseSet()
  1152. {
  1153. $App = Configure::read('App');
  1154. Configure::write('App', [
  1155. 'dir' => APP_DIR,
  1156. 'webroot' => 'webroot',
  1157. 'base' => false,
  1158. 'baseUrl' => '/cake/index.php'
  1159. ]);
  1160. $url = '/users/login';
  1161. $this->Auth->request = $this->Controller->request = new Request($url);
  1162. $this->Auth->request->addParams(Router::parse($url));
  1163. $this->Auth->request->url = Router::normalize($url);
  1164. Router::setRequestInfo($this->Auth->request);
  1165. $this->Auth->config('loginAction', ['controller' => 'users', 'action' => 'login']);
  1166. $this->Auth->config('loginRedirect', ['controller' => 'users', 'action' => 'home']);
  1167. $result = $this->Auth->redirectUrl();
  1168. $this->assertEquals('/users/home', $result);
  1169. $this->assertFalse($this->Auth->session->check('Auth.redirect'));
  1170. Configure::write('App', $App);
  1171. Router::reload();
  1172. }
  1173. /**
  1174. * testUser method
  1175. *
  1176. * @return void
  1177. */
  1178. public function testUser()
  1179. {
  1180. $data = [
  1181. 'User' => [
  1182. 'id' => '2',
  1183. 'username' => 'mark',
  1184. 'group_id' => 1,
  1185. 'Group' => [
  1186. 'id' => '1',
  1187. 'name' => 'Members'
  1188. ],
  1189. 'is_admin' => false,
  1190. ]];
  1191. $this->Auth->session->write('Auth', $data);
  1192. $result = $this->Auth->user();
  1193. $this->assertEquals($data['User'], $result);
  1194. $result = $this->Auth->user('username');
  1195. $this->assertEquals($data['User']['username'], $result);
  1196. $result = $this->Auth->user('Group.name');
  1197. $this->assertEquals($data['User']['Group']['name'], $result);
  1198. $result = $this->Auth->user('invalid');
  1199. $this->assertEquals(null, $result);
  1200. $result = $this->Auth->user('Company.invalid');
  1201. $this->assertEquals(null, $result);
  1202. $result = $this->Auth->user('is_admin');
  1203. $this->assertFalse($result);
  1204. }
  1205. /**
  1206. * testStatelessAuthNoRedirect method
  1207. *
  1208. * @expectedException \Cake\Network\Exception\UnauthorizedException
  1209. * @expectedExceptionCode 401
  1210. * @return void
  1211. * @triggers Controller.startup $this->Controller
  1212. */
  1213. public function testStatelessAuthNoRedirect()
  1214. {
  1215. $event = new Event('Controller.startup', $this->Controller);
  1216. $_SESSION = [];
  1217. $this->Auth->config('authenticate', ['Basic']);
  1218. $this->Controller->request['action'] = 'add';
  1219. $result = $this->Auth->startup($event);
  1220. }
  1221. /**
  1222. * testStatelessAuthRedirect method
  1223. *
  1224. * @return void
  1225. * @triggers Controller.startup $this->Controller
  1226. */
  1227. public function testStatelessFollowedByStatefulAuth()
  1228. {
  1229. $event = new Event('Controller.startup', $this->Controller);
  1230. $this->Auth->authenticate = ['Basic', 'Form'];
  1231. $this->Controller->request['action'] = 'add';
  1232. $this->Auth->response->expects($this->never())->method('statusCode');
  1233. $this->Auth->response->expects($this->never())->method('send');
  1234. $this->assertInstanceOf('Cake\Network\Response', $this->Auth->startup($event));
  1235. $this->assertEquals('/users/login', $this->Controller->testUrl);
  1236. }
  1237. /**
  1238. * test for BC getting/setting AuthComponent::$sessionKey gets/sets `key`
  1239. * config of session storage.
  1240. *
  1241. * @return void
  1242. */
  1243. public function testSessionKeyBC()
  1244. {
  1245. $this->assertEquals('Auth.User', $this->Auth->sessionKey);
  1246. $this->Auth->sessionKey = 'Auth.Member';
  1247. $this->assertEquals('Auth.Member', $this->Auth->sessionKey);
  1248. $this->assertEquals('Auth.Member', $this->Auth->storage()->config('key'));
  1249. $this->Auth->sessionKey = false;
  1250. $this->assertInstanceOf('Cake\Auth\Storage\MemoryStorage', $this->Auth->storage());
  1251. }
  1252. /**
  1253. * Test that setting config 'earlyAuth' to true make AuthComponent do the initial
  1254. * checks in beforeFilter() instead of startup().
  1255. *
  1256. * @return void
  1257. */
  1258. public function testCheckAuthInConfig()
  1259. {
  1260. $this->Controller->components()->set('Auth', $this->Auth);
  1261. $this->Auth->earlyAuthTest = true;
  1262. $this->Auth->authCheckCalledFrom = null;
  1263. $this->Controller->startupProcess();
  1264. $this->assertEquals('Controller.startup', $this->Auth->authCheckCalledFrom);
  1265. $this->Auth->authCheckCalledFrom = null;
  1266. $this->Auth->config('checkAuthIn', 'Controller.initialize');
  1267. $this->Controller->startupProcess();
  1268. $this->assertEquals('Controller.initialize', $this->Auth->authCheckCalledFrom);
  1269. }
  1270. }