AuthComponent.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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 \Cake\Auth\BaseAuthenticate[]
  170. */
  171. protected $_authenticateObjects = [];
  172. /**
  173. * Objects that will be used for authorization checks.
  174. *
  175. * @var \Cake\Auth\BaseAuthorize[]
  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. $char = strpos($loginAction, '?') === false ? '?' : '&';
  370. $loginAction .= $char . static::QUERY_STRING_REDIRECT . '=' . urlencode($currentUrl);
  371. }
  372. return $loginAction;
  373. }
  374. /**
  375. * Normalizes config `loginAction` and checks if current request URL is same as login action.
  376. *
  377. * @param \Cake\Controller\Controller $controller A reference to the controller object.
  378. * @return bool True if current action is login action else false.
  379. */
  380. protected function _isLoginAction(Controller $controller)
  381. {
  382. $url = '';
  383. if (isset($controller->request->url)) {
  384. $url = $controller->request->url;
  385. }
  386. $url = Router::normalize($url);
  387. $loginAction = Router::normalize($this->_config['loginAction']);
  388. return $loginAction === $url;
  389. }
  390. /**
  391. * Handle unauthorized access attempt
  392. *
  393. * @param \Cake\Controller\Controller $controller A reference to the controller object
  394. * @return \Cake\Network\Response
  395. * @throws \Cake\Network\Exception\ForbiddenException
  396. */
  397. protected function _unauthorized(Controller $controller)
  398. {
  399. if ($this->_config['unauthorizedRedirect'] === false) {
  400. throw new ForbiddenException($this->_config['authError']);
  401. }
  402. $this->flash($this->_config['authError']);
  403. if ($this->_config['unauthorizedRedirect'] === true) {
  404. $default = '/';
  405. if (!empty($this->_config['loginRedirect'])) {
  406. $default = $this->_config['loginRedirect'];
  407. }
  408. if (is_array($default)) {
  409. $default['_base'] = false;
  410. }
  411. $url = $controller->referer($default, true);
  412. } else {
  413. $url = $this->_config['unauthorizedRedirect'];
  414. }
  415. return $controller->redirect($url);
  416. }
  417. /**
  418. * Sets defaults for configs.
  419. *
  420. * @return void
  421. */
  422. protected function _setDefaults()
  423. {
  424. $defaults = [
  425. 'authenticate' => ['Form'],
  426. 'flash' => [
  427. 'element' => 'default',
  428. 'key' => 'auth',
  429. 'params' => ['class' => 'error']
  430. ],
  431. 'loginAction' => [
  432. 'controller' => 'Users',
  433. 'action' => 'login',
  434. 'plugin' => null
  435. ],
  436. 'logoutRedirect' => $this->_config['loginAction'],
  437. 'authError' => __d('cake', 'You are not authorized to access that location.')
  438. ];
  439. $config = $this->config();
  440. foreach ($config as $key => $value) {
  441. if ($value !== null) {
  442. unset($defaults[$key]);
  443. }
  444. }
  445. $this->config($defaults);
  446. }
  447. /**
  448. * Check if the provided user is authorized for the request.
  449. *
  450. * Uses the configured Authorization adapters to check whether or not a user is authorized.
  451. * Each adapter will be checked in sequence, if any of them return true, then the user will
  452. * be authorized for the request.
  453. *
  454. * @param array|\ArrayAccess|null $user The user to check the authorization of.
  455. * If empty the user fetched from storage will be used.
  456. * @param \Cake\Network\Request|null $request The request to authenticate for.
  457. * If empty, the current request will be used.
  458. * @return bool True if $user is authorized, otherwise false
  459. */
  460. public function isAuthorized($user = null, Request $request = null)
  461. {
  462. if (empty($user) && !$this->user()) {
  463. return false;
  464. }
  465. if (empty($user)) {
  466. $user = $this->user();
  467. }
  468. if (empty($request)) {
  469. $request = $this->request;
  470. }
  471. if (empty($this->_authorizeObjects)) {
  472. $this->constructAuthorize();
  473. }
  474. foreach ($this->_authorizeObjects as $authorizer) {
  475. if ($authorizer->authorize($user, $request) === true) {
  476. $this->_authorizationProvider = $authorizer;
  477. return true;
  478. }
  479. }
  480. return false;
  481. }
  482. /**
  483. * Loads the authorization objects configured.
  484. *
  485. * @return array|null The loaded authorization objects, or null when authorize is empty.
  486. * @throws \Cake\Core\Exception\Exception
  487. */
  488. public function constructAuthorize()
  489. {
  490. if (empty($this->_config['authorize'])) {
  491. return null;
  492. }
  493. $this->_authorizeObjects = [];
  494. $authorize = Hash::normalize((array)$this->_config['authorize']);
  495. $global = [];
  496. if (isset($authorize[AuthComponent::ALL])) {
  497. $global = $authorize[AuthComponent::ALL];
  498. unset($authorize[AuthComponent::ALL]);
  499. }
  500. foreach ($authorize as $alias => $config) {
  501. if (!empty($config['className'])) {
  502. $class = $config['className'];
  503. unset($config['className']);
  504. } else {
  505. $class = $alias;
  506. }
  507. $className = App::className($class, 'Auth', 'Authorize');
  508. if (!class_exists($className)) {
  509. throw new Exception(sprintf('Authorization adapter "%s" was not found.', $class));
  510. }
  511. if (!method_exists($className, 'authorize')) {
  512. throw new Exception('Authorization objects must implement an authorize() method.');
  513. }
  514. $config = (array)$config + $global;
  515. $this->_authorizeObjects[$alias] = new $className($this->_registry, $config);
  516. }
  517. return $this->_authorizeObjects;
  518. }
  519. /**
  520. * Getter for authorize objects. Will return a particular authorize object.
  521. *
  522. * @param string $alias Alias for the authorize object
  523. * @return \Cake\Auth\BaseAuthorize|null
  524. */
  525. public function getAuthorize($alias)
  526. {
  527. if (empty($this->_authorizeObjects)) {
  528. $this->constructAuthorize();
  529. }
  530. return isset($this->_authorizeObjects[$alias]) ? $this->_authorizeObjects[$alias] : null;
  531. }
  532. /**
  533. * Takes a list of actions in the current controller for which authentication is not required, or
  534. * no parameters to allow all actions.
  535. *
  536. * You can use allow with either an array or a simple string.
  537. *
  538. * ```
  539. * $this->Auth->allow('view');
  540. * $this->Auth->allow(['edit', 'add']);
  541. * ```
  542. * or to allow all actions
  543. * ```
  544. * $this->Auth->allow();
  545. * ```
  546. *
  547. * @param string|array|null $actions Controller action name or array of actions
  548. * @return void
  549. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#making-actions-public
  550. */
  551. public function allow($actions = null)
  552. {
  553. if ($actions === null) {
  554. $controller = $this->_registry->getController();
  555. $this->allowedActions = get_class_methods($controller);
  556. return;
  557. }
  558. $this->allowedActions = array_merge($this->allowedActions, (array)$actions);
  559. }
  560. /**
  561. * Removes items from the list of allowed/no authentication required actions.
  562. *
  563. * You can use deny with either an array or a simple string.
  564. *
  565. * ```
  566. * $this->Auth->deny('view');
  567. * $this->Auth->deny(['edit', 'add']);
  568. * ```
  569. * or
  570. * ```
  571. * $this->Auth->deny();
  572. * ```
  573. * to remove all items from the allowed list
  574. *
  575. * @param string|array|null $actions Controller action name or array of actions
  576. * @return void
  577. * @see \Cake\Controller\Component\AuthComponent::allow()
  578. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#making-actions-require-authorization
  579. */
  580. public function deny($actions = null)
  581. {
  582. if ($actions === null) {
  583. $this->allowedActions = [];
  584. return;
  585. }
  586. foreach ((array)$actions as $action) {
  587. $i = array_search($action, $this->allowedActions);
  588. if (is_int($i)) {
  589. unset($this->allowedActions[$i]);
  590. }
  591. }
  592. $this->allowedActions = array_values($this->allowedActions);
  593. }
  594. /**
  595. * Set provided user info to storage as logged in user.
  596. *
  597. * The storage class is configured using `storage` config key or passing
  598. * instance to AuthComponent::storage().
  599. *
  600. * @param array|\ArrayAccess $user User data.
  601. * @return void
  602. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#identifying-users-and-logging-them-in
  603. */
  604. public function setUser($user)
  605. {
  606. $this->storage()->write($user);
  607. }
  608. /**
  609. * Log a user out.
  610. *
  611. * Returns the logout action to redirect to. Triggers the `Auth.logout` event
  612. * which the authenticate classes can listen for and perform custom logout logic.
  613. *
  614. * @return string Normalized config `logoutRedirect`
  615. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#logging-users-out
  616. */
  617. public function logout()
  618. {
  619. $this->_setDefaults();
  620. if (empty($this->_authenticateObjects)) {
  621. $this->constructAuthenticate();
  622. }
  623. $user = (array)$this->user();
  624. $this->dispatchEvent('Auth.logout', [$user]);
  625. $this->storage()->delete();
  626. return Router::normalize($this->_config['logoutRedirect']);
  627. }
  628. /**
  629. * Get the current user from storage.
  630. *
  631. * @param string|null $key Field to retrieve. Leave null to get entire User record.
  632. * @return mixed|null Either User record or null if no user is logged in, or retrieved field if key is specified.
  633. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#accessing-the-logged-in-user
  634. */
  635. public function user($key = null)
  636. {
  637. $user = $this->storage()->read();
  638. if (!$user) {
  639. return null;
  640. }
  641. if ($key === null) {
  642. return $user;
  643. }
  644. return Hash::get($user, $key);
  645. }
  646. /**
  647. * Similar to AuthComponent::user() except if user is not found in
  648. * configured storage, connected authentication objects will have their
  649. * getUser() methods called.
  650. *
  651. * This lets stateless authentication methods function correctly.
  652. *
  653. * @return bool true If a user can be found, false if one cannot.
  654. */
  655. protected function _getUser()
  656. {
  657. $user = $this->user();
  658. if ($user) {
  659. return true;
  660. }
  661. if (empty($this->_authenticateObjects)) {
  662. $this->constructAuthenticate();
  663. }
  664. foreach ($this->_authenticateObjects as $auth) {
  665. $result = $auth->getUser($this->request);
  666. if (!empty($result) && is_array($result)) {
  667. $this->_authenticationProvider = $auth;
  668. $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]);
  669. if ($event->result() !== null) {
  670. $result = $event->result();
  671. }
  672. $this->storage()->write($result);
  673. return true;
  674. }
  675. }
  676. return false;
  677. }
  678. /**
  679. * Get the URL a user should be redirected to upon login.
  680. *
  681. * Pass a URL in to set the destination a user should be redirected to upon
  682. * logging in.
  683. *
  684. * If no parameter is passed, gets the authentication redirect URL. The URL
  685. * returned is as per following rules:
  686. *
  687. * - Returns the normalized redirect URL from storage if it is
  688. * present and for the same domain the current app is running on.
  689. * - If there is no URL returned from storage and there is a config
  690. * `loginRedirect`, the `loginRedirect` value is returned.
  691. * - If there is no session and no `loginRedirect`, / is returned.
  692. *
  693. * @param string|array|null $url Optional URL to write as the login redirect URL.
  694. * @return string Redirect URL
  695. */
  696. public function redirectUrl($url = null)
  697. {
  698. $redirectUrl = $this->request->query(static::QUERY_STRING_REDIRECT);
  699. if ($redirectUrl && (substr($redirectUrl, 0, 1) !== '/' || substr($redirectUrl, 0, 2) === '//')) {
  700. $redirectUrl = null;
  701. }
  702. if ($url !== null) {
  703. $redirectUrl = $url;
  704. } elseif ($redirectUrl) {
  705. if (Router::normalize($redirectUrl) === Router::normalize($this->_config['loginAction'])) {
  706. $redirectUrl = $this->_config['loginRedirect'];
  707. }
  708. } elseif ($this->_config['loginRedirect']) {
  709. $redirectUrl = $this->_config['loginRedirect'];
  710. } else {
  711. $redirectUrl = '/';
  712. }
  713. if (is_array($redirectUrl)) {
  714. return Router::url($redirectUrl + ['_base' => false]);
  715. }
  716. return $redirectUrl;
  717. }
  718. /**
  719. * Use the configured authentication adapters, and attempt to identify the user
  720. * by credentials contained in $request.
  721. *
  722. * Triggers `Auth.afterIdentify` event which the authenticate classes can listen
  723. * to.
  724. *
  725. * @return array|bool User record data, or false, if the user could not be identified.
  726. */
  727. public function identify()
  728. {
  729. $this->_setDefaults();
  730. if (empty($this->_authenticateObjects)) {
  731. $this->constructAuthenticate();
  732. }
  733. foreach ($this->_authenticateObjects as $auth) {
  734. $result = $auth->authenticate($this->request, $this->response);
  735. if (!empty($result)) {
  736. $this->_authenticationProvider = $auth;
  737. $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]);
  738. if ($event->result() !== null) {
  739. return $event->result();
  740. }
  741. return $result;
  742. }
  743. }
  744. return false;
  745. }
  746. /**
  747. * Loads the configured authentication objects.
  748. *
  749. * @return array|null The loaded authorization objects, or null on empty authenticate value.
  750. * @throws \Cake\Core\Exception\Exception
  751. */
  752. public function constructAuthenticate()
  753. {
  754. if (empty($this->_config['authenticate'])) {
  755. return null;
  756. }
  757. $this->_authenticateObjects = [];
  758. $authenticate = Hash::normalize((array)$this->_config['authenticate']);
  759. $global = [];
  760. if (isset($authenticate[AuthComponent::ALL])) {
  761. $global = $authenticate[AuthComponent::ALL];
  762. unset($authenticate[AuthComponent::ALL]);
  763. }
  764. foreach ($authenticate as $alias => $config) {
  765. if (!empty($config['className'])) {
  766. $class = $config['className'];
  767. unset($config['className']);
  768. } else {
  769. $class = $alias;
  770. }
  771. $className = App::className($class, 'Auth', 'Authenticate');
  772. if (!class_exists($className)) {
  773. throw new Exception(sprintf('Authentication adapter "%s" was not found.', $class));
  774. }
  775. if (!method_exists($className, 'authenticate')) {
  776. throw new Exception('Authentication objects must implement an authenticate() method.');
  777. }
  778. $config = array_merge($global, (array)$config);
  779. $this->_authenticateObjects[$alias] = new $className($this->_registry, $config);
  780. $this->eventManager()->on($this->_authenticateObjects[$alias]);
  781. }
  782. return $this->_authenticateObjects;
  783. }
  784. /**
  785. * Get/set user record storage object.
  786. *
  787. * @param \Cake\Auth\Storage\StorageInterface|null $storage Sets provided
  788. * object as storage or if null returns configured storage object.
  789. * @return \Cake\Auth\Storage\StorageInterface|null
  790. */
  791. public function storage(StorageInterface $storage = null)
  792. {
  793. if ($storage !== null) {
  794. $this->_storage = $storage;
  795. return null;
  796. }
  797. if ($this->_storage) {
  798. return $this->_storage;
  799. }
  800. $config = $this->_config['storage'];
  801. if (is_string($config)) {
  802. $class = $config;
  803. $config = [];
  804. } else {
  805. $class = $config['className'];
  806. unset($config['className']);
  807. }
  808. $className = App::className($class, 'Auth/Storage', 'Storage');
  809. if (!class_exists($className)) {
  810. throw new Exception(sprintf('Auth storage adapter "%s" was not found.', $class));
  811. }
  812. $this->_storage = new $className($this->request, $this->response, $config);
  813. return $this->_storage;
  814. }
  815. /**
  816. * Magic accessor for backward compatibility for property `$sessionKey`.
  817. *
  818. * @param string $name Property name
  819. * @return mixed
  820. */
  821. public function __get($name)
  822. {
  823. if ($name === 'sessionKey') {
  824. return $this->storage()->config('key');
  825. }
  826. return parent::__get($name);
  827. }
  828. /**
  829. * Magic setter for backward compatibility for property `$sessionKey`.
  830. *
  831. * @param string $name Property name.
  832. * @param mixed $value Value to set.
  833. * @return void
  834. */
  835. public function __set($name, $value)
  836. {
  837. if ($name === 'sessionKey') {
  838. $this->_storage = null;
  839. if ($value === false) {
  840. $this->config('storage', 'Memory');
  841. return;
  842. }
  843. $this->config('storage', 'Session');
  844. $this->storage()->config('key', $value);
  845. return;
  846. }
  847. $this->{$name} = $value;
  848. }
  849. /**
  850. * Getter for authenticate objects. Will return a particular authenticate object.
  851. *
  852. * @param string $alias Alias for the authenticate object
  853. *
  854. * @return \Cake\Auth\BaseAuthenticate|null
  855. */
  856. public function getAuthenticate($alias)
  857. {
  858. if (empty($this->_authenticateObjects)) {
  859. $this->constructAuthenticate();
  860. }
  861. return isset($this->_authenticateObjects[$alias]) ? $this->_authenticateObjects[$alias] : null;
  862. }
  863. /**
  864. * Set a flash message. Uses the Flash component with values from `flash` config.
  865. *
  866. * @param string $message The message to set.
  867. * @return void
  868. */
  869. public function flash($message)
  870. {
  871. if ($message !== false) {
  872. $this->Flash->set($message, $this->_config['flash']);
  873. }
  874. }
  875. /**
  876. * If login was called during this request and the user was successfully
  877. * authenticated, this function will return the instance of the authentication
  878. * object that was used for logging the user in.
  879. *
  880. * @return \Cake\Auth\BaseAuthenticate|null
  881. */
  882. public function authenticationProvider()
  883. {
  884. return $this->_authenticationProvider;
  885. }
  886. /**
  887. * If there was any authorization processing for the current request, this function
  888. * will return the instance of the Authorization object that granted access to the
  889. * user to the current address.
  890. *
  891. * @return \Cake\Auth\BaseAuthorize|null
  892. */
  893. public function authorizationProvider()
  894. {
  895. return $this->_authorizationProvider;
  896. }
  897. }