1: <?php
2: /**
3: * Authentication component
4: *
5: * Manages user logins and permissions.
6: *
7: * PHP 5
8: *
9: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
10: * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
11: *
12: * Licensed under The MIT License
13: * Redistributions of files must retain the above copyright notice.
14: *
15: * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
16: * @link http://cakephp.org CakePHP(tm) Project
17: * @package Cake.Controller.Component
18: * @since CakePHP(tm) v 0.10.0.1076
19: * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
20: */
21:
22:
23: App::uses('Component', 'Controller');
24: App::uses('Router', 'Routing');
25: App::uses('Security', 'Utility');
26: App::uses('Debugger', 'Utility');
27: App::uses('CakeSession', 'Model/Datasource');
28: App::uses('BaseAuthorize', 'Controller/Component/Auth');
29: App::uses('BaseAuthenticate', 'Controller/Component/Auth');
30:
31: /**
32: * Authentication control component class
33: *
34: * Binds access control with user authentication and session management.
35: *
36: * @package Cake.Controller.Component
37: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
38: */
39: class AuthComponent extends Component {
40:
41: const ALL = 'all';
42:
43: /**
44: * Other components utilized by AuthComponent
45: *
46: * @var array
47: */
48: public $components = array('Session', 'RequestHandler');
49:
50: /**
51: * An array of authentication objects to use for authenticating users. You can configure
52: * multiple adapters and they will be checked sequentially when users are identified.
53: *
54: * {{{
55: * $this->Auth->authenticate = array(
56: * 'Form' => array(
57: * 'userModel' => 'Users.User'
58: * )
59: * );
60: * }}}
61: *
62: * Using the class name without 'Authenticate' as the key, you can pass in an array of settings for each
63: * authentication object. Additionally you can define settings that should be set to all authentications objects
64: * using the 'all' key:
65: *
66: * {{{
67: * $this->Auth->authenticate = array(
68: * 'all' => array(
69: * 'userModel' => 'Users.User',
70: * 'scope' => array('User.active' => 1)
71: * ),
72: * 'Form',
73: * 'Basic'
74: * );
75: * }}}
76: *
77: * You can also use AuthComponent::ALL instead of the string 'all'.
78: *
79: * @var array
80: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
81: */
82: public $authenticate = array('Form');
83:
84: /**
85: * Objects that will be used for authentication checks.
86: *
87: * @var array
88: */
89: protected $_authenticateObjects = array();
90:
91: /**
92: * An array of authorization objects to use for authorizing users. You can configure
93: * multiple adapters and they will be checked sequentially when authorization checks are done.
94: *
95: * {{{
96: * $this->Auth->authorize = array(
97: * 'Crud' => array(
98: * 'actionPath' => 'controllers/'
99: * )
100: * );
101: * }}}
102: *
103: * Using the class name without 'Authorize' as the key, you can pass in an array of settings for each
104: * authorization object. Additionally you can define settings that should be set to all authorization objects
105: * using the 'all' key:
106: *
107: * {{{
108: * $this->Auth->authorize = array(
109: * 'all' => array(
110: * 'actionPath' => 'controllers/'
111: * ),
112: * 'Crud',
113: * 'CustomAuth'
114: * );
115: * }}}
116: *
117: * You can also use AuthComponent::ALL instead of the string 'all'
118: *
119: * @var mixed
120: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authorization
121: */
122: public $authorize = false;
123:
124: /**
125: * Objects that will be used for authorization checks.
126: *
127: * @var array
128: */
129: protected $_authorizeObjects = array();
130:
131: /**
132: * The name of an optional view element to render when an Ajax request is made
133: * with an invalid or expired session
134: *
135: * @var string
136: */
137: public $ajaxLogin = null;
138:
139: /**
140: * Settings to use when Auth needs to do a flash message with SessionComponent::setFlash().
141: * Available keys are:
142: *
143: * - `element` - The element to use, defaults to 'default'.
144: * - `key` - The key to use, defaults to 'auth'
145: * - `params` - The array of additional params to use, defaults to array()
146: *
147: * @var array
148: */
149: public $flash = array(
150: 'element' => 'default',
151: 'key' => 'auth',
152: 'params' => array()
153: );
154:
155: /**
156: * The session key name where the record of the current user is stored. If
157: * unspecified, it will be "Auth.User".
158: *
159: * @var string
160: */
161: public static $sessionKey = 'Auth.User';
162:
163: /**
164: * The current user, used for stateless authentication when
165: * sessions are not available.
166: *
167: * @var array
168: */
169: protected static $_user = array();
170:
171: /**
172: * A URL (defined as a string or array) to the controller action that handles
173: * logins. Defaults to `/users/login`
174: *
175: * @var mixed
176: */
177: public $loginAction = array(
178: 'controller' => 'users',
179: 'action' => 'login',
180: 'plugin' => null
181: );
182:
183: /**
184: * Normally, if a user is redirected to the $loginAction page, the location they
185: * were redirected from will be stored in the session so that they can be
186: * redirected back after a successful login. If this session value is not
187: * set, the user will be redirected to the page specified in $loginRedirect.
188: *
189: * @var mixed
190: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$loginRedirect
191: */
192: public $loginRedirect = null;
193:
194: /**
195: * The default action to redirect to after the user is logged out. While AuthComponent does
196: * not handle post-logout redirection, a redirect URL will be returned from AuthComponent::logout().
197: * Defaults to AuthComponent::$loginAction.
198: *
199: * @var mixed
200: * @see AuthComponent::$loginAction
201: * @see AuthComponent::logout()
202: */
203: public $logoutRedirect = null;
204:
205: /**
206: * Error to display when user attempts to access an object or action to which they do not have
207: * access.
208: *
209: * @var string
210: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$authError
211: */
212: public $authError = null;
213:
214: /**
215: * Controller actions for which user validation is not required.
216: *
217: * @var array
218: * @see AuthComponent::allow()
219: */
220: public $allowedActions = array();
221:
222: /**
223: * Request object
224: *
225: * @var CakeRequest
226: */
227: public $request;
228:
229: /**
230: * Response object
231: *
232: * @var CakeResponse
233: */
234: public $response;
235:
236: /**
237: * Method list for bound controller
238: *
239: * @var array
240: */
241: protected $_methods = array();
242:
243: /**
244: * Initializes AuthComponent for use in the controller
245: *
246: * @param Controller $controller A reference to the instantiating controller object
247: * @return void
248: */
249: public function initialize(Controller $controller) {
250: $this->request = $controller->request;
251: $this->response = $controller->response;
252: $this->_methods = $controller->methods;
253:
254: if (Configure::read('debug') > 0) {
255: Debugger::checkSecurityKeys();
256: }
257: }
258:
259: /**
260: * Main execution method. Handles redirecting of invalid users, and processing
261: * of login form data.
262: *
263: * @param Controller $controller A reference to the instantiating controller object
264: * @return boolean
265: */
266: public function startup(Controller $controller) {
267: $methods = array_flip(array_map('strtolower', $controller->methods));
268: $action = strtolower($controller->request->params['action']);
269:
270: $isMissingAction = (
271: $controller->scaffold === false &&
272: !isset($methods[$action])
273: );
274:
275: if ($isMissingAction) {
276: return true;
277: }
278:
279: if (!$this->_setDefaults()) {
280: return false;
281: }
282: $request = $controller->request;
283:
284: $url = '';
285:
286: if (isset($request->url)) {
287: $url = $request->url;
288: }
289: $url = Router::normalize($url);
290: $loginAction = Router::normalize($this->loginAction);
291:
292: $allowedActions = $this->allowedActions;
293: $isAllowed = (
294: $this->allowedActions == array('*') ||
295: in_array($action, array_map('strtolower', $allowedActions))
296: );
297:
298: if ($loginAction != $url && $isAllowed) {
299: return true;
300: }
301:
302: if ($loginAction == $url) {
303: if (empty($request->data)) {
304: if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
305: $this->Session->write('Auth.redirect', $controller->referer(null, true));
306: }
307: }
308: return true;
309: } else {
310: if (!$this->_getUser()) {
311: if (!$request->is('ajax')) {
312: $this->flash($this->authError);
313: $this->Session->write('Auth.redirect', $request->here());
314: $controller->redirect($loginAction);
315: return false;
316: } elseif (!empty($this->ajaxLogin)) {
317: $controller->viewPath = 'Elements';
318: echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
319: $this->_stop();
320: return false;
321: } else {
322: $controller->redirect(null, 403);
323: }
324: }
325: }
326: if (empty($this->authorize) || $this->isAuthorized($this->user())) {
327: return true;
328: }
329:
330: $this->flash($this->authError);
331: $default = '/';
332: if (!empty($this->loginRedirect)) {
333: $default = $this->loginRedirect;
334: }
335: $controller->redirect($controller->referer($default), null, true);
336: return false;
337: }
338:
339: /**
340: * Attempts to introspect the correct values for object properties.
341: *
342: * @return boolean
343: */
344: protected function _setDefaults() {
345: $defaults = array(
346: 'logoutRedirect' => $this->loginAction,
347: 'authError' => __d('cake', 'You are not authorized to access that location.')
348: );
349: foreach ($defaults as $key => $value) {
350: if (empty($this->{$key})) {
351: $this->{$key} = $value;
352: }
353: }
354: return true;
355: }
356:
357: /**
358: * Uses the configured Authorization adapters to check whether or not a user is authorized.
359: * Each adapter will be checked in sequence, if any of them return true, then the user will
360: * be authorized for the request.
361: *
362: * @param mixed $user The user to check the authorization of. If empty the user in the session will be used.
363: * @param CakeRequest $request The request to authenticate for. If empty, the current request will be used.
364: * @return boolean True if $user is authorized, otherwise false
365: */
366: public function isAuthorized($user = null, $request = null) {
367: if (empty($user) && !$this->user()) {
368: return false;
369: } elseif (empty($user)) {
370: $user = $this->user();
371: }
372: if (empty($request)) {
373: $request = $this->request;
374: }
375: if (empty($this->_authorizeObjects)) {
376: $this->constructAuthorize();
377: }
378: foreach ($this->_authorizeObjects as $authorizer) {
379: if ($authorizer->authorize($user, $request) === true) {
380: return true;
381: }
382: }
383: return false;
384: }
385:
386: /**
387: * Loads the authorization objects configured.
388: *
389: * @return mixed Either null when authorize is empty, or the loaded authorization objects.
390: * @throws CakeException
391: */
392: public function constructAuthorize() {
393: if (empty($this->authorize)) {
394: return;
395: }
396: $this->_authorizeObjects = array();
397: $config = Set::normalize($this->authorize);
398: $global = array();
399: if (isset($config[AuthComponent::ALL])) {
400: $global = $config[AuthComponent::ALL];
401: unset($config[AuthComponent::ALL]);
402: }
403: foreach ($config as $class => $settings) {
404: list($plugin, $class) = pluginSplit($class, true);
405: $className = $class . 'Authorize';
406: App::uses($className, $plugin . 'Controller/Component/Auth');
407: if (!class_exists($className)) {
408: throw new CakeException(__d('cake_dev', 'Authorization adapter "%s" was not found.', $class));
409: }
410: if (!method_exists($className, 'authorize')) {
411: throw new CakeException(__d('cake_dev', 'Authorization objects must implement an authorize method.'));
412: }
413: $settings = array_merge($global, (array)$settings);
414: $this->_authorizeObjects[] = new $className($this->_Collection, $settings);
415: }
416: return $this->_authorizeObjects;
417: }
418:
419: /**
420: * Takes a list of actions in the current controller for which authentication is not required, or
421: * no parameters to allow all actions.
422: *
423: * You can use allow with either an array, or var args.
424: *
425: * `$this->Auth->allow(array('edit', 'add'));` or
426: * `$this->Auth->allow('edit', 'add');` or
427: * `$this->Auth->allow();` to allow all actions
428: *
429: * @param mixed $action,... Controller action name or array of actions
430: * @return void
431: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
432: */
433: public function allow($action = null) {
434: $args = func_get_args();
435: if (empty($args) || $action === null) {
436: $this->allowedActions = $this->_methods;
437: } else {
438: if (isset($args[0]) && is_array($args[0])) {
439: $args = $args[0];
440: }
441: $this->allowedActions = array_merge($this->allowedActions, $args);
442: }
443: }
444:
445: /**
446: * Removes items from the list of allowed/no authentication required actions.
447: *
448: * You can use deny with either an array, or var args.
449: *
450: * `$this->Auth->deny(array('edit', 'add'));` or
451: * `$this->Auth->deny('edit', 'add');` or
452: * `$this->Auth->deny();` to remove all items from the allowed list
453: *
454: * @param mixed $action,... Controller action name or array of actions
455: * @return void
456: * @see AuthComponent::allow()
457: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
458: */
459: public function deny($action = null) {
460: $args = func_get_args();
461: if (empty($args) || $action === null) {
462: $this->allowedActions = array();
463: } else {
464: if (isset($args[0]) && is_array($args[0])) {
465: $args = $args[0];
466: }
467: foreach ($args as $arg) {
468: $i = array_search($arg, $this->allowedActions);
469: if (is_int($i)) {
470: unset($this->allowedActions[$i]);
471: }
472: }
473: $this->allowedActions = array_values($this->allowedActions);
474: }
475: }
476:
477: /**
478: * Maps action names to CRUD operations. Used for controller-based authentication. Make sure
479: * to configure the authorize property before calling this method. As it delegates $map to all the
480: * attached authorize objects.
481: *
482: * @param array $map Actions to map
483: * @return void
484: * @see BaseAuthorize::mapActions()
485: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
486: */
487: public function mapActions($map = array()) {
488: if (empty($this->_authorizeObjects)) {
489: $this->constructAuthorize();
490: }
491: foreach ($this->_authorizeObjects as $auth) {
492: $auth->mapActions($map);
493: }
494: }
495:
496: /**
497: * Log a user in. If a $user is provided that data will be stored as the logged in user. If `$user` is empty or not
498: * specified, the request will be used to identify a user. If the identification was successful,
499: * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
500: * will also change the session id in order to help mitigate session replays.
501: *
502: * @param mixed $user Either an array of user data, or null to identify a user using the current request.
503: * @return boolean True on login success, false on failure
504: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
505: */
506: public function login($user = null) {
507: $this->_setDefaults();
508:
509: if (empty($user)) {
510: $user = $this->identify($this->request, $this->response);
511: }
512: if ($user) {
513: $this->Session->renew();
514: $this->Session->write(self::$sessionKey, $user);
515: }
516: return $this->loggedIn();
517: }
518:
519: /**
520: * Logs a user out, and returns the login action to redirect to.
521: * Triggers the logout() method of all the authenticate objects, so they can perform
522: * custom logout logic. AuthComponent will remove the session data, so
523: * there is no need to do that in an authentication object. Logging out
524: * will also renew the session id. This helps mitigate issues with session replays.
525: *
526: * @return string AuthComponent::$logoutRedirect
527: * @see AuthComponent::$logoutRedirect
528: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
529: */
530: public function logout() {
531: $this->_setDefaults();
532: if (empty($this->_authenticateObjects)) {
533: $this->constructAuthenticate();
534: }
535: $user = $this->user();
536: foreach ($this->_authenticateObjects as $auth) {
537: $auth->logout($user);
538: }
539: $this->Session->delete(self::$sessionKey);
540: $this->Session->delete('Auth.redirect');
541: $this->Session->renew();
542: return Router::normalize($this->logoutRedirect);
543: }
544:
545: /**
546: * Get the current user.
547: *
548: * Will prefer the static user cache over sessions. The static user
549: * cache is primarily used for stateless authentication. For stateful authentication,
550: * cookies + sessions will be used.
551: *
552: * @param string $key field to retrieve. Leave null to get entire User record
553: * @return mixed User record. or null if no user is logged in.
554: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
555: */
556: public static function user($key = null) {
557: if (empty(self::$_user) && !CakeSession::check(self::$sessionKey)) {
558: return null;
559: }
560: if (!empty(self::$_user)) {
561: $user = self::$_user;
562: } else {
563: $user = CakeSession::read(self::$sessionKey);
564: }
565: if ($key === null) {
566: return $user;
567: }
568: if (isset($user[$key])) {
569: return $user[$key];
570: }
571: return null;
572: }
573:
574: /**
575: * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
576: * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
577: *
578: * @return boolean true if a user can be found, false if one cannot.
579: */
580: protected function _getUser() {
581: $user = $this->user();
582: if ($user) {
583: return true;
584: }
585: if (empty($this->_authenticateObjects)) {
586: $this->constructAuthenticate();
587: }
588: foreach ($this->_authenticateObjects as $auth) {
589: $result = $auth->getUser($this->request);
590: if (!empty($result) && is_array($result)) {
591: self::$_user = $result;
592: return true;
593: }
594: }
595: return false;
596: }
597:
598: /**
599: * If no parameter is passed, gets the authentication redirect URL. Pass a url in to
600: * set the destination a user should be redirected to upon logging in. Will fallback to
601: * AuthComponent::$loginRedirect if there is no stored redirect value.
602: *
603: * @param mixed $url Optional URL to write as the login redirect URL.
604: * @return string Redirect URL
605: */
606: public function redirect($url = null) {
607: if (!is_null($url)) {
608: $redir = $url;
609: $this->Session->write('Auth.redirect', $redir);
610: } elseif ($this->Session->check('Auth.redirect')) {
611: $redir = $this->Session->read('Auth.redirect');
612: $this->Session->delete('Auth.redirect');
613:
614: if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
615: $redir = $this->loginRedirect;
616: }
617: } else {
618: $redir = $this->loginRedirect;
619: }
620: return Router::normalize($redir);
621: }
622:
623: /**
624: * Use the configured authentication adapters, and attempt to identify the user
625: * by credentials contained in $request.
626: *
627: * @param CakeRequest $request The request that contains authentication data.
628: * @param CakeResponse $response The response
629: * @return array User record data, or false, if the user could not be identified.
630: */
631: public function identify(CakeRequest $request, CakeResponse $response) {
632: if (empty($this->_authenticateObjects)) {
633: $this->constructAuthenticate();
634: }
635: foreach ($this->_authenticateObjects as $auth) {
636: $result = $auth->authenticate($request, $response);
637: if (!empty($result) && is_array($result)) {
638: return $result;
639: }
640: }
641: return false;
642: }
643:
644: /**
645: * loads the configured authentication objects.
646: *
647: * @return mixed either null on empty authenticate value, or an array of loaded objects.
648: * @throws CakeException
649: */
650: public function constructAuthenticate() {
651: if (empty($this->authenticate)) {
652: return;
653: }
654: $this->_authenticateObjects = array();
655: $config = Set::normalize($this->authenticate);
656: $global = array();
657: if (isset($config[AuthComponent::ALL])) {
658: $global = $config[AuthComponent::ALL];
659: unset($config[AuthComponent::ALL]);
660: }
661: foreach ($config as $class => $settings) {
662: list($plugin, $class) = pluginSplit($class, true);
663: $className = $class . 'Authenticate';
664: App::uses($className, $plugin . 'Controller/Component/Auth');
665: if (!class_exists($className)) {
666: throw new CakeException(__d('cake_dev', 'Authentication adapter "%s" was not found.', $class));
667: }
668: if (!method_exists($className, 'authenticate')) {
669: throw new CakeException(__d('cake_dev', 'Authentication objects must implement an authenticate method.'));
670: }
671: $settings = array_merge($global, (array)$settings);
672: $this->_authenticateObjects[] = new $className($this->_Collection, $settings);
673: }
674: return $this->_authenticateObjects;
675: }
676:
677: /**
678: * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
679: *
680: * This method is intended as a convenience wrapper for Security::hash(). If you want to use
681: * a hashing/encryption system not supported by that method, do not use this method.
682: *
683: * @param string $password Password to hash
684: * @return string Hashed password
685: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#hashing-passwords
686: */
687: public static function password($password) {
688: return Security::hash($password, null, true);
689: }
690:
691: /**
692: * Component shutdown. If user is logged in, wipe out redirect.
693: *
694: * @param Controller $controller Instantiating controller
695: * @return void
696: */
697: public function shutdown(Controller $controller) {
698: if ($this->loggedIn()) {
699: $this->Session->delete('Auth.redirect');
700: }
701: }
702:
703: /**
704: * Check whether or not the current user has data in the session, and is considered logged in.
705: *
706: * @return boolean true if the user is logged in, false otherwise
707: */
708: public function loggedIn() {
709: return $this->user() != array();
710: }
711:
712: /**
713: * Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
714: *
715: * @param string $message The message to set.
716: * @return void
717: */
718: public function flash($message) {
719: $this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']);
720: }
721:
722: }
723: