AuthComponentTest.php 57 KB

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