AuthComponent.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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\Controller\Component;
  17. use Cake\Controller\ComponentRegistry;
  18. use Cake\Controller\Controller;
  19. use Cake\Core\App;
  20. use Cake\Core\Configure;
  21. use Cake\Error;
  22. use Cake\Event\Event;
  23. use Cake\Network\Request;
  24. use Cake\Network\Response;
  25. use Cake\Network\Session;
  26. use Cake\Routing\Router;
  27. use Cake\Utility\Debugger;
  28. use Cake\Utility\Hash;
  29. use Cake\Utility\Security;
  30. /**
  31. * Authentication control component class
  32. *
  33. * Binds access control with user authentication and session management.
  34. *
  35. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
  36. */
  37. class AuthComponent extends Component {
  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. * Session::flash(). Available keys are:
  105. *
  106. * - `key` - The message domain to use for flashes generated by this component, defaults to 'auth'.
  107. * - `params` - The array of additional params to use, defaults to []
  108. *
  109. * - `loginAction` - A URL (defined as a string or array) to the controller action
  110. * that handles logins. Defaults to `/users/login`.
  111. *
  112. * - `loginRedirect` - Normally, if a user is redirected to the `loginAction` page,
  113. * the location they were redirected from will be stored in the session so that
  114. * they can be redirected back after a successful login. If this session value
  115. * is not set, redirectUrl() method will return the URL specified in `loginRedirect`.
  116. *
  117. * - `logoutRedirect` - The default action to redirect to after the user is logged out.
  118. * While AuthComponent does not handle post-logout redirection, a redirect URL
  119. * will be returned from `AuthComponent::logout()`. Defaults to `loginAction`.
  120. *
  121. * - `authError` - Error to display when user attempts to access an object or
  122. * action to which they do not have access.
  123. *
  124. * - `unauthorizedRedirect` - Controls handling of unauthorized access.
  125. *
  126. * - For default value `true` unauthorized user is redirected to the referrer URL
  127. * or `$loginRedirect` or '/'.
  128. * - If set to a string or array the value is used as a URL to redirect to.
  129. * - If set to false a `ForbiddenException` exception is thrown instead of redirecting.
  130. *
  131. * @var array
  132. */
  133. protected $_defaultConfig = [
  134. 'authenticate' => null,
  135. 'authorize' => null,
  136. 'ajaxLogin' => null,
  137. 'flash' => null,
  138. 'loginAction' => null,
  139. 'loginRedirect' => null,
  140. 'logoutRedirect' => null,
  141. 'authError' => null,
  142. 'unauthorizedRedirect' => true
  143. ];
  144. /**
  145. * Other components utilized by AuthComponent
  146. *
  147. * @var array
  148. */
  149. public $components = array('RequestHandler');
  150. /**
  151. * Objects that will be used for authentication checks.
  152. *
  153. * @var array
  154. */
  155. protected $_authenticateObjects = array();
  156. /**
  157. * Objects that will be used for authorization checks.
  158. *
  159. * @var array
  160. */
  161. protected $_authorizeObjects = array();
  162. /**
  163. * The session key name where the record of the current user is stored. Default
  164. * key is "Auth.User". If you are using only stateless authenticators set this
  165. * to false to ensure session is not started.
  166. *
  167. * @var string
  168. */
  169. public $sessionKey = 'Auth.User';
  170. /**
  171. * The current user, used for stateless authentication when
  172. * sessions are not available.
  173. *
  174. * @var array
  175. */
  176. protected $_user = array();
  177. /**
  178. * Controller actions for which user validation is not required.
  179. *
  180. * @var array
  181. * @see AuthComponent::allow()
  182. */
  183. public $allowedActions = array();
  184. /**
  185. * Request object
  186. *
  187. * @var \Cake\Network\Request
  188. */
  189. public $request;
  190. /**
  191. * Response object
  192. *
  193. * @var \Cake\Network\Response
  194. */
  195. public $response;
  196. /**
  197. * Instance of the Session object
  198. *
  199. * @return void
  200. */
  201. public $session;
  202. /**
  203. * Method list for bound controller.
  204. *
  205. * @var array
  206. */
  207. protected $_methods = array();
  208. /**
  209. * The instance of the Authenticate provider that was used for
  210. * successfully logging in the current user after calling `login()`
  211. * in the same request
  212. *
  213. * @var Cake\Auth\BaseAuthenticate
  214. */
  215. protected $_authenticationProvider;
  216. /**
  217. * The instance of the Authorize provider that was used to grant
  218. * access to the current user to the url they are requesting.
  219. *
  220. * @var Cake\Auth\BaseAuthorize
  221. */
  222. protected $_authorizationProvider;
  223. /**
  224. * Initializes AuthComponent for use in the controller.
  225. *
  226. * @param Event $event The initialize event.
  227. * @return void
  228. */
  229. public function initialize(Event $event) {
  230. $controller = $event->subject();
  231. $this->request = $controller->request;
  232. $this->response = $controller->response;
  233. $this->_methods = $controller->methods;
  234. $this->session = $controller->request->session();
  235. if (Configure::read('debug')) {
  236. Debugger::checkSecurityKeys();
  237. }
  238. }
  239. /**
  240. * Main execution method. Handles redirecting of invalid users, and processing
  241. * of login form data.
  242. *
  243. * @param Event $event The startup event.
  244. * @return void|\Cake\Network\Response
  245. */
  246. public function startup(Event $event) {
  247. $controller = $event->subject();
  248. $methods = array_flip(array_map('strtolower', $controller->methods));
  249. $action = strtolower($controller->request->params['action']);
  250. if (!isset($methods[$action])) {
  251. return;
  252. }
  253. $this->_setDefaults();
  254. if ($this->_isAllowed($controller)) {
  255. return;
  256. }
  257. if (!$this->_getUser()) {
  258. $result = $this->_unauthenticated($controller);
  259. if ($result instanceof Response) {
  260. $event->stopPropagation();
  261. }
  262. return $result;
  263. }
  264. if ($this->_isLoginAction($controller) ||
  265. empty($this->_config['authorize']) ||
  266. $this->isAuthorized($this->user())
  267. ) {
  268. return;
  269. }
  270. $event->stopPropagation();
  271. return $this->_unauthorized($controller);
  272. }
  273. /**
  274. * Events supported by this component.
  275. *
  276. * @return array
  277. */
  278. public function implementedEvents() {
  279. return [
  280. 'Controller.initialize' => 'initialize',
  281. 'Controller.startup' => 'startup',
  282. ];
  283. }
  284. /**
  285. * Checks whether current action is accessible without authentication.
  286. *
  287. * @param Controller $controller A reference to the instantiating controller object
  288. * @return bool True if action is accessible without authentication else false
  289. */
  290. protected function _isAllowed(Controller $controller) {
  291. $action = strtolower($controller->request->params['action']);
  292. if (in_array($action, array_map('strtolower', $this->allowedActions))) {
  293. return true;
  294. }
  295. return false;
  296. }
  297. /**
  298. * Handles unauthenticated access attempt. First the `unathenticated()` method
  299. * of the last authenticator in the chain will be called. The authenticator can
  300. * handle sending response or redirection as appropriate and return `true` to
  301. * indicate no furthur action is necessary. If authenticator returns null this
  302. * method redirects user to login action. If it's an ajax request and config
  303. * `ajaxLogin` is specified that element is rendered else a 403 http status code
  304. * is returned.
  305. *
  306. * @param Controller $controller A reference to the controller object.
  307. * @return void|\Cake\Network\Response Null if current action is login action
  308. * else response object returned by authenticate object or Controller::redirect().
  309. */
  310. protected function _unauthenticated(Controller $controller) {
  311. if (empty($this->_authenticateObjects)) {
  312. $this->constructAuthenticate();
  313. }
  314. $auth = $this->_authenticateObjects[count($this->_authenticateObjects) - 1];
  315. $result = $auth->unauthenticated($this->request, $this->response);
  316. if ($result !== null) {
  317. return $result;
  318. }
  319. if ($this->_isLoginAction($controller)) {
  320. if (empty($controller->request->data) &&
  321. !$this->session->check('Auth.redirect') &&
  322. $this->request->env('HTTP_REFERER')
  323. ) {
  324. $this->session->write('Auth.redirect', $controller->referer(null, true));
  325. }
  326. return;
  327. }
  328. if (!$controller->request->is('ajax')) {
  329. $this->flash($this->_config['authError']);
  330. $this->session->write('Auth.redirect', $controller->request->here(false));
  331. return $controller->redirect($this->_config['loginAction']);
  332. }
  333. if (!empty($this->_config['ajaxLogin'])) {
  334. $controller->viewPath = 'Element';
  335. $response = $controller->render(
  336. $this->_config['ajaxLogin'],
  337. $this->RequestHandler->ajaxLayout
  338. );
  339. $response->statusCode(403);
  340. return $response;
  341. }
  342. return $controller->redirect(null, 403);
  343. }
  344. /**
  345. * Normalizes config `loginAction` and checks if current request URL is same as login action.
  346. *
  347. * @param Controller $controller A reference to the controller object.
  348. * @return bool True if current action is login action else false.
  349. */
  350. protected function _isLoginAction(Controller $controller) {
  351. $url = '';
  352. if (isset($controller->request->url)) {
  353. $url = $controller->request->url;
  354. }
  355. $url = Router::normalize($url);
  356. $loginAction = Router::normalize($this->_config['loginAction']);
  357. return $loginAction === $url;
  358. }
  359. /**
  360. * Handle unauthorized access attempt
  361. *
  362. * @param Controller $controller A reference to the controller object
  363. * @return \Cake\Network\Response
  364. * @throws \Cake\Error\ForbiddenException
  365. */
  366. protected function _unauthorized(Controller $controller) {
  367. if ($this->_config['unauthorizedRedirect'] === false) {
  368. throw new Error\ForbiddenException($this->_config['authError']);
  369. }
  370. $this->flash($this->_config['authError']);
  371. if ($this->_config['unauthorizedRedirect'] === true) {
  372. $default = '/';
  373. if (!empty($this->_config['loginRedirect'])) {
  374. $default = $this->_config['loginRedirect'];
  375. }
  376. $url = $controller->referer($default, true);
  377. } else {
  378. $url = $this->_config['unauthorizedRedirect'];
  379. }
  380. return $controller->redirect($url);
  381. }
  382. /**
  383. * Sets defaults for configs.
  384. *
  385. * @return void
  386. */
  387. protected function _setDefaults() {
  388. $defaults = [
  389. 'authenticate' => ['Form'],
  390. 'flash' => [
  391. 'element' => 'default',
  392. 'key' => 'auth',
  393. 'params' => []
  394. ],
  395. 'loginAction' => [
  396. 'controller' => 'users',
  397. 'action' => 'login',
  398. 'plugin' => null
  399. ],
  400. 'logoutRedirect' => $this->_config['loginAction'],
  401. 'authError' => __d('cake', 'You are not authorized to access that location.')
  402. ];
  403. $config = $this->config();
  404. foreach ($config as $key => $value) {
  405. if ($value !== null) {
  406. unset($defaults[$key]);
  407. }
  408. }
  409. $this->config($defaults);
  410. }
  411. /**
  412. * Check if the provided user is authorized for the request.
  413. *
  414. * Uses the configured Authorization adapters to check whether or not a user is authorized.
  415. * Each adapter will be checked in sequence, if any of them return true, then the user will
  416. * be authorized for the request.
  417. *
  418. * @param array $user The user to check the authorization of. If empty the user in the session will be used.
  419. * @param \Cake\Network\Request $request The request to authenticate for. If empty, the current request will be used.
  420. * @return bool True if $user is authorized, otherwise false
  421. */
  422. public function isAuthorized($user = null, Request $request = null) {
  423. if (empty($user) && !$this->user()) {
  424. return false;
  425. }
  426. if (empty($user)) {
  427. $user = $this->user();
  428. }
  429. if (empty($request)) {
  430. $request = $this->request;
  431. }
  432. if (empty($this->_authorizeObjects)) {
  433. $this->constructAuthorize();
  434. }
  435. foreach ($this->_authorizeObjects as $authorizer) {
  436. if ($authorizer->authorize($user, $request) === true) {
  437. $this->_authorizationProvider = $authorizer;
  438. return true;
  439. }
  440. }
  441. return false;
  442. }
  443. /**
  444. * Loads the authorization objects configured.
  445. *
  446. * @return mixed Either null when authorize is empty, or the loaded authorization objects.
  447. * @throws \Cake\Error\Exception
  448. */
  449. public function constructAuthorize() {
  450. if (empty($this->_config['authorize'])) {
  451. return;
  452. }
  453. $this->_authorizeObjects = array();
  454. $authorize = Hash::normalize((array)$this->_config['authorize']);
  455. $global = array();
  456. if (isset($authorize[AuthComponent::ALL])) {
  457. $global = $authorize[AuthComponent::ALL];
  458. unset($authorize[AuthComponent::ALL]);
  459. }
  460. foreach ($authorize as $class => $config) {
  461. $className = App::className($class, 'Auth', 'Authorize');
  462. if (!class_exists($className)) {
  463. throw new Error\Exception(sprintf('Authorization adapter "%s" was not found.', $class));
  464. }
  465. if (!method_exists($className, 'authorize')) {
  466. throw new Error\Exception('Authorization objects must implement an authorize() method.');
  467. }
  468. $config = array_merge($global, (array)$config);
  469. $this->_authorizeObjects[] = new $className($this->_registry, $config);
  470. }
  471. return $this->_authorizeObjects;
  472. }
  473. /**
  474. * Takes a list of actions in the current controller for which authentication is not required, or
  475. * no parameters to allow all actions.
  476. *
  477. * You can use allow with either an array or a simple string.
  478. *
  479. * `$this->Auth->allow('view');`
  480. * `$this->Auth->allow(['edit', 'add']);`
  481. * `$this->Auth->allow();` to allow all actions
  482. *
  483. * @param string|array $actions Controller action name or array of actions
  484. * @return void
  485. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
  486. */
  487. public function allow($actions = null) {
  488. if ($actions === null) {
  489. $this->allowedActions = $this->_methods;
  490. return;
  491. }
  492. $this->allowedActions = array_merge($this->allowedActions, (array)$actions);
  493. }
  494. /**
  495. * Removes items from the list of allowed/no authentication required actions.
  496. *
  497. * You can use deny with either an array or a simple string.
  498. *
  499. * `$this->Auth->deny('view');`
  500. * `$this->Auth->deny(['edit', 'add']);`
  501. * `$this->Auth->deny();` to remove all items from the allowed list
  502. *
  503. * @param string|array $actions Controller action name or array of actions
  504. * @return void
  505. * @see AuthComponent::allow()
  506. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
  507. */
  508. public function deny($actions = null) {
  509. if ($actions === null) {
  510. $this->allowedActions = array();
  511. return;
  512. }
  513. foreach ((array)$actions as $action) {
  514. $i = array_search($action, $this->allowedActions);
  515. if (is_int($i)) {
  516. unset($this->allowedActions[$i]);
  517. }
  518. }
  519. $this->allowedActions = array_values($this->allowedActions);
  520. }
  521. /**
  522. * Maps action names to CRUD operations.
  523. *
  524. * Used for controller-based authentication. Make sure
  525. * to configure the authorize property before calling this method. As it delegates $map to all the
  526. * attached authorize objects.
  527. *
  528. * @param array $map Actions to map
  529. * @return void
  530. * @see BaseAuthorize::mapActions()
  531. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
  532. */
  533. public function mapActions(array $map = array()) {
  534. if (empty($this->_authorizeObjects)) {
  535. $this->constructAuthorize();
  536. }
  537. foreach ($this->_authorizeObjects as $auth) {
  538. $auth->mapActions($map);
  539. }
  540. }
  541. /**
  542. * Log a user in.
  543. *
  544. * If a $user is provided that data will be stored as the logged in user. If `$user` is empty or not
  545. * specified, the request will be used to identify a user. If the identification was successful,
  546. * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
  547. * will also change the session id in order to help mitigate session replays.
  548. *
  549. * @param array $user Either an array of user data, or null to identify a user using the current request.
  550. * @return bool True on login success, false on failure
  551. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
  552. */
  553. public function login($user = null) {
  554. $this->_setDefaults();
  555. if (empty($user)) {
  556. $user = $this->identify($this->request, $this->response);
  557. }
  558. if ($user) {
  559. $this->session->renew();
  560. $this->session->write($this->sessionKey, $user);
  561. }
  562. return (bool)$this->user();
  563. }
  564. /**
  565. * Log a user out.
  566. *
  567. * Returns the logout action to redirect to. Triggers the logout() method of
  568. * all the authenticate objects, so they can perform custom logout logic.
  569. * AuthComponent will remove the session data, so there is no need to do that
  570. * in an authentication object. Logging out will also renew the session id.
  571. * This helps mitigate issues with session replays.
  572. *
  573. * @return string Normalized config `logoutRedirect`
  574. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
  575. */
  576. public function logout() {
  577. $this->_setDefaults();
  578. if (empty($this->_authenticateObjects)) {
  579. $this->constructAuthenticate();
  580. }
  581. $user = (array)$this->user();
  582. foreach ($this->_authenticateObjects as $auth) {
  583. $auth->logout($user);
  584. }
  585. $this->session->delete($this->sessionKey);
  586. $this->session->delete('Auth.redirect');
  587. $this->session->renew();
  588. return Router::normalize($this->_config['logoutRedirect']);
  589. }
  590. /**
  591. * Get the current user.
  592. *
  593. * Will prefer the user cache over sessions. The user cache is primarily used for
  594. * stateless authentication. For stateful authentication,
  595. * cookies + sessions will be used.
  596. *
  597. * @param string $key field to retrieve. Leave null to get entire User record
  598. * @return mixed User record. or null if no user is logged in.
  599. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
  600. */
  601. public function user($key = null) {
  602. if (!empty($this->_user)) {
  603. $user = $this->_user;
  604. } elseif ($this->sessionKey && $this->session->check($this->sessionKey)) {
  605. $user = $this->session->read($this->sessionKey);
  606. } else {
  607. return null;
  608. }
  609. if ($key === null) {
  610. return $user;
  611. }
  612. return Hash::get($user, $key);
  613. }
  614. /**
  615. * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
  616. * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
  617. *
  618. * @return bool true if a user can be found, false if one cannot.
  619. */
  620. protected function _getUser() {
  621. $user = $this->user();
  622. if ($user) {
  623. $this->session->delete('Auth.redirect');
  624. return true;
  625. }
  626. if (empty($this->_authenticateObjects)) {
  627. $this->constructAuthenticate();
  628. }
  629. foreach ($this->_authenticateObjects as $auth) {
  630. $result = $auth->getUser($this->request);
  631. if (!empty($result) && is_array($result)) {
  632. $this->_user = $result;
  633. return true;
  634. }
  635. }
  636. return false;
  637. }
  638. /**
  639. * Get the URL a user should be redirected to upon login.
  640. *
  641. * Pass a URL in to set the destination a user should be redirected to upon
  642. * logging in.
  643. *
  644. * If no parameter is passed, gets the authentication redirect URL. The URL
  645. * returned is as per following rules:
  646. *
  647. * - Returns the normalized URL from session Auth.redirect value if it is
  648. * present and for the same domain the current app is running on.
  649. * - If there is no session value and there is a config `loginRedirect`, the
  650. * `loginRedirect` value is returned.
  651. * - If there is no session and no `loginRedirect`, / is returned.
  652. *
  653. * @param string|array $url Optional URL to write as the login redirect URL.
  654. * @return string Redirect URL
  655. */
  656. public function redirectUrl($url = null) {
  657. if ($url !== null) {
  658. $redir = $url;
  659. $this->session->write('Auth.redirect', $redir);
  660. } elseif ($this->session->check('Auth.redirect')) {
  661. $redir = $this->session->read('Auth.redirect');
  662. $this->session->delete('Auth.redirect');
  663. if (Router::normalize($redir) === Router::normalize($this->_config['loginAction'])) {
  664. $redir = $this->_config['loginRedirect'];
  665. }
  666. } elseif ($this->_config['loginRedirect']) {
  667. $redir = $this->_config['loginRedirect'];
  668. } else {
  669. $redir = '/';
  670. }
  671. if (is_array($redir)) {
  672. return Router::url($redir + array('base' => false));
  673. }
  674. return $redir;
  675. }
  676. /**
  677. * Use the configured authentication adapters, and attempt to identify the user
  678. * by credentials contained in $request.
  679. *
  680. * @param \Cake\Network\Request $request The request that contains authentication data.
  681. * @param \Cake\Network\Response $response The response
  682. * @return array User record data, or false, if the user could not be identified.
  683. */
  684. public function identify(Request $request, Response $response) {
  685. if (empty($this->_authenticateObjects)) {
  686. $this->constructAuthenticate();
  687. }
  688. foreach ($this->_authenticateObjects as $auth) {
  689. $result = $auth->authenticate($request, $response);
  690. if (!empty($result) && is_array($result)) {
  691. $this->_authenticationProvider = $auth;
  692. return $result;
  693. }
  694. }
  695. return false;
  696. }
  697. /**
  698. * Loads the configured authentication objects.
  699. *
  700. * @return mixed either null on empty authenticate value, or an array of loaded objects.
  701. * @throws \Cake\Error\Exception
  702. */
  703. public function constructAuthenticate() {
  704. if (empty($this->_config['authenticate'])) {
  705. return;
  706. }
  707. $this->_authenticateObjects = array();
  708. $authenticate = Hash::normalize((array)$this->_config['authenticate']);
  709. $global = array();
  710. if (isset($authenticate[AuthComponent::ALL])) {
  711. $global = $authenticate[AuthComponent::ALL];
  712. unset($authenticate[AuthComponent::ALL]);
  713. }
  714. foreach ($authenticate as $class => $config) {
  715. if (!empty($config['className'])) {
  716. $class = $config['className'];
  717. unset($config['className']);
  718. }
  719. $className = App::className($class, 'Auth', 'Authenticate');
  720. if (!class_exists($className)) {
  721. throw new Error\Exception(sprintf('Authentication adapter "%s" was not found.', $class));
  722. }
  723. if (!method_exists($className, 'authenticate')) {
  724. throw new Error\Exception('Authentication objects must implement an authenticate() method.');
  725. }
  726. $config = array_merge($global, (array)$config);
  727. $this->_authenticateObjects[] = new $className($this->_registry, $config);
  728. }
  729. return $this->_authenticateObjects;
  730. }
  731. /**
  732. * Set a flash message. Uses the Session component, and values from `flash` config.
  733. *
  734. * @param string $message The message to set.
  735. * @param string $type Message type. Defaults to 'error'.
  736. * @return void
  737. */
  738. public function flash($message, $type = 'error') {
  739. if ($message === false) {
  740. return;
  741. }
  742. $flashConfig = $this->_config['flash'];
  743. $key = $flashConfig['key'];
  744. $params = [];
  745. if (isset($flashConfig['params'])) {
  746. $params = $flashConfig['params'];
  747. }
  748. $this->session->flash($message, 'error', $params + compact('key'));
  749. }
  750. /**
  751. * If login was called during this request and the suer was successfully
  752. * authenticated, this function will return the instance of the authentication
  753. * object that was used for logging the user in.
  754. *
  755. * @return \Cake\Auth\BaseAuthenticate|null
  756. */
  757. public function authenticationProvider() {
  758. return $this->_authenticationProvider;
  759. }
  760. /**
  761. * If there was any authorization processing for the current request, this function
  762. * will return the instance of the Authorization object that granted access to the
  763. * user to the current address.
  764. *
  765. * @return \Cake\Auth\BaseAuthorize|null
  766. */
  767. public function authorizationProvider() {
  768. return $this->_authorizationProvider;
  769. }
  770. }