Permalink
Browse files

Merge branch 'hotfix/ZF2-199' of https://github.com/rhunwicks/zf2 int…

…o hotfix/zf2-199
  • Loading branch information...
2 parents ab7c575 + d532378 commit 60c852d09b171f922f0c8cb5d80e49c7cd837846 @weierophinney weierophinney committed Apr 9, 2012
Showing with 106 additions and 202 deletions.
  1. +64 −104 library/Zend/Authentication/Adapter/DbTable.php
  2. +42 −98 tests/Zend/Authentication/Adapter/DbTableTest.php
View
168 library/Zend/Authentication/Adapter/DbTable.php
@@ -22,17 +22,12 @@
namespace Zend\Authentication\Adapter;
use Zend\Authentication\Adapter as AuthenticationAdapter,
Zend\Authentication\Result as AuthenticationResult,
- Zend\Db\Db,
- Zend\Db\Adapter\AbstractAdapter as AbstractDBAdapter,
- Zend\Db\Expr as DBExpr,
- Zend\Db\Select as DBSelect,
- Zend\Db\Table\AbstractTable;
+ Zend\Db\Adapter\Adapter as DbAdapter,
+ Zend\Db\Sql\Select as DbSelect,
+ Zend\Db\Sql\Expression,
+ Zend\Db\ResultSet\ResultSet;
/**
- * @uses Zend\Authentication\Adapter\Exception
- * @uses Zend\Authentication\Adapter
- * @uses Zend\Authentication\Result
- * @uses Zend_Db_Adapter_Abstract
* @category Zend
* @package Zend_Authentication
* @subpackage Adapter
@@ -45,12 +40,12 @@ class DbTable implements AuthenticationAdapter
/**
* Database Connection
*
- * @var Zend\Db\Adapter\AbstractAdapter
+ * @var DbAdapter
*/
protected $_zendDb = null;
/**
- * @var Zend\Db\Select
+ * @var DbSelect
*/
protected $_dbSelect = null;
@@ -109,30 +104,30 @@ class DbTable implements AuthenticationAdapter
* @var array
*/
protected $_resultRow = null;
-
+
/**
- * $_ambiguityIdentity - Flag to indicate same Identity can be used with
+ * $_ambiguityIdentity - Flag to indicate same Identity can be used with
* different credentials. Default is FALSE and need to be set to true to
* allow ambiguity usage.
- *
+ *
* @var boolean
*/
protected $_ambiguityIdentity = false;
/**
* __construct() - Sets configuration options
*
- * @param Zend\Db\Adapter\AbstractAdapter $zendDb
+ * @param DbAdapter $zendDb
* @param string $tableName
* @param string $identityColumn
* @param string $credentialColumn
* @param string $credentialTreatment
* @return void
*/
- public function __construct(AbstractDBAdapter $zendDb = null, $tableName = null, $identityColumn = null,
+ public function __construct(DbAdapter $zendDb, $tableName = null, $identityColumn = null,
$credentialColumn = null, $credentialTreatment = null)
{
- $this->_setDbAdapter($zendDb);
+ $this->_zendDb = $zendDb;
if (null !== $tableName) {
$this->setTableName($tableName);
@@ -152,37 +147,10 @@ public function __construct(AbstractDBAdapter $zendDb = null, $tableName = null,
}
/**
- * _setDbAdapter() - set the database adapter to be used for quering
- *
- * @param Zend_Db_Adapter_Abstract
- * @throws Zend_Auth_Adapter_Exception
- * @return Zend_Auth_Adapter_DbTable
- */
- protected function _setDbAdapter(AbstractDBAdapter $zendDb = null)
- {
- $this->_zendDb = $zendDb;
-
- /**
- * If no adapter is specified, fetch default database adapter.
- */
- if(null === $this->_zendDb) {
- $this->_zendDb = AbstractTable::getDefaultAdapter();
- if (null === $this->_zendDb) {
- throw new Exception\RuntimeException(
- 'Null was provided for the adapter but there is no default'
- . ' adatper registered with Zend\Db\Table to utilize.'
- );
- }
- }
-
- return $this;
- }
-
- /**
* setTableName() - set the table name to be used in the select query
*
* @param string $tableName
- * @return Zend\Authentication\Adapter\DbTable Provides a fluent interface
+ * @return DbTable Provides a fluent interface
*/
public function setTableName($tableName)
{
@@ -194,7 +162,7 @@ public function setTableName($tableName)
* setIdentityColumn() - set the column name to be used as the identity column
*
* @param string $identityColumn
- * @return Zend\Authentication\Adapter\DbTable Provides a fluent interface
+ * @return DbTable Provides a fluent interface
*/
public function setIdentityColumn($identityColumn)
{
@@ -206,7 +174,7 @@ public function setIdentityColumn($identityColumn)
* setCredentialColumn() - set the column name to be used as the credential column
*
* @param string $credentialColumn
- * @return Zend\Authentication\Adapter\DbTable Provides a fluent interface
+ * @return DbTable Provides a fluent interface
*/
public function setCredentialColumn($credentialColumn)
{
@@ -229,7 +197,7 @@ public function setCredentialColumn($credentialColumn)
* 'MD5(?)'
*
* @param string $treatment
- * @return Zend\Authentication\Adapter\DbTable Provides a fluent interface
+ * @return DbTable Provides a fluent interface
*/
public function setCredentialTreatment($treatment)
{
@@ -241,7 +209,7 @@ public function setCredentialTreatment($treatment)
* setIdentity() - set the value to be used as the identity
*
* @param string $value
- * @return Zend\Authentication\Adapter\DbTable Provides a fluent interface
+ * @return DbTable Provides a fluent interface
*/
public function setIdentity($value)
{
@@ -254,21 +222,21 @@ public function setIdentity($value)
* to be used, should be supplied in parameterized form, such as 'MD5(?)' or 'PASSWORD(?)'
*
* @param string $credential
- * @return Zend\Authentication\Adapter\DbTable Provides a fluent interface
+ * @return DbTable Provides a fluent interface
*/
public function setCredential($credential)
{
$this->_credential = $credential;
return $this;
}
-
+
/**
* setAmbiguityIdentity() - sets a flag for usage of identical identities
* with unique credentials. It accepts integers (0, 1) or boolean (true,
* false) parameters. Default is false.
- *
+ *
* @param int|bool $flag
- * @return Zend_Auth_Adapter_DbTable
+ * @return DbTable Provides a fluent interface
*/
public function setAmbiguityIdentity($flag)
{
@@ -279,10 +247,11 @@ public function setAmbiguityIdentity($flag)
}
return $this;
}
+
/**
- * getAmbiguityIdentity() - returns TRUE for usage of multiple identical
+ * getAmbiguityIdentity() - returns TRUE for usage of multiple identical
* identies with different credentials, FALSE if not used.
- *
+ *
* @return bool
*/
public function getAmbiguityIdentity()
@@ -293,14 +262,13 @@ public function getAmbiguityIdentity()
/**
* getDbSelect() - Return the preauthentication Db Select object for userland select query modification
*
- * @return Zend\Db\Select
+ * @return DbSelect
*/
public function getDbSelect()
{
if ($this->_dbSelect == null) {
- $this->_dbSelect = $this->_zendDb->select();
+ $this->_dbSelect = new DbSelect();
}
-
return $this->_dbSelect;
}
@@ -355,8 +323,8 @@ public function getResultRowObject($returnColumns = null, $omitColumns = null)
* been configured with all necessary information to successfully connect to a database
* table and attempt to find a record matching the provided identity.
*
- * @throws Zend\Authentication\Adapter\Exception if answering the authentication query is impossible
- * @return Zend\Authentication\Result
+ * @throws Exception if answering the authentication query is impossible
+ * @return AuthenticationResult
*/
public function authenticate()
{
@@ -368,7 +336,7 @@ public function authenticate()
return $authResult;
}
- // At this point, ambiguity is allready done. Loop, check and break on success.
+ // At this point, ambiguity is already done. Loop, check and break on success.
foreach ($resultIdentities as $identity) {
$authResult = $this->_authenticateValidateResult($identity);
if ($authResult->isValid()) {
@@ -384,23 +352,23 @@ public function authenticate()
* making sure that this adapter was indeed setup properly with all
* required pieces of information.
*
- * @throws Zend\Authentication\Adapter\Exception - in the event that setup was not done properly
+ * @throws Exception - in the event that setup was not done properly
* @return true
*/
protected function _authenticateSetup()
{
$exception = null;
if ($this->_tableName == '') {
- $exception = 'A table must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
+ $exception = 'A table must be supplied for the DbTable authentication adapter.';
} elseif ($this->_identityColumn == '') {
- $exception = 'An identity column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
+ $exception = 'An identity column must be supplied for the DbTable authentication adapter.';
} elseif ($this->_credentialColumn == '') {
- $exception = 'A credential column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
+ $exception = 'A credential column must be supplied for the DbTable authentication adapter.';
} elseif ($this->_identity == '') {
- $exception = 'A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
+ $exception = 'A value for the identity was not provided prior to authentication with DbTable.';
} elseif ($this->_credential === null) {
- $exception = 'A credential value was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
+ $exception = 'A credential value was not provided prior to authentication with DbTable.';
}
if (null !== $exception) {
@@ -417,10 +385,10 @@ protected function _authenticateSetup()
}
/**
- * _authenticateCreateSelect() - This method creates a Zend_Db_Select object that
+ * _authenticateCreateSelect() - This method creates a Zend\Db\Sql\Select object that
* is completely configured to be queried against the database.
*
- * @return Zend_Db_Select
+ * @return DbSelect
*/
protected function _authenticateCreateSelect()
{
@@ -429,51 +397,45 @@ protected function _authenticateCreateSelect()
$this->_credentialTreatment = '?';
}
- $credentialExpression = new DBExpr(
- '(CASE WHEN ' .
- $this->_zendDb->quoteInto(
- $this->_zendDb->quoteIdentifier($this->_credentialColumn, true)
- . ' = ' . $this->_credentialTreatment, $this->_credential
- )
+ $credentialExpression = new Expression(
+ '(CASE WHEN '
+ . $this->_zendDb->getPlatform()->quoteIdentifier($this->_credentialColumn)
+ . ' = ' . $this->_credentialTreatment
. ' THEN 1 ELSE 0 END) AS '
- . $this->_zendDb->quoteIdentifier(
- $this->_zendDb->foldCase('zend_auth_credential_match')
- )
- );
+ . $this->_zendDb->getPlatform()->quoteIdentifier('zend_auth_credential_match')
+ );
// get select
$dbSelect = clone $this->getDbSelect();
- $dbSelect->from($this->_tableName, array('*', $credentialExpression))
- ->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity);
+ $dbSelect->from($this->_tableName)
+ ->columns(array('*', $credentialExpression))
+ ->where($this->_zendDb->getPlatform()->quoteIdentifier($this->_identityColumn) . ' = ?');
return $dbSelect;
}
/**
- * _authenticateQuerySelect() - This method accepts a Zend_Db_Select object and
+ * _authenticateQuerySelect() - This method accepts a Zend\Db\Sql\Select object and
* performs a query against the database with that object.
*
- * @param Zend_Db_Select $dbSelect
- * @throws \Zend\Authentication\Adapter\Exception - when an invalid select
- * object is encountered
+ * @param DbSelect $dbSelect
+ * @throws Exception - when an invalid select object is encountered
* @return array
*/
protected function _authenticateQuerySelect(DBSelect $dbSelect)
{
+ $statement = $this->_zendDb->createStatement();
+ $dbSelect->prepareStatement($this->_zendDb, $statement);
+ $resultSet = new ResultSet();
try {
- if ($this->_zendDb->getFetchMode() != Db::FETCH_ASSOC) {
- $origDbFetchMode = $this->_zendDb->getFetchMode();
- $this->_zendDb->setFetchMode(Db::FETCH_ASSOC);
- }
- $resultIdentities = $this->_zendDb->fetchAll($dbSelect->__toString());
- if (isset($origDbFetchMode)) {
- $this->_zendDb->setFetchMode($origDbFetchMode);
- unset($origDbFetchMode);
- }
+ $resultSet->setDataSource($statement->execute(array($this->_credential, $this->_identity)));
+ $resultIdentities = $resultSet->toArray();
} catch (\Exception $e) {
- throw new Exception\RuntimeException('The supplied parameters to Zend\Authentication\Adapter\DbTable failed to '
- . 'produce a valid sql statement, please check table and column names '
- . 'for validity.', 0, $e);
+ throw new Exception\RuntimeException(
+ 'The supplied parameters to DbTable failed to '
+ . 'produce a valid sql statement, please check table and column names '
+ . 'for validity.', 0, $e
+ );
}
return $resultIdentities;
}
@@ -507,19 +469,17 @@ protected function _authenticateValidateResultSet(array $resultIdentities)
* identity provided to this adapter.
*
* @param array $resultIdentity
- * @return Zend\Authentication\Result
+ * @return AuthenticationResult
*/
protected function _authenticateValidateResult($resultIdentity)
{
- $zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match');
-
- if ($resultIdentity[$zendAuthCredentialMatchColumn] != '1') {
+ if ($resultIdentity['zend_auth_credential_match'] != '1') {
$this->_authenticateResultInfo['code'] = AuthenticationResult::FAILURE_CREDENTIAL_INVALID;
$this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
return $this->_authenticateCreateAuthResult();
}
- unset($resultIdentity[$zendAuthCredentialMatchColumn]);
+ unset($resultIdentity['zend_auth_credential_match']);
$this->_resultRow = $resultIdentity;
$this->_authenticateResultInfo['code'] = AuthenticationResult::SUCCESS;
@@ -531,15 +491,15 @@ protected function _authenticateValidateResult($resultIdentity)
* _authenticateCreateAuthResult() - Creates a Zend_Auth_Result object from
* the information that has been collected during the authenticate() attempt.
*
- * @return \Zend\Authentication\Result
+ * @return AuthenticationResult
*/
protected function _authenticateCreateAuthResult()
{
return new AuthenticationResult(
$this->_authenticateResultInfo['code'],
$this->_authenticateResultInfo['identity'],
$this->_authenticateResultInfo['messages']
- );
+ );
}
}
View
140 tests/Zend/Authentication/Adapter/DbTableTest.php
@@ -23,9 +23,8 @@
use Zend\Authentication\Adapter,
Zend\Authentication,
- Zend\Db\Db,
- Zend\Db\Adapter\Pdo\Sqlite as SQLiteAdapter,
- Zend\Db\Select as DBSelect;
+ Zend\Db\Adapter\Adapter as DbAdapter,
+ Zend\Db\Sql\Select as DBSelect;
/**
* @category Zend
@@ -41,14 +40,14 @@ class DbTableTest extends \PHPUnit_Framework_TestCase
/**
* Sqlite database connection
*
- * @var Zend_Db_Adapter_Pdo_Sqlite
+ * @var Zend\Db\Adapter
*/
protected $_db = null;
/**
* Database table authentication adapter
*
- * @var Zend_Auth_Adapter_DbTable
+ * @var Zend\Authentication\Adapter\DbTable
*/
protected $_adapter = null;
@@ -137,8 +136,8 @@ public function testAuthenticateFailureIdentityNotFound()
*/
public function testAuthenticateFailureIdentityAmbigious()
{
- $sql_insert = 'INSERT INTO users (username, password, real_name) VALUES ("my_username", "my_password", "My Real Name")';
- $this->_db->query($sql_insert);
+ $sqlInsert = 'INSERT INTO users (username, password, real_name) VALUES ("my_username", "my_password", "My Real Name")';
+ $this->_db->query($sqlInsert, DbAdapter::QUERY_MODE_EXECUTE);
$this->_adapter->setIdentity('my_username');
$this->_adapter->setCredential('my_password');
@@ -217,17 +216,16 @@ public function testAdapterCanReturnDbSelectObject()
*/
public function testAdapterCanUseModifiedDbSelectObject()
{
- $this->_db->getProfiler()->setEnabled(true);
$select = $this->_adapter->getDbSelect();
- $select->where('1 = 1');
+ $select->where('1 = 0');
$this->_adapter->setIdentity('my_username');
$this->_adapter->setCredential('my_password');
- $this->_adapter->authenticate();
- $profiler = $this->_db->getProfiler();
- $this->assertEquals(
- 'SELECT "users".*, (CASE WHEN "password" = \'my_password\' THEN 1 ELSE 0 END) AS "zend_auth_credential_match" FROM "users" WHERE (1 = 1) AND ("username" = \'my_username\')',
- $profiler->getLastQueryProfile()->getQuery()
- );
+ try {
+ $result = $this->_adapter->authenticate();
+ $this->assertEquals(Authentication\Result::FAILURE_IDENTITY_NOT_FOUND, $result->getCode());
+ } catch (Adapter\Exception\RuntimeException $e) {
+ $this->fail('Exception should have been thrown');
+ }
}
/**
@@ -241,9 +239,11 @@ public function testAdapterReturnsASelectObjectWithoutAuthTimeModificationsAfter
$this->_adapter->setCredential('my_password');
$this->_adapter->authenticate();
$selectAfterAuth = $this->_adapter->getDbSelect();
- $whereParts = $selectAfterAuth->getPart(DBSelect::WHERE);
+ $whereParts = $selectAfterAuth->where->getPredicates();
$this->assertEquals(1, count($whereParts));
- $this->assertEquals('(1 = 1)', array_pop($whereParts));
+ $lastWherePart = array_pop($whereParts);
+ $expressionData = $lastWherePart[1]->getExpressionData();
+ $this->assertEquals('1 = 1', $expressionData[0][0]);
}
/**
@@ -308,79 +308,18 @@ public function testCatchExceptionBadSql()
}
/**
- *
- * @group ZF-3068
- */
- public function testDbTableAdapterUsesCaseFolding()
- {
- $this->tearDown();
- $this->_setupDbAdapter(array(Db::CASE_FOLDING => Db::CASE_UPPER));
- $this->_setupAuthAdapter();
-
- $this->_adapter->setIdentity('my_username');
- $this->_adapter->setCredential('my_password');
- $this->_db->foldCase(Db::CASE_UPPER);
- $this->_adapter->authenticate();
- }
-
-
- /**
- * Test fallback to default database adapter, when no such adapter set
- *
- * @group ZF-7510
- */
- public function testAuthenticateWithDefaultDbAdapterNoAdapterException()
- {
- $this->setExpectedException('Zend\Authentication\Adapter\Exception\RuntimeException', 'Null was provided');
-
- // make sure that no default adapter exists
- \Zend\Db\Table\AbstractTable::setDefaultAdapter(null);
- $this->_adapter = new Adapter\DbTable();
- }
-
- /**
- * Test fallback to default database adapter
- *
- * @group ZF-7510
- */
- public function testAuthenticateWithDefaultDbAdapter()
- {
- // preserve default adapter between cases
- $tmp = \Zend\Db\Table\AbstractTable::getDefaultAdapter();
-
- // make sure that default db adapter exists
- \Zend\Db\Table\AbstractTable::setDefaultAdapter($this->_db);
-
- // check w/o passing adapter
- $this->_adapter = new Adapter\DbTable();
- $this->_adapter
- ->setTableName('users')
- ->setIdentityColumn('username')
- ->setCredentialColumn('password')
- ->setTableName('users')
- ->setIdentity('my_username')
- ->setCredential('my_password');
- $result = $this->_adapter->authenticate();
- $this->assertTrue($result->isValid());
-
- // restore adapter
- \Zend\Db\Table\AbstractTable::setDefaultAdapter($tmp);
- }
- /**
* Test to see same usernames with different passwords can not authenticate
- * when flag is not set. This is the current state of
+ * when flag is not set. This is the current state of
* Zend_Auth_Adapter_DbTable (up to ZF 1.10.6)
- *
+ *
* @group ZF-7289
*/
public function testEqualUsernamesDifferentPasswordShouldNotAuthenticateWhenFlagIsNotSet()
{
- $this->_db->insert('users', array (
- 'username' => 'my_username',
- 'password' => 'my_otherpass',
- 'real_name' => 'Test user 2',
- ));
-
+ $sqlInsert = 'INSERT INTO users (username, password, real_name) '
+ . 'VALUES ("my_username", "my_otherpass", "Test user 2")';
+ $this->_db->query($sqlInsert, DbAdapter::QUERY_MODE_EXECUTE);
+
// test if user 1 can authenticate
$this->_adapter->setIdentity('my_username')
->setCredential('my_password');
@@ -389,20 +328,19 @@ public function testEqualUsernamesDifferentPasswordShouldNotAuthenticateWhenFlag
$result->getMessages()));
$this->assertFalse($result->isValid());
}
+
/**
* Test to see same usernames with different passwords can authenticate when
* a flag is set
- *
+ *
* @group ZF-7289
*/
public function testEqualUsernamesDifferentPasswordShouldAuthenticateWhenFlagIsSet()
{
- $this->_db->insert('users', array (
- 'username' => 'my_username',
- 'password' => 'my_otherpass',
- 'real_name' => 'Test user 2',
- ));
-
+ $sqlInsert = 'INSERT INTO users (username, password, real_name) '
+ . 'VALUES ("my_username", "my_otherpass", "Test user 2")';
+ $this->_db->query($sqlInsert, DbAdapter::QUERY_MODE_EXECUTE);
+
// test if user 1 can authenticate
$this->_adapter->setIdentity('my_username')
->setCredential('my_password')
@@ -412,10 +350,10 @@ public function testEqualUsernamesDifferentPasswordShouldAuthenticateWhenFlagIsS
$result->getMessages()));
$this->assertTrue($result->isValid());
$this->assertEquals('my_username', $result->getIdentity());
-
+
$this->_adapter = null;
$this->_setupAuthAdapter();
-
+
// test if user 2 can authenticate
$this->_adapter->setIdentity('my_username')
->setCredential('my_otherpass')
@@ -430,28 +368,34 @@ public function testEqualUsernamesDifferentPasswordShouldAuthenticateWhenFlagIsS
protected function _setupDbAdapter($optionalParams = array())
{
- $params = array('dbname' => TESTS_ZEND_AUTH_ADAPTER_DBTABLE_PDO_SQLITE_DATABASE);
+ $params = array('driver' => 'pdo_sqlite',
+ 'dbname' => TESTS_ZEND_AUTH_ADAPTER_DBTABLE_PDO_SQLITE_DATABASE);
if (!empty($optionalParams)) {
$params['options'] = $optionalParams;
}
- $this->_db = new SQLiteAdapter($params);
+ $this->_db = new DbAdapter($params);
- $sqlCreate = 'CREATE TABLE [users] ( '
+ $sqlCreate = 'CREATE TABLE IF NOT EXISTS [users] ( '
. '[id] INTEGER NOT NULL PRIMARY KEY, '
. '[username] VARCHAR(50) NOT NULL, '
. '[password] VARCHAR(32) NULL, '
. '[real_name] VARCHAR(150) NULL)';
- $this->_db->query($sqlCreate);
+ $this->_db->query($sqlCreate, DbAdapter::QUERY_MODE_EXECUTE);
+
+ $sqlDelete = 'DELETE FROM users';
+ $this->_db->query($sqlDelete, DbAdapter::QUERY_MODE_EXECUTE);
$sqlInsert = 'INSERT INTO users (username, password, real_name) '
. 'VALUES ("my_username", "my_password", "My Real Name")';
- $this->_db->query($sqlInsert);
+ $this->_db->query($sqlInsert, DbAdapter::QUERY_MODE_EXECUTE);
}
protected function _setupAuthAdapter()
{
$this->_adapter = new Adapter\DbTable($this->_db, 'users', 'username', 'password');
}
+
}
+

0 comments on commit 60c852d

Please sign in to comment.