AuthComponentTest.php 59 KB

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