AuthComponentTest.php 59 KB

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