AuthComponent.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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 0.10.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Controller\Component;
  16. use Cake\Auth\Storage\StorageInterface;
  17. use Cake\Controller\Component;
  18. use Cake\Controller\Controller;
  19. use Cake\Core\App;
  20. use Cake\Core\Exception\Exception;
  21. use Cake\Event\Event;
  22. use Cake\Event\EventDispatcherTrait;
  23. use Cake\Network\Exception\ForbiddenException;
  24. use Cake\Network\Request;
  25. use Cake\Network\Response;
  26. use Cake\Routing\Router;
  27. use Cake\Utility\Hash;
  28. /**
  29. * Authentication control component class.
  30. *
  31. * Binds access control with user authentication and session management.
  32. *
  33. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html
  34. */
  35. class AuthComponent extends Component
  36. {
  37. use EventDispatcherTrait;
  38. /**
  39. * The query string key used for remembering the referrered page when getting
  40. * redirected to login.
  41. */
  42. const QUERY_STRING_REDIRECT = 'redirect';
  43. /**
  44. * Constant for 'all'
  45. *
  46. * @var string
  47. */
  48. const ALL = 'all';
  49. /**
  50. * Default config
  51. *
  52. * - `authenticate` - An array of authentication objects to use for authenticating users.
  53. * You can configure multiple adapters and they will be checked sequentially
  54. * when users are identified.
  55. *
  56. * ```
  57. * $this->Auth->config('authenticate', [
  58. * 'Form' => [
  59. * 'userModel' => 'Users.Users'
  60. * ]
  61. * ]);
  62. * ```
  63. *
  64. * Using the class name without 'Authenticate' as the key, you can pass in an
  65. * array of config for each authentication object. Additionally you can define
  66. * config that should be set to all authentications objects using the 'all' key:
  67. *
  68. * ```
  69. * $this->Auth->config('authenticate', [
  70. * AuthComponent::ALL => [
  71. * 'userModel' => 'Users.Users',
  72. * 'scope' => ['Users.active' => 1]
  73. * ],
  74. * 'Form',
  75. * 'Basic'
  76. * ]);
  77. * ```
  78. *
  79. * - `authorize` - An array of authorization objects to use for authorizing users.
  80. * You can configure multiple adapters and they will be checked sequentially
  81. * when authorization checks are done.
  82. *
  83. * ```
  84. * $this->Auth->config('authorize', [
  85. * 'Crud' => [
  86. * 'actionPath' => 'controllers/'
  87. * ]
  88. * ]);
  89. * ```
  90. *
  91. * Using the class name without 'Authorize' as the key, you can pass in an array
  92. * of config for each authorization object. Additionally you can define config
  93. * that should be set to all authorization objects using the AuthComponent::ALL key:
  94. *
  95. * ```
  96. * $this->Auth->config('authorize', [
  97. * AuthComponent::ALL => [
  98. * 'actionPath' => 'controllers/'
  99. * ],
  100. * 'Crud',
  101. * 'CustomAuth'
  102. * ]);
  103. * ```
  104. *
  105. * - `ajaxLogin` - The name of an optional view element to render when an Ajax
  106. * request is made with an invalid or expired session.
  107. *
  108. * - `flash` - Settings to use when Auth needs to do a flash message with
  109. * FlashComponent::set(). Available keys are:
  110. *
  111. * - `key` - The message domain to use for flashes generated by this component,
  112. * defaults to 'auth'.
  113. * - `element` - Flash element to use, defaults to 'default'.
  114. * - `params` - The array of additional params to use, defaults to ['class' => 'error']
  115. *
  116. * - `loginAction` - A URL (defined as a string or array) to the controller action
  117. * that handles logins. Defaults to `/users/login`.
  118. *
  119. * - `loginRedirect` - Normally, if a user is redirected to the `loginAction` page,
  120. * the location they were redirected from will be stored in the session so that
  121. * they can be redirected back after a successful login. If this session value
  122. * is not set, redirectUrl() method will return the URL specified in `loginRedirect`.
  123. *
  124. * - `logoutRedirect` - The default action to redirect to after the user is logged out.
  125. * While AuthComponent does not handle post-logout redirection, a redirect URL
  126. * will be returned from `AuthComponent::logout()`. Defaults to `loginAction`.
  127. *
  128. * - `authError` - Error to display when user attempts to access an object or
  129. * action to which they do not have access.
  130. *
  131. * - `unauthorizedRedirect` - Controls handling of unauthorized access.
  132. *
  133. * - For default value `true` unauthorized user is redirected to the referrer URL
  134. * or `$loginRedirect` or '/'.
  135. * - If set to a string or array the value is used as a URL to redirect to.
  136. * - If set to false a `ForbiddenException` exception is thrown instead of redirecting.
  137. *
  138. * - `storage` - Storage class to use for persisting user record. When using
  139. * stateless authenticator you should set this to 'Memory'. Defaults to 'Session'.
  140. *
  141. * - `checkAuthIn` - Name of event for which initial auth checks should be done.
  142. * Defaults to 'Controller.startup'. You can set it to 'Controller.initialize'
  143. * if you want the check to be done before controller's beforeFilter() is run.
  144. *
  145. * @var array
  146. */
  147. protected $_defaultConfig = [
  148. 'authenticate' => null,
  149. 'authorize' => null,
  150. 'ajaxLogin' => null,
  151. 'flash' => null,
  152. 'loginAction' => null,
  153. 'loginRedirect' => null,
  154. 'logoutRedirect' => null,
  155. 'authError' => null,
  156. 'unauthorizedRedirect' => true,
  157. 'storage' => 'Session',
  158. 'checkAuthIn' => 'Controller.startup'
  159. ];
  160. /**
  161. * Other components utilized by AuthComponent
  162. *
  163. * @var array
  164. */
  165. public $components = ['RequestHandler', 'Flash'];
  166. /**
  167. * Objects that will be used for authentication checks.
  168. *
  169. * @var array
  170. */
  171. protected $_authenticateObjects = [];
  172. /**
  173. * Objects that will be used for authorization checks.
  174. *
  175. * @var array
  176. */
  177. protected $_authorizeObjects = [];
  178. /**
  179. * Storage object.
  180. *
  181. * @var \Cake\Auth\Storage\StorageInterface
  182. */
  183. protected $_storage;
  184. /**
  185. * Controller actions for which user validation is not required.
  186. *
  187. * @var array
  188. * @see \Cake\Controller\Component\AuthComponent::allow()
  189. */
  190. public $allowedActions = [];
  191. /**
  192. * Request object
  193. *
  194. * @var \Cake\Network\Request
  195. */
  196. public $request;
  197. /**
  198. * Response object
  199. *
  200. * @var \Cake\Network\Response
  201. */
  202. public $response;
  203. /**
  204. * Instance of the Session object
  205. *
  206. * @var \Cake\Network\Session
  207. * @deprecated 3.1.0 Will be removed in 4.0
  208. */
  209. public $session;
  210. /**
  211. * The instance of the Authenticate provider that was used for
  212. * successfully logging in the current user after calling `login()`
  213. * in the same request
  214. *
  215. * @var \Cake\Auth\BaseAuthenticate
  216. */
  217. protected $_authenticationProvider;
  218. /**
  219. * The instance of the Authorize provider that was used to grant
  220. * access to the current user to the URL they are requesting.
  221. *
  222. * @var \Cake\Auth\BaseAuthorize
  223. */
  224. protected $_authorizationProvider;
  225. /**
  226. * Initialize properties.
  227. *
  228. * @param array $config The config data.
  229. * @return void
  230. */
  231. public function initialize(array $config)
  232. {
  233. $controller = $this->_registry->getController();
  234. $this->eventManager($controller->eventManager());
  235. $this->response =& $controller->response;
  236. $this->session = $controller->request->session();
  237. }
  238. /**
  239. * Callback for Controller.startup event.
  240. *
  241. * @param \Cake\Event\Event $event Event instance.
  242. * @return \Cake\Network\Response|null
  243. */
  244. public function startup(Event $event)
  245. {
  246. return $this->authCheck($event);
  247. }
  248. /**
  249. * Main execution method, handles initial authentication check and redirection
  250. * of invalid users.
  251. *
  252. * The auth check is done when event name is same as the one configured in
  253. * `checkAuthIn` config.
  254. *
  255. * @param \Cake\Event\Event $event Event instance.
  256. * @return \Cake\Network\Response|null
  257. */
  258. public function authCheck(Event $event)
  259. {
  260. if ($this->_config['checkAuthIn'] !== $event->name()) {
  261. return null;
  262. }
  263. $controller = $event->subject();
  264. $action = strtolower($controller->request->params['action']);
  265. if (!$controller->isAction($action)) {
  266. return null;
  267. }
  268. $this->_setDefaults();
  269. if ($this->_isAllowed($controller)) {
  270. return null;
  271. }
  272. $isLoginAction = $this->_isLoginAction($controller);
  273. if (!$this->_getUser()) {
  274. if ($isLoginAction) {
  275. return null;
  276. }
  277. $result = $this->_unauthenticated($controller);
  278. if ($result instanceof Response) {
  279. $event->stopPropagation();
  280. }
  281. return $result;
  282. }
  283. if ($isLoginAction ||
  284. empty($this->_config['authorize']) ||
  285. $this->isAuthorized($this->user())
  286. ) {
  287. return null;
  288. }
  289. $event->stopPropagation();
  290. return $this->_unauthorized($controller);
  291. }
  292. /**
  293. * Events supported by this component.
  294. *
  295. * @return array
  296. */
  297. public function implementedEvents()
  298. {
  299. return [
  300. 'Controller.initialize' => 'authCheck',
  301. 'Controller.startup' => 'startup',
  302. ];
  303. }
  304. /**
  305. * Checks whether current action is accessible without authentication.
  306. *
  307. * @param \Cake\Controller\Controller $controller A reference to the instantiating
  308. * controller object
  309. * @return bool True if action is accessible without authentication else false
  310. */
  311. protected function _isAllowed(Controller $controller)
  312. {
  313. $action = strtolower($controller->request->params['action']);
  314. return in_array($action, array_map('strtolower', $this->allowedActions));
  315. }
  316. /**
  317. * Handles unauthenticated access attempt. First the `unauthenticated()` method
  318. * of the last authenticator in the chain will be called. The authenticator can
  319. * handle sending response or redirection as appropriate and return `true` to
  320. * indicate no further action is necessary. If authenticator returns null this
  321. * method redirects user to login action. If it's an AJAX request and config
  322. * `ajaxLogin` is specified that element is rendered else a 403 HTTP status code
  323. * is returned.
  324. *
  325. * @param \Cake\Controller\Controller $controller A reference to the controller object.
  326. * @return \Cake\Network\Response|null Null if current action is login action
  327. * else response object returned by authenticate object or Controller::redirect().
  328. */
  329. protected function _unauthenticated(Controller $controller)
  330. {
  331. if (empty($this->_authenticateObjects)) {
  332. $this->constructAuthenticate();
  333. }
  334. $auth = end($this->_authenticateObjects);
  335. $result = $auth->unauthenticated($this->request, $this->response);
  336. if ($result !== null) {
  337. return $result;
  338. }
  339. if (!$controller->request->is('ajax')) {
  340. $this->flash($this->_config['authError']);
  341. return $controller->redirect($this->_loginActionRedirectUrl());
  342. }
  343. if (!empty($this->_config['ajaxLogin'])) {
  344. $controller->viewBuilder()->templatePath('Element');
  345. $response = $controller->render(
  346. $this->_config['ajaxLogin'],
  347. $this->RequestHandler->ajaxLayout
  348. );
  349. $response->statusCode(403);
  350. return $response;
  351. }
  352. $this->response->statusCode(403);
  353. return $this->response;
  354. }
  355. /**
  356. * Returns the URL of the login action to redirect to.
  357. *
  358. * This includes the redirect query string if applicable.
  359. *
  360. * @return array|string
  361. */
  362. protected function _loginActionRedirectUrl()
  363. {
  364. $currentUrl = $this->request->here(false);
  365. $loginAction = $this->_config['loginAction'];
  366. if (is_array($loginAction)) {
  367. $loginAction['?'][static::QUERY_STRING_REDIRECT] = $currentUrl;
  368. } else {
  369. $loginAction .= '?' . static::QUERY_STRING_REDIRECT . '=' . rawurlencode($currentUrl);
  370. }
  371. return $loginAction;
  372. }
  373. /**
  374. * Normalizes config `loginAction` and checks if current request URL is same as login action.
  375. *
  376. * @param \Cake\Controller\Controller $controller A reference to the controller object.
  377. * @return bool True if current action is login action else false.
  378. */
  379. protected function _isLoginAction(Controller $controller)
  380. {
  381. $url = '';
  382. if (isset($controller->request->url)) {
  383. $url = $controller->request->url;
  384. }
  385. $url = Router::normalize($url);
  386. $loginAction = Router::normalize($this->_config['loginAction']);
  387. return $loginAction === $url;
  388. }
  389. /**
  390. * Handle unauthorized access attempt
  391. *
  392. * @param \Cake\Controller\Controller $controller A reference to the controller object
  393. * @return \Cake\Network\Response
  394. * @throws \Cake\Network\Exception\ForbiddenException
  395. */
  396. protected function _unauthorized(Controller $controller)
  397. {
  398. if ($this->_config['unauthorizedRedirect'] === false) {
  399. throw new ForbiddenException($this->_config['authError']);
  400. }
  401. $this->flash($this->_config['authError']);
  402. if ($this->_config['unauthorizedRedirect'] === true) {
  403. $default = '/';
  404. if (!empty($this->_config['loginRedirect'])) {
  405. $default = $this->_config['loginRedirect'];
  406. }
  407. if (is_array($default)) {
  408. $default['_base'] = false;
  409. }
  410. $url = $controller->referer($default, true);
  411. } else {
  412. $url = $this->_config['unauthorizedRedirect'];
  413. }
  414. return $controller->redirect($url);
  415. }
  416. /**
  417. * Sets defaults for configs.
  418. *
  419. * @return void
  420. */
  421. protected function _setDefaults()
  422. {
  423. $defaults = [
  424. 'authenticate' => ['Form'],
  425. 'flash' => [
  426. 'element' => 'default',
  427. 'key' => 'auth',
  428. 'params' => ['class' => 'error']
  429. ],
  430. 'loginAction' => [
  431. 'controller' => 'Users',
  432. 'action' => 'login',
  433. 'plugin' => null
  434. ],
  435. 'logoutRedirect' => $this->_config['loginAction'],
  436. 'authError' => __d('cake', 'You are not authorized to access that location.')
  437. ];
  438. $config = $this->config();
  439. foreach ($config as $key => $value) {
  440. if ($value !== null) {
  441. unset($defaults[$key]);
  442. }
  443. }
  444. $this->config($defaults);
  445. }
  446. /**
  447. * Check if the provided user is authorized for the request.
  448. *
  449. * Uses the configured Authorization adapters to check whether or not a user is authorized.
  450. * Each adapter will be checked in sequence, if any of them return true, then the user will
  451. * be authorized for the request.
  452. *
  453. * @param array|\ArrayAccess|null $user The user to check the authorization of.
  454. * If empty the user fetched from storage will be used.
  455. * @param \Cake\Network\Request|null $request The request to authenticate for.
  456. * If empty, the current request will be used.
  457. * @return bool True if $user is authorized, otherwise false
  458. */
  459. public function isAuthorized($user = null, Request $request = null)
  460. {
  461. if (empty($user) && !$this->user()) {
  462. return false;
  463. }
  464. if (empty($user)) {
  465. $user = $this->user();
  466. }
  467. if (empty($request)) {
  468. $request = $this->request;
  469. }
  470. if (empty($this->_authorizeObjects)) {
  471. $this->constructAuthorize();
  472. }
  473. foreach ($this->_authorizeObjects as $authorizer) {
  474. if ($authorizer->authorize($user, $request) === true) {
  475. $this->_authorizationProvider = $authorizer;
  476. return true;
  477. }
  478. }
  479. return false;
  480. }
  481. /**
  482. * Loads the authorization objects configured.
  483. *
  484. * @return array|null The loaded authorization objects, or null when authorize is empty.
  485. * @throws \Cake\Core\Exception\Exception
  486. */
  487. public function constructAuthorize()
  488. {
  489. if (empty($this->_config['authorize'])) {
  490. return null;
  491. }
  492. $this->_authorizeObjects = [];
  493. $authorize = Hash::normalize((array)$this->_config['authorize']);
  494. $global = [];
  495. if (isset($authorize[AuthComponent::ALL])) {
  496. $global = $authorize[AuthComponent::ALL];
  497. unset($authorize[AuthComponent::ALL]);
  498. }
  499. foreach ($authorize as $alias => $config) {
  500. if (!empty($config['className'])) {
  501. $class = $config['className'];
  502. unset($config['className']);
  503. } else {
  504. $class = $alias;
  505. }
  506. $className = App::className($class, 'Auth', 'Authorize');
  507. if (!class_exists($className)) {
  508. throw new Exception(sprintf('Authorization adapter "%s" was not found.', $class));
  509. }
  510. if (!method_exists($className, 'authorize')) {
  511. throw new Exception('Authorization objects must implement an authorize() method.');
  512. }
  513. $config = (array)$config + $global;
  514. $this->_authorizeObjects[$alias] = new $className($this->_registry, $config);
  515. }
  516. return $this->_authorizeObjects;
  517. }
  518. /**
  519. * Getter for authorize objects. Will return a particular authorize object.
  520. *
  521. * @param string $alias Alias for the authorize object
  522. * @return \Cake\Auth\BaseAuthorize|null
  523. */
  524. public function getAuthorize($alias)
  525. {
  526. if (empty($this->_authorizeObjects)) {
  527. $this->constructAuthorize();
  528. }
  529. return isset($this->_authorizeObjects[$alias]) ? $this->_authorizeObjects[$alias] : null;
  530. }
  531. /**
  532. * Takes a list of actions in the current controller for which authentication is not required, or
  533. * no parameters to allow all actions.
  534. *
  535. * You can use allow with either an array or a simple string.
  536. *
  537. * ```
  538. * $this->Auth->allow('view');
  539. * $this->Auth->allow(['edit', 'add']);
  540. * ```
  541. * or to allow all actions
  542. * ```
  543. * $this->Auth->allow();
  544. * ```
  545. *
  546. * @param string|array|null $actions Controller action name or array of actions
  547. * @return void
  548. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#making-actions-public
  549. */
  550. public function allow($actions = null)
  551. {
  552. if ($actions === null) {
  553. $controller = $this->_registry->getController();
  554. $this->allowedActions = get_class_methods($controller);
  555. return;
  556. }
  557. $this->allowedActions = array_merge($this->allowedActions, (array)$actions);
  558. }
  559. /**
  560. * Removes items from the list of allowed/no authentication required actions.
  561. *
  562. * You can use deny with either an array or a simple string.
  563. *
  564. * ```
  565. * $this->Auth->deny('view');
  566. * $this->Auth->deny(['edit', 'add']);
  567. * ```
  568. * or
  569. * ```
  570. * $this->Auth->deny();
  571. * ```
  572. * to remove all items from the allowed list
  573. *
  574. * @param string|array|null $actions Controller action name or array of actions
  575. * @return void
  576. * @see \Cake\Controller\Component\AuthComponent::allow()
  577. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#making-actions-require-authorization
  578. */
  579. public function deny($actions = null)
  580. {
  581. if ($actions === null) {
  582. $this->allowedActions = [];
  583. return;
  584. }
  585. foreach ((array)$actions as $action) {
  586. $i = array_search($action, $this->allowedActions);
  587. if (is_int($i)) {
  588. unset($this->allowedActions[$i]);
  589. }
  590. }
  591. $this->allowedActions = array_values($this->allowedActions);
  592. }
  593. /**
  594. * Set provided user info to storage as logged in user.
  595. *
  596. * The storage class is configured using `storage` config key or passing
  597. * instance to AuthComponent::storage().
  598. *
  599. * @param array|\ArrayAccess $user User data.
  600. * @return void
  601. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#identifying-users-and-logging-them-in
  602. */
  603. public function setUser($user)
  604. {
  605. $this->storage()->write($user);
  606. }
  607. /**
  608. * Log a user out.
  609. *
  610. * Returns the logout action to redirect to. Triggers the `Auth.logout` event
  611. * which the authenticate classes can listen for and perform custom logout logic.
  612. *
  613. * @return string Normalized config `logoutRedirect`
  614. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#logging-users-out
  615. */
  616. public function logout()
  617. {
  618. $this->_setDefaults();
  619. if (empty($this->_authenticateObjects)) {
  620. $this->constructAuthenticate();
  621. }
  622. $user = (array)$this->user();
  623. $this->dispatchEvent('Auth.logout', [$user]);
  624. $this->storage()->delete();
  625. return Router::normalize($this->_config['logoutRedirect']);
  626. }
  627. /**
  628. * Get the current user from storage.
  629. *
  630. * @param string|null $key Field to retrieve. Leave null to get entire User record.
  631. * @return mixed|null Either User record or null if no user is logged in, or retrieved field if key is specified.
  632. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#accessing-the-logged-in-user
  633. */
  634. public function user($key = null)
  635. {
  636. $user = $this->storage()->read();
  637. if (!$user) {
  638. return null;
  639. }
  640. if ($key === null) {
  641. return $user;
  642. }
  643. return Hash::get($user, $key);
  644. }
  645. /**
  646. * Similar to AuthComponent::user() except if user is not found in
  647. * configured storage, connected authentication objects will have their
  648. * getUser() methods called.
  649. *
  650. * This lets stateless authentication methods function correctly.
  651. *
  652. * @return bool true If a user can be found, false if one cannot.
  653. */
  654. protected function _getUser()
  655. {
  656. $user = $this->user();
  657. if ($user) {
  658. return true;
  659. }
  660. if (empty($this->_authenticateObjects)) {
  661. $this->constructAuthenticate();
  662. }
  663. foreach ($this->_authenticateObjects as $auth) {
  664. $result = $auth->getUser($this->request);
  665. if (!empty($result) && is_array($result)) {
  666. $this->_authenticationProvider = $auth;
  667. $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]);
  668. if ($event->result() !== null) {
  669. $result = $event->result();
  670. }
  671. $this->storage()->write($result);
  672. return true;
  673. }
  674. }
  675. return false;
  676. }
  677. /**
  678. * Get the URL a user should be redirected to upon login.
  679. *
  680. * Pass a URL in to set the destination a user should be redirected to upon
  681. * logging in.
  682. *
  683. * If no parameter is passed, gets the authentication redirect URL. The URL
  684. * returned is as per following rules:
  685. *
  686. * - Returns the normalized redirect URL from storage if it is
  687. * present and for the same domain the current app is running on.
  688. * - If there is no URL returned from storage and there is a config
  689. * `loginRedirect`, the `loginRedirect` value is returned.
  690. * - If there is no session and no `loginRedirect`, / is returned.
  691. *
  692. * @param string|array|null $url Optional URL to write as the login redirect URL.
  693. * @return string Redirect URL
  694. */
  695. public function redirectUrl($url = null)
  696. {
  697. $redirectUrl = $this->request->query(static::QUERY_STRING_REDIRECT);
  698. if ($redirectUrl && (substr($redirectUrl, 0, 1) !== '/')) {
  699. $redirectUrl = null;
  700. }
  701. if ($url !== null) {
  702. $redirectUrl = $url;
  703. } elseif ($redirectUrl) {
  704. if (Router::normalize($redirectUrl) === Router::normalize($this->_config['loginAction'])) {
  705. $redirectUrl = $this->_config['loginRedirect'];
  706. }
  707. } elseif ($this->_config['loginRedirect']) {
  708. $redirectUrl = $this->_config['loginRedirect'];
  709. } else {
  710. $redirectUrl = '/';
  711. }
  712. if (is_array($redirectUrl)) {
  713. return Router::url($redirectUrl + ['_base' => false]);
  714. }
  715. return $redirectUrl;
  716. }
  717. /**
  718. * Use the configured authentication adapters, and attempt to identify the user
  719. * by credentials contained in $request.
  720. *
  721. * Triggers `Auth.afterIdentify` event which the authenticate classes can listen
  722. * to.
  723. *
  724. * @return array|bool User record data, or false, if the user could not be identified.
  725. */
  726. public function identify()
  727. {
  728. $this->_setDefaults();
  729. if (empty($this->_authenticateObjects)) {
  730. $this->constructAuthenticate();
  731. }
  732. foreach ($this->_authenticateObjects as $auth) {
  733. $result = $auth->authenticate($this->request, $this->response);
  734. if (!empty($result)) {
  735. $this->_authenticationProvider = $auth;
  736. $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]);
  737. if ($event->result() !== null) {
  738. return $event->result();
  739. }
  740. return $result;
  741. }
  742. }
  743. return false;
  744. }
  745. /**
  746. * Loads the configured authentication objects.
  747. *
  748. * @return array|null The loaded authorization objects, or null on empty authenticate value.
  749. * @throws \Cake\Core\Exception\Exception
  750. */
  751. public function constructAuthenticate()
  752. {
  753. if (empty($this->_config['authenticate'])) {
  754. return null;
  755. }
  756. $this->_authenticateObjects = [];
  757. $authenticate = Hash::normalize((array)$this->_config['authenticate']);
  758. $global = [];
  759. if (isset($authenticate[AuthComponent::ALL])) {
  760. $global = $authenticate[AuthComponent::ALL];
  761. unset($authenticate[AuthComponent::ALL]);
  762. }
  763. foreach ($authenticate as $alias => $config) {
  764. if (!empty($config['className'])) {
  765. $class = $config['className'];
  766. unset($config['className']);
  767. } else {
  768. $class = $alias;
  769. }
  770. $className = App::className($class, 'Auth', 'Authenticate');
  771. if (!class_exists($className)) {
  772. throw new Exception(sprintf('Authentication adapter "%s" was not found.', $class));
  773. }
  774. if (!method_exists($className, 'authenticate')) {
  775. throw new Exception('Authentication objects must implement an authenticate() method.');
  776. }
  777. $config = array_merge($global, (array)$config);
  778. $this->_authenticateObjects[$alias] = new $className($this->_registry, $config);
  779. $this->eventManager()->on($this->_authenticateObjects[$alias]);
  780. }
  781. return $this->_authenticateObjects;
  782. }
  783. /**
  784. * Get/set user record storage object.
  785. *
  786. * @param \Cake\Auth\Storage\StorageInterface|null $storage Sets provided
  787. * object as storage or if null returns configured storage object.
  788. * @return \Cake\Auth\Storage\StorageInterface|null
  789. */
  790. public function storage(StorageInterface $storage = null)
  791. {
  792. if ($storage !== null) {
  793. $this->_storage = $storage;
  794. return null;
  795. }
  796. if ($this->_storage) {
  797. return $this->_storage;
  798. }
  799. $config = $this->_config['storage'];
  800. if (is_string($config)) {
  801. $class = $config;
  802. $config = [];
  803. } else {
  804. $class = $config['className'];
  805. unset($config['className']);
  806. }
  807. $className = App::className($class, 'Auth/Storage', 'Storage');
  808. if (!class_exists($className)) {
  809. throw new Exception(sprintf('Auth storage adapter "%s" was not found.', $class));
  810. }
  811. $this->_storage = new $className($this->request, $this->response, $config);
  812. return $this->_storage;
  813. }
  814. /**
  815. * Magic accessor for backward compatibility for property `$sessionKey`.
  816. *
  817. * @param string $name Property name
  818. * @return mixed
  819. */
  820. public function __get($name)
  821. {
  822. if ($name === 'sessionKey') {
  823. return $this->storage()->config('key');
  824. }
  825. return parent::__get($name);
  826. }
  827. /**
  828. * Magic setter for backward compatibility for property `$sessionKey`.
  829. *
  830. * @param string $name Property name.
  831. * @param mixed $value Value to set.
  832. * @return void
  833. */
  834. public function __set($name, $value)
  835. {
  836. if ($name === 'sessionKey') {
  837. $this->_storage = null;
  838. if ($value === false) {
  839. $this->config('storage', 'Memory');
  840. return;
  841. }
  842. $this->config('storage', 'Session');
  843. $this->storage()->config('key', $value);
  844. return;
  845. }
  846. $this->{$name} = $value;
  847. }
  848. /**
  849. * Getter for authenticate objects. Will return a particular authenticate object.
  850. *
  851. * @param string $alias Alias for the authenticate object
  852. *
  853. * @return \Cake\Auth\BaseAuthenticate|null
  854. */
  855. public function getAuthenticate($alias)
  856. {
  857. if (empty($this->_authenticateObjects)) {
  858. $this->constructAuthenticate();
  859. }
  860. return isset($this->_authenticateObjects[$alias]) ? $this->_authenticateObjects[$alias] : null;
  861. }
  862. /**
  863. * Set a flash message. Uses the Flash component with values from `flash` config.
  864. *
  865. * @param string $message The message to set.
  866. * @return void
  867. */
  868. public function flash($message)
  869. {
  870. if ($message !== false) {
  871. $this->Flash->set($message, $this->_config['flash']);
  872. }
  873. }
  874. /**
  875. * If login was called during this request and the user was successfully
  876. * authenticated, this function will return the instance of the authentication
  877. * object that was used for logging the user in.
  878. *
  879. * @return \Cake\Auth\BaseAuthenticate|null
  880. */
  881. public function authenticationProvider()
  882. {
  883. return $this->_authenticationProvider;
  884. }
  885. /**
  886. * If there was any authorization processing for the current request, this function
  887. * will return the instance of the Authorization object that granted access to the
  888. * user to the current address.
  889. *
  890. * @return \Cake\Auth\BaseAuthorize|null
  891. */
  892. public function authorizationProvider()
  893. {
  894. return $this->_authorizationProvider;
  895. }
  896. }