AuthComponentTest.php 59 KB

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