AuthComponentTest.php 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller\Component;
  16. use Cake\Auth\BaseAuthorize;
  17. use Cake\Auth\FormAuthenticate;
  18. use Cake\Controller\Component\AuthComponent;
  19. use Cake\Core\Configure;
  20. use Cake\Event\Event;
  21. use Cake\Event\EventManager;
  22. use Cake\Http\Response;
  23. use Cake\Http\ServerRequest;
  24. use Cake\Routing\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. * testNoLoginRedirectForAuthenticatedUser method
  722. *
  723. * @return void
  724. * @triggers Controller.startup $this->Controller
  725. */
  726. public function testStartupLoginActionIgnoreQueryString()
  727. {
  728. $request = new ServerRequest([
  729. 'params' => [
  730. 'plugin' => null,
  731. 'controller' => 'auth_test',
  732. 'action' => 'login'
  733. ],
  734. 'query' => ['redirect' => '/admin/articles'],
  735. 'url' => '/auth_test/login?redirect=%2Fadmin%2Farticles',
  736. 'session' => $this->Auth->session
  737. ]);
  738. $this->Controller->request = $request;
  739. $this->Auth->session->clear();
  740. $this->Auth->setConfig('authenticate', ['Form']);
  741. $this->Auth->setConfig('authorize', false);
  742. $this->Auth->setConfig('loginAction', ['controller' => 'auth_test', 'action' => 'login']);
  743. $event = new Event('Controller.startup', $this->Controller);
  744. $return = $this->Auth->startup($event);
  745. $this->assertNull($return);
  746. }
  747. /**
  748. * Default to loginRedirect, if set, on authError.
  749. *
  750. * @return void
  751. * @triggers Controller.startup $Controller
  752. */
  753. public function testDefaultToLoginRedirect()
  754. {
  755. $url = '/party/on';
  756. $this->Controller->request = $request = new ServerRequest([
  757. 'url' => $url,
  758. 'environment' => [
  759. 'HTTP_REFERER' => false,
  760. ],
  761. 'params' => [
  762. 'plugin' => null,
  763. 'controller' => 'Part',
  764. 'action' => 'on'
  765. ],
  766. 'base' => 'dirname',
  767. 'webroot' => '/dirname/'
  768. ]);
  769. Router::pushRequest($request);
  770. $this->Auth->setConfig('authorize', ['Controller']);
  771. $this->Auth->setUser(['username' => 'mariano', 'password' => 'cake']);
  772. $this->Auth->setConfig('loginRedirect', [
  773. 'controller' => 'something',
  774. 'action' => 'else'
  775. ]);
  776. $response = new Response();
  777. $Controller = $this->getMockBuilder('Cake\Controller\Controller')
  778. ->setMethods(['on', 'redirect'])
  779. ->setConstructorArgs([$request, $response])
  780. ->getMock();
  781. $event = new Event('Controller.startup', $Controller);
  782. // Should not contain basedir when redirect is called.
  783. $expected = '/something/else';
  784. $Controller->expects($this->once())
  785. ->method('redirect')
  786. ->with($this->equalTo($expected));
  787. $this->Auth->startup($event);
  788. }
  789. /**
  790. * testRedirectToUnauthorizedRedirect
  791. *
  792. * @return void
  793. * @triggers Controller.startup $Controller
  794. */
  795. public function testRedirectToUnauthorizedRedirect()
  796. {
  797. $url = '/party/on';
  798. $this->Auth->Flash = $this->getMockBuilder('Cake\Controller\Component\FlashComponent')
  799. ->setMethods(['set'])
  800. ->setConstructorArgs([$this->Controller->components()])
  801. ->getMock();
  802. $request = new ServerRequest([
  803. 'url' => $url,
  804. 'session' => $this->Auth->session,
  805. 'params' => ['controller' => 'Party', 'action' => 'on']
  806. ]);
  807. $this->Auth->setConfig('authorize', ['Controller']);
  808. $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
  809. $expected = ['controller' => 'no_can_do', 'action' => 'jack'];
  810. $this->Auth->setConfig('unauthorizedRedirect', $expected);
  811. $response = new Response();
  812. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  813. ->setMethods(['on', 'redirect'])
  814. ->setConstructorArgs([$request, $response])
  815. ->getMock();
  816. $controller->expects($this->once())
  817. ->method('redirect')
  818. ->with($this->equalTo($expected));
  819. $this->Auth->Flash->expects($this->once())
  820. ->method('set');
  821. $event = new Event('Controller.startup', $controller);
  822. $this->Auth->startup($event);
  823. }
  824. /**
  825. * test unauthorized redirect defaults to loginRedirect
  826. * which is a string URL.
  827. *
  828. * @return void
  829. */
  830. public function testRedirectToUnauthorizedRedirectLoginAction()
  831. {
  832. $url = '/party/on';
  833. $this->Auth->Flash = $this->getMockBuilder('Cake\Controller\Component\FlashComponent')
  834. ->setMethods(['set'])
  835. ->setConstructorArgs([$this->Controller->components()])
  836. ->getMock();
  837. $request = new ServerRequest([
  838. 'url' => $url,
  839. 'session' => $this->Auth->session,
  840. 'params' => ['controller' => 'Party', 'action' => 'on']
  841. ]);
  842. $this->Auth->setConfig('authorize', ['Controller']);
  843. $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
  844. $this->Auth->setConfig('unauthorizedRedirect', true);
  845. $this->Auth->setConfig('loginAction', '/users/login');
  846. $response = new Response();
  847. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  848. ->setMethods(['on', 'redirect'])
  849. ->setConstructorArgs([$request, $response])
  850. ->getMock();
  851. // Uses referrer instead of loginAction.
  852. $controller->expects($this->once())
  853. ->method('redirect')
  854. ->with($this->equalTo('/'));
  855. $event = new Event('Controller.startup', $controller);
  856. $this->Auth->startup($event);
  857. }
  858. /**
  859. * testRedirectToUnauthorizedRedirectSuppressedAuthError
  860. *
  861. * @return void
  862. * @triggers Controller.startup $Controller
  863. */
  864. public function testRedirectToUnauthorizedRedirectSuppressedAuthError()
  865. {
  866. $url = '/party/on';
  867. $this->Auth->session = $this->getMockBuilder(Session::class)
  868. ->setMethods(['flash'])
  869. ->getMock();
  870. $request = new ServerRequest([
  871. 'url' => $url,
  872. 'params' => ['controller' => 'Party', 'action' => 'on']
  873. ]);
  874. $this->Auth->setConfig('authorize', ['Controller']);
  875. $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
  876. $expected = ['controller' => 'no_can_do', 'action' => 'jack'];
  877. $this->Auth->setConfig('unauthorizedRedirect', $expected);
  878. $this->Auth->setConfig('authError', false);
  879. $response = new Response();
  880. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  881. ->setMethods(['on', 'redirect'])
  882. ->setConstructorArgs([$request, $response])
  883. ->getMock();
  884. $controller->expects($this->once())
  885. ->method('redirect')
  886. ->with($this->equalTo($expected));
  887. $this->Auth->session->expects($this->never())
  888. ->method('flash');
  889. $event = new Event('Controller.startup', $controller);
  890. $this->Auth->startup($event);
  891. }
  892. /**
  893. * Throw ForbiddenException if config `unauthorizedRedirect` is set to false
  894. *
  895. * @return void
  896. * @triggers Controller.startup $Controller
  897. */
  898. public function testForbiddenException()
  899. {
  900. $this->expectException(\Cake\Http\Exception\ForbiddenException::class);
  901. $this->Auth->setConfig([
  902. 'authorize' => ['Controller'],
  903. 'unauthorizedRedirect' => false
  904. ]);
  905. $this->Auth->setUser(['username' => 'baker', 'password' => 'cake']);
  906. $request = $this->request
  907. ->withAttribute('params', ['controller' => 'Party', 'action' => 'on'])
  908. ->withRequestTarget('/party/on');
  909. $response = new Response();
  910. $Controller = $this->getMockBuilder('Cake\Controller\Controller')
  911. ->setMethods(['on', 'redirect'])
  912. ->setConstructorArgs([$request, $response])
  913. ->getMock();
  914. $event = new Event('Controller.startup', $Controller);
  915. $this->Auth->startup($event);
  916. }
  917. /**
  918. * Test that no redirects or authorization tests occur on the loginAction
  919. *
  920. * @return void
  921. * @triggers Controller.startup $this->Controller
  922. */
  923. public function testNoRedirectOnLoginAction()
  924. {
  925. $event = new Event('Controller.startup', $this->Controller);
  926. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  927. ->setMethods(['redirect'])
  928. ->getMock();
  929. $controller->methods = ['login'];
  930. $url = '/AuthTest/login';
  931. $this->Controller->request = $this->request
  932. ->withAttribute('params', ['controller' => 'AuthTest', 'action' => 'login'])
  933. ->withRequestTarget($url);
  934. $this->Auth->setConfig([
  935. 'loginAction', ['controller' => 'AuthTest', 'action' => 'login'],
  936. 'authorize', ['Controller']
  937. ]);
  938. $controller->expects($this->never())
  939. ->method('redirect');
  940. $this->Auth->startup($event);
  941. }
  942. /**
  943. * Ensure that no redirect is performed when a 404 is reached
  944. * And the user doesn't have a session.
  945. *
  946. * @return void
  947. * @triggers Controller.startup $this->Controller
  948. */
  949. public function testNoRedirectOn404()
  950. {
  951. $event = new Event('Controller.startup', $this->Controller);
  952. $this->Auth->session->delete('Auth');
  953. $this->Controller->request = $this->request->withAttribute(
  954. 'params',
  955. ['controller' => 'AuthTest', 'action' => 'something_totally_wrong']
  956. );
  957. $result = $this->Auth->startup($event);
  958. $this->assertNull($result, 'Auth redirected a missing action %s');
  959. }
  960. /**
  961. * testAdminRoute method
  962. *
  963. * @return void
  964. * @triggers Controller.startup $this->Controller
  965. */
  966. public function testAdminRoute()
  967. {
  968. $event = new Event('Controller.startup', $this->Controller);
  969. Router::reload();
  970. Router::prefix('admin', function ($routes) {
  971. $routes->fallbacks(InflectedRoute::class);
  972. });
  973. Router::scope('/', function ($routes) {
  974. $routes->fallbacks(InflectedRoute::class);
  975. });
  976. $this->Controller->request = new ServerRequest([
  977. 'environment' => [
  978. 'REQUEST_METHOD' => 'GET',
  979. ],
  980. 'params' => [
  981. 'controller' => 'AuthTest',
  982. 'action' => 'add',
  983. 'plugin' => null,
  984. 'prefix' => 'admin'
  985. ],
  986. 'url' => '/admin/auth_test/add',
  987. 'session' => $this->Auth->session
  988. ]);
  989. Router::setRequestInfo($this->Controller->request);
  990. $this->Auth->setConfig('loginAction', [
  991. 'prefix' => 'admin',
  992. 'controller' => 'auth_test',
  993. 'action' => 'login'
  994. ]);
  995. $response = $this->Auth->startup($event);
  996. $redirectHeader = $response->getHeaderLine('Location');
  997. $expected = Router::url([
  998. 'prefix' => 'admin',
  999. 'controller' => 'auth_test',
  1000. 'action' => 'login',
  1001. '?' => ['redirect' => '/admin/auth_test/add']
  1002. ], true);
  1003. $this->assertEquals($expected, $redirectHeader);
  1004. }
  1005. /**
  1006. * testAjaxLogin method
  1007. *
  1008. * @return void
  1009. * @triggers Controller.startup $this->Controller
  1010. */
  1011. public function testAjaxLogin()
  1012. {
  1013. $this->Controller->request = new ServerRequest([
  1014. 'url' => '/ajax_auth/add',
  1015. 'environment' => ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'],
  1016. ]);
  1017. $this->Controller->request = $this->Controller->request->withParam('action', 'add');
  1018. $event = new Event('Controller.startup', $this->Controller);
  1019. $this->Auth->setConfig('ajaxLogin', 'test_element');
  1020. $this->Auth->RequestHandler->ajaxLayout = 'ajax2';
  1021. $response = $this->Auth->startup($event);
  1022. $this->assertTrue($event->isStopped());
  1023. $this->assertEquals(403, $response->getStatusCode());
  1024. $this->assertEquals(
  1025. "Ajax!\nthis is the test element",
  1026. str_replace("\r\n", "\n", $response->getBody())
  1027. );
  1028. }
  1029. /**
  1030. * test ajax unauthenticated
  1031. *
  1032. * @return void
  1033. * @triggers Controller.startup $this->Controller
  1034. */
  1035. public function testAjaxUnauthenticated()
  1036. {
  1037. $this->Controller->request = new ServerRequest([
  1038. 'url' => '/ajax_auth/add',
  1039. 'environment' => ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'],
  1040. ]);
  1041. $this->Controller->request = $this->Controller->request->withParam('action', 'add');
  1042. $event = new Event('Controller.startup', $this->Controller);
  1043. $response = $this->Auth->startup($event);
  1044. $this->assertTrue($event->isStopped());
  1045. $this->assertEquals(403, $response->getStatusCode());
  1046. $this->assertFalse($response->hasHeader('Location'));
  1047. }
  1048. /**
  1049. * testLoginActionRedirect method
  1050. *
  1051. * @return void
  1052. * @triggers Controller.startup $this->Controller
  1053. */
  1054. public function testLoginActionRedirect()
  1055. {
  1056. $event = new Event('Controller.startup', $this->Controller);
  1057. Router::reload();
  1058. Router::prefix('admin', function ($routes) {
  1059. $routes->fallbacks(InflectedRoute::class);
  1060. });
  1061. Router::scope('/', function ($routes) {
  1062. $routes->fallbacks(InflectedRoute::class);
  1063. });
  1064. $url = '/admin/auth_test/login';
  1065. $request = new ServerRequest([
  1066. 'params' => [
  1067. 'plugin' => null,
  1068. 'controller' => 'auth_test',
  1069. 'action' => 'login',
  1070. 'prefix' => 'admin',
  1071. 'pass' => [],
  1072. ],
  1073. 'webroot' => '/',
  1074. 'url' => $url
  1075. ]);
  1076. Router::setRequestInfo($request);
  1077. $this->Auth->setConfig('loginAction', [
  1078. 'prefix' => 'admin',
  1079. 'controller' => 'auth_test',
  1080. 'action' => 'login'
  1081. ]);
  1082. $result = $this->Auth->startup($event);
  1083. $this->assertNull($result);
  1084. }
  1085. /**
  1086. * Stateless auth methods like Basic should populate data that can be
  1087. * accessed by $this->user().
  1088. *
  1089. * @return void
  1090. * @triggers Controller.startup $this->Controller
  1091. */
  1092. public function testStatelessAuthWorksWithUser()
  1093. {
  1094. $event = new Event('Controller.startup', $this->Controller);
  1095. $this->Controller->request = new ServerRequest([
  1096. 'environment' => [
  1097. 'REQUEST_METHOD' => 'POST',
  1098. 'PHP_AUTH_USER' => 'mariano',
  1099. 'PHP_AUTH_PW' => 'cake',
  1100. ],
  1101. 'params' => ['controller' => 'AuthTest', 'action' => 'add'],
  1102. 'url' => '/auth_test/add',
  1103. 'session' => $this->Auth->session
  1104. ]);
  1105. $this->Auth->setConfig('authenticate', [
  1106. 'Basic' => ['userModel' => 'AuthUsers']
  1107. ]);
  1108. $this->Auth->setConfig('storage', 'Memory');
  1109. $this->Auth->startup($event);
  1110. $result = $this->Auth->user();
  1111. $this->assertEquals('mariano', $result['username']);
  1112. $this->assertInstanceOf(
  1113. 'Cake\Auth\BasicAuthenticate',
  1114. $this->Auth->authenticationProvider()
  1115. );
  1116. $result = $this->Auth->user('username');
  1117. $this->assertEquals('mariano', $result);
  1118. $this->assertFalse(isset($_SESSION['Auth']), 'No user data in session');
  1119. }
  1120. /**
  1121. * test $settings in Controller::$components
  1122. *
  1123. * @return void
  1124. */
  1125. public function testComponentSettings()
  1126. {
  1127. $this->Auth->setConfig([
  1128. 'loginAction' => ['controller' => 'people', 'action' => 'login'],
  1129. 'logoutRedirect' => ['controller' => 'people', 'action' => 'login'],
  1130. ]);
  1131. $expected = [
  1132. 'loginAction' => ['controller' => 'people', 'action' => 'login'],
  1133. 'logoutRedirect' => ['controller' => 'people', 'action' => 'login'],
  1134. ];
  1135. $this->assertEquals(
  1136. $expected['loginAction'],
  1137. $this->Auth->getConfig('loginAction')
  1138. );
  1139. $this->assertEquals(
  1140. $expected['logoutRedirect'],
  1141. $this->Auth->getConfig('logoutRedirect')
  1142. );
  1143. }
  1144. /**
  1145. * test that logout deletes the session variables. and returns the correct URL
  1146. *
  1147. * @return void
  1148. */
  1149. public function testLogout()
  1150. {
  1151. $this->Auth->session->write('Auth.User.id', '1');
  1152. $this->Auth->setConfig('logoutRedirect', '/');
  1153. $result = $this->Auth->logout();
  1154. $this->assertEquals('/', $result);
  1155. $this->assertNull($this->Auth->session->read('Auth.AuthUsers'));
  1156. }
  1157. /**
  1158. * Test that Auth.afterIdentify and Auth.logout events are triggered
  1159. *
  1160. * @return void
  1161. */
  1162. public function testEventTriggering()
  1163. {
  1164. $this->Auth->setConfig('authenticate', [
  1165. 'Test' => ['className' => 'TestApp\Auth\TestAuthenticate']
  1166. ]);
  1167. $user = $this->Auth->identify();
  1168. $this->Auth->logout();
  1169. $authObject = $this->Auth->authenticationProvider();
  1170. $expected = ['afterIdentify', 'logout'];
  1171. $this->assertEquals($expected, $authObject->callStack);
  1172. $expected = ['id' => 1, 'username' => 'admad'];
  1173. $this->assertEquals($expected, $user);
  1174. $this->assertInstanceOf(
  1175. 'TestApp\Auth\TestAuthenticate',
  1176. $authObject->authenticationProvider
  1177. );
  1178. // Callback for Auth.afterIdentify returns a value
  1179. $authObject->modifiedUser = true;
  1180. $user = $this->Auth->identify();
  1181. $expected = ['id' => 1, 'username' => 'admad', 'extra' => 'foo'];
  1182. $this->assertEquals($expected, $user);
  1183. }
  1184. /**
  1185. * testAfterIdentifyForStatelessAuthentication
  1186. *
  1187. * @return void
  1188. * @triggers Controller.startup $this->Controller
  1189. */
  1190. public function testAfterIdentifyForStatelessAuthentication()
  1191. {
  1192. $event = new Event('Controller.startup', $this->Controller);
  1193. $url = '/auth_test/add';
  1194. $this->Controller->request = $this->Controller->request
  1195. ->withParam('controller', 'AuthTest')
  1196. ->withParam('action', 'add')
  1197. ->withEnv('PHP_AUTH_USER', 'mariano')
  1198. ->withEnv('PHP_AUTH_PW', 'cake');
  1199. $this->Auth->setConfig('authenticate', [
  1200. 'Basic' => ['userModel' => 'AuthUsers']
  1201. ]);
  1202. $this->Auth->setConfig('storage', 'Memory');
  1203. EventManager::instance()->on('Auth.afterIdentify', function (Event $event) {
  1204. $user = $event->getData(0);
  1205. $user['from_callback'] = true;
  1206. return $user;
  1207. });
  1208. $this->Auth->startup($event);
  1209. $this->assertEquals('mariano', $this->Auth->user('username'));
  1210. $this->assertTrue($this->Auth->user('from_callback'));
  1211. }
  1212. /**
  1213. * test setting user info to session.
  1214. *
  1215. * @return void
  1216. */
  1217. public function testSetUser()
  1218. {
  1219. $storage = $this->getMockBuilder('Cake\Auth\Storage\SessionStorage')
  1220. ->setMethods(['write'])
  1221. ->setConstructorArgs([$this->Controller->request, $this->Auth->response])
  1222. ->getMock();
  1223. $this->Auth->storage($storage);
  1224. $user = ['username' => 'mark', 'role' => 'admin'];
  1225. $storage->expects($this->once())
  1226. ->method('write')
  1227. ->with($user);
  1228. $this->Auth->setUser($user);
  1229. }
  1230. /**
  1231. * testGettingUserAfterSetUser
  1232. *
  1233. * @return void
  1234. */
  1235. public function testGettingUserAfterSetUser()
  1236. {
  1237. $this->assertFalse((bool)$this->Auth->user());
  1238. $user = [
  1239. 'username' => 'mariano',
  1240. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  1241. 'created' => new \DateTime('2007-03-17 01:16:23'),
  1242. 'updated' => new \DateTime('2007-03-17 01:18:31')
  1243. ];
  1244. $this->Auth->setUser($user);
  1245. $this->assertTrue((bool)$this->Auth->user());
  1246. $this->assertEquals($user['username'], $this->Auth->user('username'));
  1247. }
  1248. /**
  1249. * test flash settings.
  1250. *
  1251. * @return void
  1252. * @triggers Controller.startup $this->Controller)
  1253. */
  1254. public function testFlashSettings()
  1255. {
  1256. $this->Auth->Flash = $this->getMockBuilder('Cake\Controller\Component\FlashComponent')
  1257. ->setConstructorArgs([$this->Controller->components()])
  1258. ->getMock();
  1259. $this->Controller->request = $this->Controller->request->withParam('action', 'add');
  1260. $this->Auth->startup(new Event('Controller.startup', $this->Controller));
  1261. $this->Auth->Flash->expects($this->at(0))
  1262. ->method('set')
  1263. ->with(
  1264. 'Auth failure',
  1265. [
  1266. 'key' => 'auth-key',
  1267. 'element' => 'error',
  1268. 'params' => ['class' => 'error']
  1269. ]
  1270. );
  1271. $this->Auth->Flash->expects($this->at(1))
  1272. ->method('set')
  1273. ->with('Auth failure', ['key' => 'auth-key', 'element' => 'custom']);
  1274. $this->Auth->setConfig('flash', [
  1275. 'key' => 'auth-key'
  1276. ]);
  1277. $this->Auth->flash('Auth failure');
  1278. $this->Auth->setConfig('flash', [
  1279. 'key' => 'auth-key',
  1280. 'element' => 'custom'
  1281. ], false);
  1282. $this->Auth->flash('Auth failure');
  1283. }
  1284. /**
  1285. * test the various states of Auth::redirect()
  1286. *
  1287. * @return void
  1288. */
  1289. public function testRedirectSet()
  1290. {
  1291. $value = ['controller' => 'users', 'action' => 'home'];
  1292. $result = $this->Auth->redirectUrl($value);
  1293. $this->assertEquals('/users/home', $result);
  1294. }
  1295. /**
  1296. * Tests redirect using redirect key from the query string.
  1297. *
  1298. * @return void
  1299. */
  1300. public function testRedirectQueryStringRead()
  1301. {
  1302. $this->Auth->setConfig('loginAction', ['controller' => 'users', 'action' => 'login']);
  1303. $this->Controller->request = $this->Controller->request->withQueryParams(['redirect' => '/users/custom']);
  1304. $result = $this->Auth->redirectUrl();
  1305. $this->assertEquals('/users/custom', $result);
  1306. }
  1307. /**
  1308. * Tests redirectUrl with duplicate base.
  1309. *
  1310. * @return void
  1311. */
  1312. public function testRedirectQueryStringReadDuplicateBase()
  1313. {
  1314. $this->Controller->request = $this->Controller->request
  1315. ->withAttribute('webroot', '/waves/')
  1316. ->withAttribute('base', '/waves')
  1317. ->withQueryParams(['redirect' => '/waves/add']);
  1318. Router::setRequestInfo($this->Controller->request);
  1319. $result = $this->Auth->redirectUrl();
  1320. $this->assertEquals('/waves/add', $result);
  1321. }
  1322. /**
  1323. * test that redirect does not return loginAction if that is what's passed as redirect.
  1324. * instead loginRedirect should be used.
  1325. *
  1326. * @return void
  1327. */
  1328. public function testRedirectQueryStringReadEqualToLoginAction()
  1329. {
  1330. $this->Auth->setConfig([
  1331. 'loginAction' => ['controller' => 'users', 'action' => 'login'],
  1332. 'loginRedirect' => ['controller' => 'users', 'action' => 'home']
  1333. ]);
  1334. $this->Controller->request = $this->Controller->request->withQueryParams(['redirect' => '/users/login']);
  1335. $result = $this->Auth->redirectUrl();
  1336. $this->assertEquals('/users/home', $result);
  1337. }
  1338. /**
  1339. * Tests that redirect does not return loginAction if that contains a host,
  1340. * instead loginRedirect should be used.
  1341. *
  1342. * @return void
  1343. */
  1344. public function testRedirectQueryStringInvalid()
  1345. {
  1346. $this->Auth->setConfig([
  1347. 'loginAction' => ['controller' => 'users', 'action' => 'login'],
  1348. 'loginRedirect' => ['controller' => 'users', 'action' => 'home']
  1349. ]);
  1350. $this->Controller->request = $this->Controller->request->withQueryParams(['redirect' => 'http://some.domain.example/users/login']);
  1351. $result = $this->Auth->redirectUrl();
  1352. $this->assertEquals('/users/home', $result);
  1353. $this->Controller->request = $this->Controller->request->withQueryParams(['redirect' => '//some.domain.example/users/login']);
  1354. $result = $this->Auth->redirectUrl();
  1355. $this->assertEquals('/users/home', $result);
  1356. }
  1357. /**
  1358. * test that the returned URL doesn't contain the base URL.
  1359. *
  1360. * @return void This test method doesn't return anything.
  1361. */
  1362. public function testRedirectUrlWithBaseSet()
  1363. {
  1364. $App = Configure::read('App');
  1365. Configure::write('App', [
  1366. 'dir' => APP_DIR,
  1367. 'webroot' => 'webroot',
  1368. 'base' => false,
  1369. 'baseUrl' => '/cake/index.php'
  1370. ]);
  1371. $url = '/users/login';
  1372. $this->Controller->request = $this->Controller->request = new ServerRequest([
  1373. 'url' => $url,
  1374. 'params' => ['plugin' => null, 'controller' => 'Users', 'action' => 'login']
  1375. ]);
  1376. Router::setRequestInfo($this->Controller->request);
  1377. $this->Auth->setConfig('loginAction', ['controller' => 'users', 'action' => 'login']);
  1378. $this->Auth->setConfig('loginRedirect', ['controller' => 'users', 'action' => 'home']);
  1379. $result = $this->Auth->redirectUrl();
  1380. $this->assertEquals('/users/home', $result);
  1381. Configure::write('App', $App);
  1382. Router::reload();
  1383. }
  1384. /**
  1385. * testUser method
  1386. *
  1387. * @return void
  1388. */
  1389. public function testUser()
  1390. {
  1391. $data = [
  1392. 'User' => [
  1393. 'id' => '2',
  1394. 'username' => 'mark',
  1395. 'group_id' => 1,
  1396. 'Group' => [
  1397. 'id' => '1',
  1398. 'name' => 'Members'
  1399. ],
  1400. 'is_admin' => false,
  1401. ]];
  1402. $this->Auth->session->write('Auth', $data);
  1403. $result = $this->Auth->user();
  1404. $this->assertEquals($data['User'], $result);
  1405. $result = $this->Auth->user('username');
  1406. $this->assertEquals($data['User']['username'], $result);
  1407. $result = $this->Auth->user('Group.name');
  1408. $this->assertEquals($data['User']['Group']['name'], $result);
  1409. $result = $this->Auth->user('invalid');
  1410. $this->assertNull($result);
  1411. $result = $this->Auth->user('Company.invalid');
  1412. $this->assertNull($result);
  1413. $result = $this->Auth->user('is_admin');
  1414. $this->assertFalse($result);
  1415. }
  1416. /**
  1417. * testStatelessAuthNoRedirect method
  1418. *
  1419. * @return void
  1420. * @triggers Controller.startup $this->Controller
  1421. */
  1422. public function testStatelessAuthNoRedirect()
  1423. {
  1424. $this->expectException(\Cake\Http\Exception\UnauthorizedException::class);
  1425. $this->expectExceptionCode(401);
  1426. $event = new Event('Controller.startup', $this->Controller);
  1427. $_SESSION = [];
  1428. $this->Auth->setConfig('authenticate', ['Basic']);
  1429. $this->Controller->request = $this->Controller->request->withParam('action', 'add');
  1430. $result = $this->Auth->startup($event);
  1431. }
  1432. /**
  1433. * testStatelessAuthRedirect method
  1434. *
  1435. * @return void
  1436. * @triggers Controller.startup $this->Controller
  1437. */
  1438. public function testStatelessAuthRedirectToLogin()
  1439. {
  1440. $event = new Event('Controller.startup', $this->Controller);
  1441. $this->Auth->authenticate = ['Basic', 'Form'];
  1442. $this->Controller->request = $this->Controller->request->withParam('action', 'add');
  1443. $response = $this->Auth->startup($event);
  1444. $this->assertInstanceOf(Response::class, $response);
  1445. $this->assertEquals(
  1446. 'http://localhost/users/login?redirect=%2Fauth_test',
  1447. $response->getHeaderLine('Location')
  1448. );
  1449. }
  1450. /**
  1451. * test for BC getting/setting AuthComponent::$sessionKey gets/sets `key`
  1452. * config of session storage.
  1453. *
  1454. * @return void
  1455. */
  1456. public function testSessionKeyBC()
  1457. {
  1458. $this->assertEquals('Auth.User', $this->Auth->sessionKey);
  1459. $this->Auth->sessionKey = 'Auth.Member';
  1460. $this->assertEquals('Auth.Member', $this->Auth->sessionKey);
  1461. $this->assertEquals('Auth.Member', $this->Auth->storage()->getConfig('key'));
  1462. $this->Auth->sessionKey = false;
  1463. $this->assertInstanceOf('Cake\Auth\Storage\MemoryStorage', $this->Auth->storage());
  1464. }
  1465. /**
  1466. * Test that setting config 'earlyAuth' to true make AuthComponent do the initial
  1467. * checks in beforeFilter() instead of startup().
  1468. *
  1469. * @return void
  1470. */
  1471. public function testCheckAuthInConfig()
  1472. {
  1473. $this->Controller->components()->set('Auth', $this->Auth);
  1474. $this->Auth->earlyAuthTest = true;
  1475. $this->Auth->authCheckCalledFrom = null;
  1476. $this->Controller->startupProcess();
  1477. $this->assertEquals('Controller.startup', $this->Auth->authCheckCalledFrom);
  1478. $this->Auth->authCheckCalledFrom = null;
  1479. $this->Auth->setConfig('checkAuthIn', 'Controller.initialize');
  1480. $this->Controller->startupProcess();
  1481. $this->assertEquals('Controller.initialize', $this->Auth->authCheckCalledFrom);
  1482. }
  1483. }