AuthComponentTest.php 57 KB

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