AuthComponent.php 31 KB

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