AuthComponentTest.php 59 KB

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