Form.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\security\auth\adapter;
  9. use lithium\core\Libraries;
  10. use UnexpectedValueException;
  11. use lithium\security\Password;
  12. /**
  13. * The `Form` adapter provides basic authentication facilities for checking credentials submitted
  14. * via a web form against a database. To perform an authentication check, the adapter accepts
  15. * an instance of a `Request` object which contains the submitted form data in its `$data` property.
  16. *
  17. * When a request is submitted, the adapter will take the form data from the `Request` object,
  18. * apply any filters as appropriate (see the `'filters'` configuration setting below), and
  19. * query a model class using using the filtered data. The data is then checked against any
  20. * validators configured, which can programmatically check submitted values against database values.
  21. *
  22. * By default, the adapter uses a model called `Users`, and lookup fields called `'username'` and
  23. * `'password'`. These can be customized by setting the `'model'` and `'fields'` configuration keys,
  24. * respectively. The `'model'` key accepts either a model name (i.e. `Customers`), or a
  25. * fully-namespaced model class name (i.e. `my_app\models\Customers`). The `'fields'` setting
  26. * accepts an array of field names to use when looking up a user. An example configuration,
  27. * including a custom model class and lookup fields might look like the following:
  28. *
  29. * {{{
  30. * Auth::config(array(
  31. * 'customer' => array(
  32. * 'adapter' => 'Form',
  33. * 'model' => 'Customers',
  34. * 'fields' => array('email', 'password')
  35. * )
  36. * ));
  37. * }}}
  38. *
  39. * If the field names present in the form match the fields used in the database lookup, the above
  40. * will suffice. If, however, the form fields must be matched to different database field names,
  41. * you can specify an array which matches up the form field names to their corresponding database
  42. * field names. Suppose, for example, user authentication information in a MongoDB database is
  43. * nested within a sub-object called `login`. The adapter could be configured as follows:
  44. *
  45. * {{{
  46. * Auth::config(array(
  47. * 'customer' => array(
  48. * 'adapter' => 'Form',
  49. * 'model' => 'Customers',
  50. * 'fields' => array('username' => 'login.username', 'password' => 'login.password'),
  51. * 'scope' => array('active' => true)
  52. * )
  53. * ));
  54. * }}}
  55. *
  56. * Note that any additional fields may be specified which should be included in the query. For
  57. * example, if a user must select a group when logging in, you may override the `'fields'` key with
  58. * that value as well (i.e. `'fields' => array('username', 'password', 'group')`). If a field is
  59. * specified which is not present in the request data, the value in the authentication query will be
  60. * `null`). Note that this will only submit data that is specified in the incoming request. If you
  61. * would like to further limit the query using fixed conditions, use the `'scope'` key, as shown in
  62. * the example above.
  63. *
  64. * ## Pre-Query Filtering
  65. *
  66. * As mentioned, prior to any queries being executed, the request data is modified by any filters
  67. * configured. Filters are callbacks which accept the value of a submitted form field as input, and
  68. * return a modified version of the value as output. Filters can be any PHP callable, i.e. a closure
  69. * or `array('ClassName', 'method')`.
  70. *
  71. * For example, if you're doing simple password hashing against a legacy application, you can
  72. * configure the adapter as follows:
  73. *
  74. * {{{
  75. * Auth::config(array(
  76. * 'default' => array(
  77. * 'adapter' => 'Form',
  78. * 'filters' => array('password' => array('lithium\util\String', 'hash')),
  79. * 'validators' => array('password' => false)
  80. * )
  81. * ));
  82. * }}}
  83. *
  84. * This applies the default system hash (SHA 512) against the password prior to using it in the
  85. * query, and overrides `'validators'` to disable the default crypto-based query validation that
  86. * would occur after the query.
  87. *
  88. * Note that if you are specifying the `'fields'` configuration using key / value pairs, the key
  89. * used to specify the filter must match the key side of the `'fields'` assignment. Additionally,
  90. * specifying a filter with no key allows the entire data array to be filtered, as in the following:
  91. *
  92. * {{{
  93. * Auth::config(array(
  94. * 'default' => array(
  95. * 'adapter' => 'Form',
  96. * 'filters' => array(function ($data) {
  97. * // Make any modifications to $data, including adding/removing keys
  98. * return $data;
  99. * })
  100. * )
  101. * ));
  102. * }}}
  103. *
  104. * For more information, see the `_filters()` method or the `$_filters` property.
  105. *
  106. * ## Post-Query Validation
  107. *
  108. * In addition to filtering data, you can also apply validators to do check submitted form data
  109. * against database values programmatically. For example, the default adapter uses a cryptographic
  110. * hash function which operates in constant time to validate passwords. Configuring this validator
  111. * manually would work as follows:
  112. *
  113. * {{{
  114. * use lithium\security\Password;
  115. *
  116. * Auth::config(array(
  117. * 'default' => array(
  118. * 'adapter' => 'Form',
  119. * 'validators' => array(
  120. * 'password' => function($form, $data) {
  121. * return Password::check($form, $data);
  122. * }
  123. * )
  124. * )
  125. * ));
  126. * }}}
  127. *
  128. * As with filters, each validator can be defined as any PHP callable, and must be keyed using the
  129. * name of the form field submitted (if form and database field names do not match). If a validator
  130. * is specified with no key, it will apply to all data submitted. See the `$_validators` property
  131. * and the `_validate()` method for more information.
  132. *
  133. * @see lithium\net\http\Request::$data
  134. * @see lithium\data\Model::find()
  135. * @see lithium\util\String::hash()
  136. */
  137. class Form extends \lithium\core\Object {
  138. /**
  139. * The name of the model class to query against. This can either be a model name (i.e.
  140. * `'Users'`), or a fully-namespaced class reference (i.e. `'app\models\Users'`). When
  141. * authenticating users, the magic `first()` method is invoked against the model to return the
  142. * first record found when combining the conditions in the `$_scope` property with the
  143. * authentication data yielded from the `Request` object in `Form::check()`. (Note that the
  144. * model method called is configurable using the `$_query` property).
  145. *
  146. * @see lithium\security\auth\adapter\Form::$_query
  147. * @var string
  148. */
  149. protected $_model = '';
  150. /**
  151. * The list of fields to extract from the `Request` object and use when querying the database.
  152. * This can either be a simple array of field names, or a set of key/value pairs, which map
  153. * the field names in the request to database field names.
  154. *
  155. * For example, if you had a form field name `username`, which mapped to a database field named
  156. * username, you could use the following in the `'fields'` configuration:
  157. *
  158. * {{{ embed:lithium\tests\cases\security\auth\adapter\FormTest::testMixedFieldMapping(3-3) }}}
  159. *
  160. * This is especially relevant for document databases, where you may want to map a form field to
  161. * a nested document field:
  162. *
  163. * {{{
  164. * 'fields' => array('username' => 'login.username', 'password'),
  165. * }}}
  166. *
  167. * @var array
  168. */
  169. protected $_fields = array();
  170. /**
  171. * Additional data to apply to the model query conditions when looking up users, i.e.
  172. * `array('active' => true)` to disallow authenticating against inactive user accounts.
  173. *
  174. * @var array
  175. */
  176. protected $_scope = array();
  177. /**
  178. * Callback filters to apply to request data before using it in the authentication query. Each
  179. * key in the array must match a request field specified in the `$_fields` property, and each
  180. * value must either be a reference to a function or method name, or a closure. For example, to
  181. * automatically hash passwords using simple SHA 512 hashing, the `Form` adapter could be
  182. * configured with the following: `array('password' => array('lithium\util\String', 'hash'))`.
  183. *
  184. * Optionally, you can specify a callback with no key, which will receive (and can modify) the
  185. * entire credentials array before the query is executed, as in the following example:
  186. *
  187. * {{{
  188. * Auth::config(array(
  189. * 'members' => array(
  190. * 'adapter' => 'Form',
  191. * 'model' => 'Member',
  192. * 'fields' => array('email', 'password'),
  193. * 'filters' => array(function($data) {
  194. * // If the user is outside the company, then their account must have the
  195. * // 'private' field set to true in order to log in:
  196. * if (!preg_match('/@mycompany\.com$/', $data['email'])) {
  197. * $data['private'] = true;
  198. * }
  199. * return $data;
  200. * })
  201. * )
  202. * ));
  203. * }}}
  204. *
  205. * @see lithium\security\auth\adapter\Form::$_fields
  206. * @var array
  207. */
  208. protected $_filters = array();
  209. /**
  210. * An array of callbacks, keyed by form field name, which make an assertion about a piece of
  211. * submitted form data. Each validator should accept the value of the form field submitted
  212. * (which will be modified by any applied filters), and return a boolean value indicating the
  213. * success of the validation. If a validator is specified with no key, it will receive all form
  214. * data and all database data. See the `_validate()` method for more information.
  215. *
  216. * @see lithium\security\auth\adapter\Form::_validate()
  217. * @var array
  218. */
  219. protected $_validators = array();
  220. /**
  221. * If you require custom model logic in your authentication query, use this setting to specify
  222. * which model method to call, and this method will receive the authentication query. In return,
  223. * the `Form` adapter expects a `Record` object which implements the `data()` method. See the
  224. * constructor for more information on setting this property. Defaults to `'first'`, which
  225. * calls, for example, `Users::first()`.
  226. *
  227. * @see lithium\security\auth\adapter\Form::__construct()
  228. * @see lithium\data\entity\Record::data()
  229. * @var string
  230. */
  231. protected $_query = 'first';
  232. /**
  233. * List of configuration properties to automatically assign to the properties of the adapter
  234. * when the class is constructed.
  235. *
  236. * @var array
  237. */
  238. protected $_autoConfig = array('model', 'fields', 'scope', 'filters', 'validators', 'query');
  239. /**
  240. * Sets the initial configuration for the `Form` adapter, as detailed below.
  241. *
  242. * @see lithium\security\auth\adapter\Form::$_model
  243. * @see lithium\security\auth\adapter\Form::$_fields
  244. * @see lithium\security\auth\adapter\Form::$_filters
  245. * @see lithium\security\auth\adapter\Form::$_validators
  246. * @see lithium\security\auth\adapter\Form::$_query
  247. * @param array $config Sets the configuration for the adapter, which has the following options:
  248. * - `'model'` _string_: The name of the model class to use. See the `$_model`
  249. * property for details.
  250. * - `'fields'` _array_: The model fields to query against when taking input from
  251. * the request data. See the `$_fields` property for details.
  252. * - `'scope'` _array_: Any additional conditions used to constrain the
  253. * authentication query. For example, if active accounts in an application have
  254. * an `active` field which must be set to `true`, you can specify
  255. * `'scope' => array('active' => true)`. See the `$_scope` property for more
  256. * details.
  257. * - `'filters'` _array_: Named callbacks to apply to request data before the user
  258. * lookup query is generated. See the `$_filters` property for more details.
  259. * - `'validators'` _array_: Named callbacks to apply to fields in request data and
  260. * corresponding fields in database data in order to do programmatic
  261. * authentication checks after the query has occurred. See the `$_validators`
  262. * property for more details.
  263. * - `'query'` _string_: Determines the model method to invoke for authentication
  264. * checks. See the `$_query` property for more details.
  265. */
  266. public function __construct(array $config = array()) {
  267. $defaults = array(
  268. 'model' => 'Users',
  269. 'query' => 'first',
  270. 'filters' => array(),
  271. 'validators' => array(),
  272. 'fields' => array('username', 'password')
  273. );
  274. $config += $defaults;
  275. $password = function($form, $data) {
  276. return Password::check($form, $data);
  277. };
  278. $config['validators'] = array_filter($config['validators'] + compact('password'));
  279. parent::__construct($config + $defaults);
  280. }
  281. /**
  282. * Initializes values configured in the constructor.
  283. *
  284. * @return void
  285. */
  286. protected function _init() {
  287. parent::_init();
  288. foreach ($this->_fields as $key => $val) {
  289. if (is_int($key)) {
  290. unset($this->_fields[$key]);
  291. $this->_fields[$val] = $val;
  292. }
  293. }
  294. $this->_model = Libraries::locate('models', $this->_model);
  295. }
  296. /**
  297. * Called by the `Auth` class to run an authentication check against a model class using the
  298. * credentials in a data container (a `Request` object), and returns an array of user
  299. * information on success, or `false` on failure.
  300. *
  301. * @param object $credentials A data container which wraps the authentication credentials used
  302. * to query the model (usually a `Request` object). See the documentation for this
  303. * class for further details.
  304. * @param array $options Additional configuration options. Not currently implemented in this
  305. * adapter.
  306. * @return array Returns an array containing user information on success, or `false` on failure.
  307. */
  308. public function check($credentials, array $options = array()) {
  309. $model = $this->_model;
  310. $query = $this->_query;
  311. $data = $this->_filters($credentials->data);
  312. $validate = array_flip(array_intersect_key($this->_fields, $this->_validators));
  313. $conditions = $this->_scope + array_diff_key($data, $validate);
  314. $user = $model::$query(compact('conditions') + $options);
  315. if (!$user) {
  316. return false;
  317. }
  318. return $this->_validate($user, $data);
  319. }
  320. /**
  321. * A pass-through method called by `Auth`. Returns the value of `$data`, which is written to
  322. * a user's session. When implementing a custom adapter, this method may be used to modify or
  323. * reject data before it is written to the session.
  324. *
  325. * @param array $data User data to be written to the session.
  326. * @param array $options Adapter-specific options. Not implemented in the `Form` adapter.
  327. * @return array Returns the value of `$data`.
  328. */
  329. public function set($data, array $options = array()) {
  330. return $data;
  331. }
  332. /**
  333. * Called by `Auth` when a user session is terminated. Not implemented in the `Form` adapter.
  334. *
  335. * @param array $options Adapter-specific options. Not implemented in the `Form` adapter.
  336. * @return void
  337. */
  338. public function clear(array $options = array()) {
  339. }
  340. /**
  341. * Iterates over the filters configured in `$_filters` which are applied to submitted form data
  342. * _before_ it is used in the query.
  343. *
  344. * @see lithium\security\auth\adapter\Form::$_filters
  345. * @param array $data The array of raw form data to be filtered.
  346. * @return array Callback result.
  347. */
  348. protected function _filters($data) {
  349. $result = array();
  350. foreach ($this->_fields as $from => $to) {
  351. $result[$to] = isset($data[$from]) ? $data[$from] : null;
  352. if (!isset($this->_filters[$from])) {
  353. $result[$to] = is_scalar($result[$to]) ? $result[$to] : null;
  354. continue;
  355. }
  356. if ($this->_filters[$from] === false) {
  357. continue;
  358. }
  359. if (!is_callable($this->_filters[$from])) {
  360. $message = "Authentication filter for `{$from}` is not callable.";
  361. throw new UnexpectedValueException($message);
  362. }
  363. $result[$to] = call_user_func($this->_filters[$from], $result[$to]);
  364. }
  365. if (!isset($this->_filters[0])) {
  366. return $result;
  367. }
  368. if (!is_callable($this->_filters[0])) {
  369. throw new UnexpectedValueException("Authentication filter is not callable.");
  370. }
  371. return call_user_func($this->_filters[0], $result);
  372. }
  373. /**
  374. * After an authentication query against the configured model class has occurred, this method
  375. * iterates over the configured validators and checks each one by passing the submitted form
  376. * value as the first parameter, and the corresponding database value as the second. The
  377. * validator then returns a boolean to indicate success. If the validator fails, it will cause
  378. * the entire authentication operation to fail. Note that any filters applied to a form field
  379. * will affect the data passed to the validator.
  380. *
  381. * @see lithium\security\auth\adapter\Form::__construct()
  382. * @see lithium\security\auth\adapter\Form::$_validators
  383. * @param object $user The user object returned from the database. This object must support a
  384. * `data()` method, which returns the object's array representation, and
  385. * also returns individual field values by name.
  386. * @param array $data The form data submitted in the request and passed to `Form::check()`.
  387. * @return array Returns an array of authenticated user data on success, otherwise `false` if
  388. * any of the configured validators fails. See `'validators'` in the `$config`
  389. * parameter of `__construct()`.
  390. */
  391. protected function _validate($user, array $data) {
  392. foreach ($this->_validators as $field => $validator) {
  393. if (!isset($this->_fields[$field]) || $field === 0) {
  394. continue;
  395. }
  396. if (!is_callable($validator)) {
  397. $message = "Authentication validator for `{$field}` is not callable.";
  398. throw new UnexpectedValueException($message);
  399. }
  400. $field = $this->_fields[$field];
  401. $value = isset($data[$field]) ? $data[$field] : null;
  402. if (!call_user_func($validator, $value, $user->data($field))) {
  403. return false;
  404. }
  405. }
  406. $user = $user->data();
  407. if (!isset($this->_validators[0])) {
  408. return $user;
  409. }
  410. if (!is_callable($this->_validators[0])) {
  411. throw new UnexpectedValueException("Authentication validator is not callable.");
  412. }
  413. return call_user_func($this->_validators[0], $data, $user) ? $user : false;
  414. }
  415. }
  416. ?>