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-2011, 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-2011, 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/view/1275/authorize
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) {
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) {
267: if ($controller->name == 'CakeError') {
268: return true;
269: }
270:
271: $methods = array_flip(array_map('strtolower', $controller->methods));
272: $action = strtolower($controller->request->params['action']);
273:
274: $isMissingAction = (
275: $controller->scaffold === false &&
276: !isset($methods[$action])
277: );
278:
279: if ($isMissingAction) {
280: return true;
281: }
282:
283: if (!$this->_setDefaults()) {
284: return false;
285: }
286: $request = $controller->request;
287:
288: $url = '';
289:
290: if (isset($request->url)) {
291: $url = $request->url;
292: }
293: $url = Router::normalize($url);
294: $loginAction = Router::normalize($this->loginAction);
295:
296: $allowedActions = $this->allowedActions;
297: $isAllowed = (
298: $this->allowedActions == array('*') ||
299: in_array($action, array_map('strtolower', $allowedActions))
300: );
301:
302: if ($loginAction != $url && $isAllowed) {
303: return true;
304: }
305:
306: if ($loginAction == $url) {
307: if (empty($request->data)) {
308: if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
309: $this->Session->write('Auth.redirect', $controller->referer(null, true));
310: }
311: }
312: return true;
313: } else {
314: if (!$this->_getUser()) {
315: if (!$request->is('ajax')) {
316: $this->flash($this->authError);
317: $this->Session->write('Auth.redirect', $request->here());
318: $controller->redirect($loginAction);
319: return false;
320: } elseif (!empty($this->ajaxLogin)) {
321: $controller->viewPath = 'Elements';
322: echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
323: $this->_stop();
324: return false;
325: } else {
326: $controller->redirect(null, 403);
327: }
328: }
329: }
330: if (empty($this->authorize) || $this->isAuthorized($this->user())) {
331: return true;
332: }
333:
334: $this->flash($this->authError);
335: $controller->redirect($controller->referer('/'), 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');`
427: * `$this->Auth->allow();` to allow all actions.
428: *
429: * allow() also supports '*' as a wildcard to mean all actions.
430: *
431: * `$this->Auth->allow('*');`
432: *
433: * @param mixed $action,... Controller action name or array of actions
434: * @return void
435: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
436: */
437: public function allow($action = null) {
438: $args = func_get_args();
439: if (empty($args) || $args == array('*')) {
440: $this->allowedActions = $this->_methods;
441: } else {
442: if (isset($args[0]) && is_array($args[0])) {
443: $args = $args[0];
444: }
445: $this->allowedActions = array_merge($this->allowedActions, $args);
446: }
447: }
448:
449: /**
450: * Removes items from the list of allowed/no authentication required actions.
451: *
452: * You can use deny with either an array, or var args.
453: *
454: * `$this->Auth->deny(array('edit', 'add'));` or
455: * `$this->Auth->deny('edit', 'add');` or
456: * `$this->Auth->deny();` to remove all items from the allowed list
457: *
458: * @param mixed $action,... Controller action name or array of actions
459: * @return void
460: * @see AuthComponent::allow()
461: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
462: */
463: public function deny($action = null) {
464: $args = func_get_args();
465: if (empty($args)) {
466: $this->allowedActions = array();
467: } else {
468: if (isset($args[0]) && is_array($args[0])) {
469: $args = $args[0];
470: }
471: foreach ($args as $arg) {
472: $i = array_search($arg, $this->allowedActions);
473: if (is_int($i)) {
474: unset($this->allowedActions[$i]);
475: }
476: }
477: $this->allowedActions = array_values($this->allowedActions);
478: }
479: }
480:
481: /**
482: * Maps action names to CRUD operations. Used for controller-based authentication. Make sure
483: * to configure the authorize property before calling this method. As it delegates $map to all the
484: * attached authorize objects.
485: *
486: * @param array $map Actions to map
487: * @return void
488: * @see BaseAuthorize::mapActions()
489: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
490: */
491: public function mapActions($map = array()) {
492: if (empty($this->_authorizeObjects)) {
493: $this->constructAuthorize();
494: }
495: foreach ($this->_authorizeObjects as $auth) {
496: $auth->mapActions($map);
497: }
498: }
499:
500: /**
501: * 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
502: * specified, the request will be used to identify a user. If the identification was successful,
503: * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
504: * will also change the session id in order to help mitigate session replays.
505: *
506: * @param mixed $user Either an array of user data, or null to identify a user using the current request.
507: * @return boolean True on login success, false on failure
508: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
509: */
510: public function login($user = null) {
511: $this->_setDefaults();
512:
513: if (empty($user)) {
514: $user = $this->identify($this->request, $this->response);
515: }
516: if ($user) {
517: $this->Session->renew();
518: $this->Session->write(self::$sessionKey, $user);
519: }
520: return $this->loggedIn();
521: }
522:
523: /**
524: * Logs a user out, and returns the login action to redirect to.
525: * Triggers the logout() method of all the authenticate objects, so they can perform
526: * custom logout logic. AuthComponent will remove the session data, so
527: * there is no need to do that in an authentication object. Logging out
528: * will also renew the session id. This helps mitigate issues with session replays.
529: *
530: * @return string AuthComponent::$logoutRedirect
531: * @see AuthComponent::$logoutRedirect
532: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
533: */
534: public function logout() {
535: $this->_setDefaults();
536: if (empty($this->_authenticateObjects)) {
537: $this->constructAuthenticate();
538: }
539: $user = $this->user();
540: foreach ($this->_authenticateObjects as $auth) {
541: $auth->logout($user);
542: }
543: $this->Session->delete(self::$sessionKey);
544: $this->Session->delete('Auth.redirect');
545: $this->Session->renew();
546: return Router::normalize($this->logoutRedirect);
547: }
548:
549: /**
550: * Get the current user.
551: *
552: * Will prefer the static user cache over sessions. The static user
553: * cache is primarily used for stateless authentication. For stateful authentication,
554: * cookies + sessions will be used.
555: *
556: * @param string $key field to retrieve. Leave null to get entire User record
557: * @return mixed User record. or null if no user is logged in.
558: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
559: */
560: public static function user($key = null) {
561: if (empty(self::$_user) && !CakeSession::check(self::$sessionKey)) {
562: return null;
563: }
564: if (!empty(self::$_user)) {
565: $user = self::$_user;
566: } else {
567: $user = CakeSession::read(self::$sessionKey);
568: }
569: if ($key === null) {
570: return $user;
571: }
572: if (isset($user[$key])) {
573: return $user[$key];
574: }
575: return null;
576: }
577:
578: /**
579: * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
580: * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
581: *
582: * @return boolean true if a user can be found, false if one cannot.
583: */
584: protected function _getUser() {
585: $user = $this->user();
586: if ($user) {
587: return true;
588: }
589: if (empty($this->_authenticateObjects)) {
590: $this->constructAuthenticate();
591: }
592: foreach ($this->_authenticateObjects as $auth) {
593: $result = $auth->getUser($this->request);
594: if (!empty($result) && is_array($result)) {
595: self::$_user = $result;
596: return true;
597: }
598: }
599: return false;
600: }
601:
602: /**
603: * If no parameter is passed, gets the authentication redirect URL. Pass a url in to
604: * set the destination a user should be redirected to upon logging in. Will fallback to
605: * AuthComponent::$loginRedirect if there is no stored redirect value.
606: *
607: * @param mixed $url Optional URL to write as the login redirect URL.
608: * @return string Redirect URL
609: */
610: public function redirect($url = null) {
611: if (!is_null($url)) {
612: $redir = $url;
613: $this->Session->write('Auth.redirect', $redir);
614: } elseif ($this->Session->check('Auth.redirect')) {
615: $redir = $this->Session->read('Auth.redirect');
616: $this->Session->delete('Auth.redirect');
617:
618: if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
619: $redir = $this->loginRedirect;
620: }
621: } else {
622: $redir = $this->loginRedirect;
623: }
624: return Router::normalize($redir);
625: }
626:
627: /**
628: * Use the configured authentication adapters, and attempt to identify the user
629: * by credentials contained in $request.
630: *
631: * @param CakeRequest $request The request that contains authentication data.
632: * @param CakeResponse $response The response
633: * @return array User record data, or false, if the user could not be identified.
634: */
635: public function identify(CakeRequest $request, CakeResponse $response) {
636: if (empty($this->_authenticateObjects)) {
637: $this->constructAuthenticate();
638: }
639: foreach ($this->_authenticateObjects as $auth) {
640: $result = $auth->authenticate($request, $response);
641: if (!empty($result) && is_array($result)) {
642: return $result;
643: }
644: }
645: return false;
646: }
647:
648: /**
649: * loads the configured authentication objects.
650: *
651: * @return mixed either null on empty authenticate value, or an array of loaded objects.
652: * @throws CakeException
653: */
654: public function constructAuthenticate() {
655: if (empty($this->authenticate)) {
656: return;
657: }
658: $this->_authenticateObjects = array();
659: $config = Set::normalize($this->authenticate);
660: $global = array();
661: if (isset($config[AuthComponent::ALL])) {
662: $global = $config[AuthComponent::ALL];
663: unset($config[AuthComponent::ALL]);
664: }
665: foreach ($config as $class => $settings) {
666: list($plugin, $class) = pluginSplit($class, true);
667: $className = $class . 'Authenticate';
668: App::uses($className, $plugin . 'Controller/Component/Auth');
669: if (!class_exists($className)) {
670: throw new CakeException(__d('cake_dev', 'Authentication adapter "%s" was not found.', $class));
671: }
672: if (!method_exists($className, 'authenticate')) {
673: throw new CakeException(__d('cake_dev', 'Authentication objects must implement an authenticate method.'));
674: }
675: $settings = array_merge($global, (array)$settings);
676: $this->_authenticateObjects[] = new $className($this->_Collection, $settings);
677: }
678: return $this->_authenticateObjects;
679: }
680:
681: /**
682: * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
683: *
684: * This method is intended as a convenience wrapper for Security::hash(). If you want to use
685: * a hashing/encryption system not supported by that method, do not use this method.
686: *
687: * @param string $password Password to hash
688: * @return string Hashed password
689: * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#hashing-passwords
690: */
691: public static function password($password) {
692: return Security::hash($password, null, true);
693: }
694:
695: /**
696: * Component shutdown. If user is logged in, wipe out redirect.
697: *
698: * @param Controller $controller Instantiating controller
699: * @return void
700: */
701: public function shutdown($controller) {
702: if ($this->loggedIn()) {
703: $this->Session->delete('Auth.redirect');
704: }
705: }
706:
707: /**
708: * Check whether or not the current user has data in the session, and is considered logged in.
709: *
710: * @return boolean true if the user is logged in, false otherwise
711: */
712: public function loggedIn() {
713: return $this->user() != array();
714: }
715:
716: /**
717: * Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
718: *
719: * @param string $message The message to set.
720: * @return void
721: */
722: public function flash($message) {
723: $this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']);
724: }
725: }
726: