AuthComponentTest.php 59 KB

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