DbTable.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Auth
  17. * @subpackage Adapter
  18. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Auth_Adapter_Interface
  24. */
  25. require_once 'Zend/Auth/Adapter/Interface.php';
  26. /**
  27. * @see Zend_Db_Adapter_Abstract
  28. */
  29. require_once 'Zend/Db/Adapter/Abstract.php';
  30. /**
  31. * @see Zend_Auth_Result
  32. */
  33. require_once 'Zend/Auth/Result.php';
  34. /**
  35. * @category Zend
  36. * @package Zend_Auth
  37. * @subpackage Adapter
  38. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  39. * @license http://framework.zend.com/license/new-bsd New BSD License
  40. */
  41. class Zend_Auth_Adapter_DbTable implements Zend_Auth_Adapter_Interface
  42. {
  43. /**
  44. * Database Connection
  45. *
  46. * @var Zend_Db_Adapter_Abstract
  47. */
  48. protected $_zendDb = null;
  49. /**
  50. * @var Zend_Db_Select
  51. */
  52. protected $_dbSelect = null;
  53. /**
  54. * $_tableName - the table name to check
  55. *
  56. * @var string
  57. */
  58. protected $_tableName = null;
  59. /**
  60. * $_identityColumn - the column to use as the identity
  61. *
  62. * @var string
  63. */
  64. protected $_identityColumn = null;
  65. /**
  66. * $_credentialColumns - columns to be used as the credentials
  67. *
  68. * @var string
  69. */
  70. protected $_credentialColumn = null;
  71. /**
  72. * $_identity - Identity value
  73. *
  74. * @var string
  75. */
  76. protected $_identity = null;
  77. /**
  78. * $_credential - Credential values
  79. *
  80. * @var string
  81. */
  82. protected $_credential = null;
  83. /**
  84. * $_credentialTreatment - Treatment applied to the credential, such as MD5() or PASSWORD()
  85. *
  86. * @var string
  87. */
  88. protected $_credentialTreatment = null;
  89. /**
  90. * $_authenticateResultInfo
  91. *
  92. * @var array
  93. */
  94. protected $_authenticateResultInfo = null;
  95. /**
  96. * $_resultRow - Results of database authentication query
  97. *
  98. * @var array
  99. */
  100. protected $_resultRow = null;
  101. /**
  102. * $_ambiguityIdentity - Flag to indicate same Identity can be used with
  103. * different credentials. Default is FALSE and need to be set to true to
  104. * allow ambiguity usage.
  105. *
  106. * @var boolean
  107. */
  108. protected $_ambiguityIdentity = false;
  109. /**
  110. * __construct() - Sets configuration options
  111. *
  112. * @param Zend_Db_Adapter_Abstract $zendDb If null, default database adapter assumed
  113. * @param string $tableName
  114. * @param string $identityColumn
  115. * @param string $credentialColumn
  116. * @param string $credentialTreatment
  117. */
  118. public function __construct(Zend_Db_Adapter_Abstract $zendDb = null, $tableName = null, $identityColumn = null,
  119. $credentialColumn = null, $credentialTreatment = null)
  120. {
  121. $this->_setDbAdapter($zendDb);
  122. if (null !== $tableName) {
  123. $this->setTableName($tableName);
  124. }
  125. if (null !== $identityColumn) {
  126. $this->setIdentityColumn($identityColumn);
  127. }
  128. if (null !== $credentialColumn) {
  129. $this->setCredentialColumn($credentialColumn);
  130. }
  131. if (null !== $credentialTreatment) {
  132. $this->setCredentialTreatment($credentialTreatment);
  133. }
  134. }
  135. /**
  136. * _setDbAdapter() - set the database adapter to be used for quering
  137. *
  138. * @param Zend_Db_Adapter_Abstract
  139. * @throws Zend_Auth_Adapter_Exception
  140. * @return Zend_Auth_Adapter_DbTable
  141. */
  142. protected function _setDbAdapter(Zend_Db_Adapter_Abstract $zendDb = null)
  143. {
  144. $this->_zendDb = $zendDb;
  145. /**
  146. * If no adapter is specified, fetch default database adapter.
  147. */
  148. if(null === $this->_zendDb) {
  149. require_once 'Zend/Db/Table/Abstract.php';
  150. $this->_zendDb = Zend_Db_Table_Abstract::getDefaultAdapter();
  151. if (null === $this->_zendDb) {
  152. require_once 'Zend/Auth/Adapter/Exception.php';
  153. throw new Zend_Auth_Adapter_Exception('No database adapter present');
  154. }
  155. }
  156. return $this;
  157. }
  158. /**
  159. * setTableName() - set the table name to be used in the select query
  160. *
  161. * @param string $tableName
  162. * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
  163. */
  164. public function setTableName($tableName)
  165. {
  166. $this->_tableName = $tableName;
  167. return $this;
  168. }
  169. /**
  170. * setIdentityColumn() - set the column name to be used as the identity column
  171. *
  172. * @param string $identityColumn
  173. * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
  174. */
  175. public function setIdentityColumn($identityColumn)
  176. {
  177. $this->_identityColumn = $identityColumn;
  178. return $this;
  179. }
  180. /**
  181. * setCredentialColumn() - set the column name to be used as the credential column
  182. *
  183. * @param string $credentialColumn
  184. * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
  185. */
  186. public function setCredentialColumn($credentialColumn)
  187. {
  188. $this->_credentialColumn = $credentialColumn;
  189. return $this;
  190. }
  191. /**
  192. * setCredentialTreatment() - allows the developer to pass a parameterized string that is
  193. * used to transform or treat the input credential data.
  194. *
  195. * In many cases, passwords and other sensitive data are encrypted, hashed, encoded,
  196. * obscured, or otherwise treated through some function or algorithm. By specifying a
  197. * parameterized treatment string with this method, a developer may apply arbitrary SQL
  198. * upon input credential data.
  199. *
  200. * Examples:
  201. *
  202. * 'PASSWORD(?)'
  203. * 'MD5(?)'
  204. *
  205. * @param string $treatment
  206. * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
  207. */
  208. public function setCredentialTreatment($treatment)
  209. {
  210. $this->_credentialTreatment = $treatment;
  211. return $this;
  212. }
  213. /**
  214. * setIdentity() - set the value to be used as the identity
  215. *
  216. * @param string $value
  217. * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
  218. */
  219. public function setIdentity($value)
  220. {
  221. $this->_identity = $value;
  222. return $this;
  223. }
  224. /**
  225. * setCredential() - set the credential value to be used, optionally can specify a treatment
  226. * to be used, should be supplied in parameterized form, such as 'MD5(?)' or 'PASSWORD(?)'
  227. *
  228. * @param string $credential
  229. * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
  230. */
  231. public function setCredential($credential)
  232. {
  233. $this->_credential = $credential;
  234. return $this;
  235. }
  236. /**
  237. * setAmbiguityIdentity() - sets a flag for usage of identical identities
  238. * with unique credentials. It accepts integers (0, 1) or boolean (true,
  239. * false) parameters. Default is false.
  240. *
  241. * @param int|bool $flag
  242. * @return Zend_Auth_Adapter_DbTable
  243. */
  244. public function setAmbiguityIdentity($flag)
  245. {
  246. if (is_integer($flag)) {
  247. $this->_ambiguityIdentity = (1 === $flag ? true : false);
  248. } elseif (is_bool($flag)) {
  249. $this->_ambiguityIdentity = $flag;
  250. }
  251. return $this;
  252. }
  253. /**
  254. * getAmbiguityIdentity() - returns TRUE for usage of multiple identical
  255. * identies with different credentials, FALSE if not used.
  256. *
  257. * @return bool
  258. */
  259. public function getAmbiguityIdentity()
  260. {
  261. return $this->_ambiguityIdentity;
  262. }
  263. /**
  264. * getDbSelect() - Return the preauthentication Db Select object for userland select query modification
  265. *
  266. * @return Zend_Db_Select
  267. */
  268. public function getDbSelect()
  269. {
  270. if ($this->_dbSelect == null) {
  271. $this->_dbSelect = $this->_zendDb->select();
  272. }
  273. return $this->_dbSelect;
  274. }
  275. /**
  276. * getResultRowObject() - Returns the result row as a stdClass object
  277. *
  278. * @param string|array $returnColumns
  279. * @param string|array $omitColumns
  280. * @return stdClass|boolean
  281. */
  282. public function getResultRowObject($returnColumns = null, $omitColumns = null)
  283. {
  284. if (!$this->_resultRow) {
  285. return false;
  286. }
  287. $returnObject = new stdClass();
  288. if (null !== $returnColumns) {
  289. $availableColumns = array_keys($this->_resultRow);
  290. foreach ( (array) $returnColumns as $returnColumn) {
  291. if (in_array($returnColumn, $availableColumns)) {
  292. $returnObject->{$returnColumn} = $this->_resultRow[$returnColumn];
  293. }
  294. }
  295. return $returnObject;
  296. } elseif (null !== $omitColumns) {
  297. $omitColumns = (array) $omitColumns;
  298. foreach ($this->_resultRow as $resultColumn => $resultValue) {
  299. if (!in_array($resultColumn, $omitColumns)) {
  300. $returnObject->{$resultColumn} = $resultValue;
  301. }
  302. }
  303. return $returnObject;
  304. } else {
  305. foreach ($this->_resultRow as $resultColumn => $resultValue) {
  306. $returnObject->{$resultColumn} = $resultValue;
  307. }
  308. return $returnObject;
  309. }
  310. }
  311. /**
  312. * authenticate() - defined by Zend_Auth_Adapter_Interface. This method is called to
  313. * attempt an authentication. Previous to this call, this adapter would have already
  314. * been configured with all necessary information to successfully connect to a database
  315. * table and attempt to find a record matching the provided identity.
  316. *
  317. * @throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible
  318. * @return Zend_Auth_Result
  319. */
  320. public function authenticate()
  321. {
  322. $this->_authenticateSetup();
  323. $dbSelect = $this->_authenticateCreateSelect();
  324. $resultIdentities = $this->_authenticateQuerySelect($dbSelect);
  325. if ( ($authResult = $this->_authenticateValidateResultSet($resultIdentities)) instanceof Zend_Auth_Result) {
  326. return $authResult;
  327. }
  328. if (true === $this->getAmbiguityIdentity()) {
  329. $validIdentities = array ();
  330. $zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match');
  331. foreach ($resultIdentities as $identity) {
  332. if (1 === (int) $identity[$zendAuthCredentialMatchColumn]) {
  333. $validIdentities[] = $identity;
  334. }
  335. }
  336. $resultIdentities = $validIdentities;
  337. }
  338. $authResult = $this->_authenticateValidateResult(array_shift($resultIdentities));
  339. return $authResult;
  340. }
  341. /**
  342. * _authenticateSetup() - This method abstracts the steps involved with
  343. * making sure that this adapter was indeed setup properly with all
  344. * required pieces of information.
  345. *
  346. * @throws Zend_Auth_Adapter_Exception - in the event that setup was not done properly
  347. * @return true
  348. */
  349. protected function _authenticateSetup()
  350. {
  351. $exception = null;
  352. if ($this->_tableName == '') {
  353. $exception = 'A table must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
  354. } elseif ($this->_identityColumn == '') {
  355. $exception = 'An identity column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
  356. } elseif ($this->_credentialColumn == '') {
  357. $exception = 'A credential column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
  358. } elseif ($this->_identity == '') {
  359. $exception = 'A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
  360. } elseif ($this->_credential === null) {
  361. $exception = 'A credential value was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
  362. }
  363. if (null !== $exception) {
  364. /**
  365. * @see Zend_Auth_Adapter_Exception
  366. */
  367. require_once 'Zend/Auth/Adapter/Exception.php';
  368. throw new Zend_Auth_Adapter_Exception($exception);
  369. }
  370. $this->_authenticateResultInfo = array(
  371. 'code' => Zend_Auth_Result::FAILURE,
  372. 'identity' => $this->_identity,
  373. 'messages' => array()
  374. );
  375. return true;
  376. }
  377. /**
  378. * _authenticateCreateSelect() - This method creates a Zend_Db_Select object that
  379. * is completely configured to be queried against the database.
  380. *
  381. * @return Zend_Db_Select
  382. */
  383. protected function _authenticateCreateSelect()
  384. {
  385. // build credential expression
  386. if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, '?') === false)) {
  387. $this->_credentialTreatment = '?';
  388. }
  389. $credentialExpression = new Zend_Db_Expr(
  390. '(CASE WHEN ' .
  391. $this->_zendDb->quoteInto(
  392. $this->_zendDb->quoteIdentifier($this->_credentialColumn, true)
  393. . ' = ' . $this->_credentialTreatment, $this->_credential
  394. )
  395. . ' THEN 1 ELSE 0 END) AS '
  396. . $this->_zendDb->quoteIdentifier(
  397. $this->_zendDb->foldCase('zend_auth_credential_match')
  398. )
  399. );
  400. // get select
  401. $dbSelect = clone $this->getDbSelect();
  402. $dbSelect->from($this->_tableName, array('*', $credentialExpression))
  403. ->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity);
  404. return $dbSelect;
  405. }
  406. /**
  407. * _authenticateQuerySelect() - This method accepts a Zend_Db_Select object and
  408. * performs a query against the database with that object.
  409. *
  410. * @param Zend_Db_Select $dbSelect
  411. * @throws Zend_Auth_Adapter_Exception - when an invalid select
  412. * object is encountered
  413. * @return array
  414. */
  415. protected function _authenticateQuerySelect(Zend_Db_Select $dbSelect)
  416. {
  417. try {
  418. if ($this->_zendDb->getFetchMode() != Zend_DB::FETCH_ASSOC) {
  419. $origDbFetchMode = $this->_zendDb->getFetchMode();
  420. $this->_zendDb->setFetchMode(Zend_DB::FETCH_ASSOC);
  421. }
  422. $resultIdentities = $this->_zendDb->fetchAll($dbSelect);
  423. if (isset($origDbFetchMode)) {
  424. $this->_zendDb->setFetchMode($origDbFetchMode);
  425. unset($origDbFetchMode);
  426. }
  427. } catch (Exception $e) {
  428. /**
  429. * @see Zend_Auth_Adapter_Exception
  430. */
  431. require_once 'Zend/Auth/Adapter/Exception.php';
  432. throw new Zend_Auth_Adapter_Exception('The supplied parameters to Zend_Auth_Adapter_DbTable failed to '
  433. . 'produce a valid sql statement, please check table and column names '
  434. . 'for validity.', 0, $e);
  435. }
  436. return $resultIdentities;
  437. }
  438. /**
  439. * _authenticateValidateResultSet() - This method attempts to make
  440. * certain that only one record was returned in the resultset
  441. *
  442. * @param array $resultIdentities
  443. * @return true|Zend_Auth_Result
  444. */
  445. protected function _authenticateValidateResultSet(array $resultIdentities)
  446. {
  447. if (count($resultIdentities) < 1) {
  448. $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
  449. $this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.';
  450. return $this->_authenticateCreateAuthResult();
  451. } elseif (count($resultIdentities) > 1 && false === $this->getAmbiguityIdentity()) {
  452. $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
  453. $this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.';
  454. return $this->_authenticateCreateAuthResult();
  455. }
  456. return true;
  457. }
  458. /**
  459. * _authenticateValidateResult() - This method attempts to validate that
  460. * the record in the resultset is indeed a record that matched the
  461. * identity provided to this adapter.
  462. *
  463. * @param array $resultIdentity
  464. * @return Zend_Auth_Result
  465. */
  466. protected function _authenticateValidateResult($resultIdentity)
  467. {
  468. $zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match');
  469. if ($resultIdentity[$zendAuthCredentialMatchColumn] != '1') {
  470. $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
  471. $this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
  472. return $this->_authenticateCreateAuthResult();
  473. }
  474. unset($resultIdentity[$zendAuthCredentialMatchColumn]);
  475. $this->_resultRow = $resultIdentity;
  476. $this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS;
  477. $this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
  478. return $this->_authenticateCreateAuthResult();
  479. }
  480. /**
  481. * _authenticateCreateAuthResult() - Creates a Zend_Auth_Result object from
  482. * the information that has been collected during the authenticate() attempt.
  483. *
  484. * @return Zend_Auth_Result
  485. */
  486. protected function _authenticateCreateAuthResult()
  487. {
  488. return new Zend_Auth_Result(
  489. $this->_authenticateResultInfo['code'],
  490. $this->_authenticateResultInfo['identity'],
  491. $this->_authenticateResultInfo['messages']
  492. );
  493. }
  494. }