AuthComponentTest.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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. $result = $this->Auth->user('username');
  939. $this->assertEquals('mariano', $result);
  940. $this->assertFalse(isset($_SESSION));
  941. }
  942. /**
  943. * test $settings in Controller::$components
  944. *
  945. * @return void
  946. */
  947. public function testComponentSettings()
  948. {
  949. $this->Auth->config([
  950. 'loginAction' => ['controller' => 'people', 'action' => 'login'],
  951. 'logoutRedirect' => ['controller' => 'people', 'action' => 'login'],
  952. ]);
  953. $expected = [
  954. 'loginAction' => ['controller' => 'people', 'action' => 'login'],
  955. 'logoutRedirect' => ['controller' => 'people', 'action' => 'login'],
  956. ];
  957. $this->assertEquals(
  958. $expected['loginAction'],
  959. $this->Auth->config('loginAction')
  960. );
  961. $this->assertEquals(
  962. $expected['logoutRedirect'],
  963. $this->Auth->config('logoutRedirect')
  964. );
  965. }
  966. /**
  967. * test that logout deletes the session variables. and returns the correct URL
  968. *
  969. * @return void
  970. */
  971. public function testLogout()
  972. {
  973. $this->Auth->session->write('Auth.User.id', '1');
  974. $this->Auth->session->write('Auth.redirect', '/Users/login');
  975. $this->Auth->config('logoutRedirect', '/');
  976. $result = $this->Auth->logout();
  977. $this->assertEquals('/', $result);
  978. $this->assertNull($this->Auth->session->read('Auth.AuthUsers'));
  979. $this->assertNull($this->Auth->session->read('Auth.redirect'));
  980. }
  981. /**
  982. * Test that Auth.afterIdentify and Auth.logout events are triggered
  983. *
  984. * @return void
  985. */
  986. public function testEventTriggering()
  987. {
  988. $this->Auth->config('authenticate', [
  989. 'Test' => ['className' => 'TestApp\Auth\TestAuthenticate']
  990. ]);
  991. $user = $this->Auth->identify();
  992. $this->Auth->logout();
  993. $authObject = $this->Auth->authenticationProvider();
  994. $expected = ['afterIdentify', 'logout'];
  995. $this->assertEquals($expected, $authObject->callStack);
  996. $expected = ['id' => 1, 'username' => 'admad'];
  997. $this->assertEquals($expected, $user);
  998. // Callback for Auth.afterIdentify returns a value
  999. $authObject->modifiedUser = true;
  1000. $user = $this->Auth->identify();
  1001. $expected = ['id' => 1, 'username' => 'admad', 'extra' => 'foo'];
  1002. $this->assertEquals($expected, $user);
  1003. }
  1004. /**
  1005. * test setting user info to session.
  1006. *
  1007. * @return void
  1008. */
  1009. public function testSetUser()
  1010. {
  1011. $storage = $this->getMock(
  1012. 'Cake\Auth\Storage\SessionStorage',
  1013. ['write'],
  1014. [$this->Auth->request, $this->Auth->response]
  1015. );
  1016. $this->Auth->storage($storage);
  1017. $user = ['username' => 'mark', 'role' => 'admin'];
  1018. $storage->expects($this->once())
  1019. ->method('write')
  1020. ->with($user);
  1021. $this->Auth->setUser($user);
  1022. }
  1023. /**
  1024. * testGettingUserAfterSetUser
  1025. *
  1026. * @return void
  1027. */
  1028. public function testGettingUserAfterSetUser()
  1029. {
  1030. $this->assertFalse((bool)$this->Auth->user());
  1031. $user = [
  1032. 'username' => 'mariano',
  1033. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  1034. 'created' => new \DateTime('2007-03-17 01:16:23'),
  1035. 'updated' => new \DateTime('2007-03-17 01:18:31')
  1036. ];
  1037. $this->Auth->setUser($user);
  1038. $this->assertTrue((bool)$this->Auth->user());
  1039. $this->assertEquals($user['username'], $this->Auth->user('username'));
  1040. }
  1041. /**
  1042. * test flash settings.
  1043. *
  1044. * @return void
  1045. * @triggers Controller.startup $this->Controller)
  1046. */
  1047. public function testFlashSettings()
  1048. {
  1049. $this->Auth->Flash = $this->getMock(
  1050. 'Cake\Controller\Component\FlashComponent',
  1051. [],
  1052. [$this->Controller->components()]
  1053. );
  1054. $this->Controller->request->params['action'] = 'add';
  1055. $this->Auth->startup(new Event('Controller.startup', $this->Controller));
  1056. $this->Auth->Flash->expects($this->at(0))
  1057. ->method('set')
  1058. ->with(
  1059. 'Auth failure',
  1060. [
  1061. 'key' => 'auth-key',
  1062. 'element' => 'default',
  1063. 'params' => ['class' => 'error']
  1064. ]
  1065. );
  1066. $this->Auth->Flash->expects($this->at(1))
  1067. ->method('set')
  1068. ->with('Auth failure', ['key' => 'auth-key', 'element' => 'custom']);
  1069. $this->Auth->config('flash', [
  1070. 'key' => 'auth-key'
  1071. ]);
  1072. $this->Auth->flash('Auth failure');
  1073. $this->Auth->config('flash', [
  1074. 'key' => 'auth-key',
  1075. 'element' => 'custom'
  1076. ], false);
  1077. $this->Auth->flash('Auth failure');
  1078. }
  1079. /**
  1080. * test the various states of Auth::redirect()
  1081. *
  1082. * @return void
  1083. */
  1084. public function testRedirectSet()
  1085. {
  1086. $value = ['controller' => 'users', 'action' => 'home'];
  1087. $result = $this->Auth->redirectUrl($value);
  1088. $this->assertEquals('/users/home', $result);
  1089. $this->assertEquals($value, $this->Auth->session->read('Auth.redirect'));
  1090. $request = new Request();
  1091. $request->base = '/base';
  1092. Router::setRequestInfo($request);
  1093. $result = $this->Auth->redirectUrl($value);
  1094. $this->assertEquals('/users/home', $result);
  1095. }
  1096. /**
  1097. * test redirect using Auth.redirect from the session.
  1098. *
  1099. * @return void
  1100. */
  1101. public function testRedirectSessionRead()
  1102. {
  1103. $this->Auth->config('loginAction', ['controller' => 'users', 'action' => 'login']);
  1104. $this->Auth->session->write('Auth.redirect', '/users/home');
  1105. $result = $this->Auth->redirectUrl();
  1106. $this->assertEquals('/users/home', $result);
  1107. $this->assertFalse($this->Auth->session->check('Auth.redirect'));
  1108. }
  1109. /**
  1110. * test redirectUrl with duplicate base.
  1111. *
  1112. * @return void
  1113. */
  1114. public function testRedirectSessionReadDuplicateBase()
  1115. {
  1116. $this->Auth->request->webroot = '/waves/';
  1117. $this->Auth->request->base = '/waves';
  1118. Router::setRequestInfo($this->Auth->request);
  1119. $this->Auth->session->write('Auth.redirect', '/waves/add');
  1120. $result = $this->Auth->redirectUrl();
  1121. $this->assertEquals('/waves/add', $result);
  1122. }
  1123. /**
  1124. * test that redirect does not return loginAction if that is what's stored in Auth.redirect.
  1125. * instead loginRedirect should be used.
  1126. *
  1127. * @return void
  1128. */
  1129. public function testRedirectSessionReadEqualToLoginAction()
  1130. {
  1131. $this->Auth->config([
  1132. 'loginAction' => ['controller' => 'users', 'action' => 'login'],
  1133. 'loginRedirect' => ['controller' => 'users', 'action' => 'home']
  1134. ]);
  1135. $this->Auth->session->write('Auth.redirect', ['controller' => 'users', 'action' => 'login']);
  1136. $result = $this->Auth->redirectUrl();
  1137. $this->assertEquals('/users/home', $result);
  1138. $this->assertFalse($this->Auth->session->check('Auth.redirect'));
  1139. }
  1140. /**
  1141. * test that the returned URL doesn't contain the base URL.
  1142. *
  1143. * @see https://cakephp.lighthouseapp.com/projects/42648/tickets/3922-authcomponentredirecturl-prepends-appbaseurl
  1144. *
  1145. * @return void This test method doesn't return anything.
  1146. */
  1147. public function testRedirectUrlWithBaseSet()
  1148. {
  1149. $App = Configure::read('App');
  1150. Configure::write('App', [
  1151. 'dir' => APP_DIR,
  1152. 'webroot' => 'webroot',
  1153. 'base' => false,
  1154. 'baseUrl' => '/cake/index.php'
  1155. ]);
  1156. $url = '/users/login';
  1157. $this->Auth->request = $this->Controller->request = new Request($url);
  1158. $this->Auth->request->addParams(Router::parse($url));
  1159. $this->Auth->request->url = Router::normalize($url);
  1160. Router::setRequestInfo($this->Auth->request);
  1161. $this->Auth->config('loginAction', ['controller' => 'users', 'action' => 'login']);
  1162. $this->Auth->config('loginRedirect', ['controller' => 'users', 'action' => 'home']);
  1163. $result = $this->Auth->redirectUrl();
  1164. $this->assertEquals('/users/home', $result);
  1165. $this->assertFalse($this->Auth->session->check('Auth.redirect'));
  1166. Configure::write('App', $App);
  1167. Router::reload();
  1168. }
  1169. /**
  1170. * testUser method
  1171. *
  1172. * @return void
  1173. */
  1174. public function testUser()
  1175. {
  1176. $data = [
  1177. 'User' => [
  1178. 'id' => '2',
  1179. 'username' => 'mark',
  1180. 'group_id' => 1,
  1181. 'Group' => [
  1182. 'id' => '1',
  1183. 'name' => 'Members'
  1184. ],
  1185. 'is_admin' => false,
  1186. ]];
  1187. $this->Auth->session->write('Auth', $data);
  1188. $result = $this->Auth->user();
  1189. $this->assertEquals($data['User'], $result);
  1190. $result = $this->Auth->user('username');
  1191. $this->assertEquals($data['User']['username'], $result);
  1192. $result = $this->Auth->user('Group.name');
  1193. $this->assertEquals($data['User']['Group']['name'], $result);
  1194. $result = $this->Auth->user('invalid');
  1195. $this->assertEquals(null, $result);
  1196. $result = $this->Auth->user('Company.invalid');
  1197. $this->assertEquals(null, $result);
  1198. $result = $this->Auth->user('is_admin');
  1199. $this->assertFalse($result);
  1200. }
  1201. /**
  1202. * testStatelessAuthNoRedirect method
  1203. *
  1204. * @expectedException \Cake\Network\Exception\UnauthorizedException
  1205. * @expectedExceptionCode 401
  1206. * @return void
  1207. * @triggers Controller.startup $this->Controller
  1208. */
  1209. public function testStatelessAuthNoRedirect()
  1210. {
  1211. $event = new Event('Controller.startup', $this->Controller);
  1212. $_SESSION = [];
  1213. $this->Auth->config('authenticate', ['Basic']);
  1214. $this->Controller->request['action'] = 'add';
  1215. $result = $this->Auth->startup($event);
  1216. }
  1217. /**
  1218. * testStatelessAuthRedirect method
  1219. *
  1220. * @return void
  1221. * @triggers Controller.startup $this->Controller
  1222. */
  1223. public function testStatelessFollowedByStatefulAuth()
  1224. {
  1225. $event = new Event('Controller.startup', $this->Controller);
  1226. $this->Auth->authenticate = ['Basic', 'Form'];
  1227. $this->Controller->request['action'] = 'add';
  1228. $this->Auth->response->expects($this->never())->method('statusCode');
  1229. $this->Auth->response->expects($this->never())->method('send');
  1230. $this->assertInstanceOf('Cake\Network\Response', $this->Auth->startup($event));
  1231. $this->assertEquals('/users/login', $this->Controller->testUrl);
  1232. }
  1233. /**
  1234. * test for BC getting/setting AuthComponent::$sessionKey gets/sets `key`
  1235. * config of session storage.
  1236. *
  1237. * @return void
  1238. */
  1239. public function testSessionKeyBC()
  1240. {
  1241. $this->assertEquals('Auth.User', $this->Auth->sessionKey);
  1242. $this->Auth->sessionKey = 'Auth.Member';
  1243. $this->assertEquals('Auth.Member', $this->Auth->sessionKey);
  1244. $this->assertEquals('Auth.Member', $this->Auth->storage()->config('key'));
  1245. $this->Auth->sessionKey = false;
  1246. $this->assertInstanceOf('Cake\Auth\Storage\MemoryStorage', $this->Auth->storage());
  1247. }
  1248. /**
  1249. * Test that setting config 'earlyAuth' to true make AuthComponent do the initial
  1250. * checks in beforeFilter() instead of startup().
  1251. *
  1252. * @return void
  1253. */
  1254. public function testCheckAuthInConfig()
  1255. {
  1256. $this->Controller->components()->set('Auth', $this->Auth);
  1257. $this->Auth->earlyAuthTest = true;
  1258. $this->Auth->authCheckCalledFrom = null;
  1259. $this->Controller->startupProcess();
  1260. $this->assertEquals('Controller.startup', $this->Auth->authCheckCalledFrom);
  1261. $this->Auth->authCheckCalledFrom = null;
  1262. $this->Auth->config('checkAuthIn', 'Controller.initialize');
  1263. $this->Controller->startupProcess();
  1264. $this->assertEquals('Controller.initialize', $this->Auth->authCheckCalledFrom);
  1265. }
  1266. }