AuthComponent.php 24 KB

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