AuthComponentTest.php 50 KB

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