AuthComponentTest.php 59 KB

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