adding zend project folders into old campcaster.

This commit is contained in:
naomiaro 2010-12-07 14:19:27 -05:00
parent 56abfaf28e
commit 7ef0c18b26
4045 changed files with 1054952 additions and 0 deletions

View file

@ -0,0 +1,487 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: DbTable.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Auth_Adapter_Interface
*/
require_once 'Zend/Auth/Adapter/Interface.php';
/**
* @see Zend_Db_Adapter_Abstract
*/
require_once 'Zend/Db/Adapter/Abstract.php';
/**
* @see Zend_Auth_Result
*/
require_once 'Zend/Auth/Result.php';
/**
* @category Zend
* @package Zend_Auth
* @subpackage Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_DbTable implements Zend_Auth_Adapter_Interface
{
/**
* Database Connection
*
* @var Zend_Db_Adapter_Abstract
*/
protected $_zendDb = null;
/**
* @var Zend_Db_Select
*/
protected $_dbSelect = null;
/**
* $_tableName - the table name to check
*
* @var string
*/
protected $_tableName = null;
/**
* $_identityColumn - the column to use as the identity
*
* @var string
*/
protected $_identityColumn = null;
/**
* $_credentialColumns - columns to be used as the credentials
*
* @var string
*/
protected $_credentialColumn = null;
/**
* $_identity - Identity value
*
* @var string
*/
protected $_identity = null;
/**
* $_credential - Credential values
*
* @var string
*/
protected $_credential = null;
/**
* $_credentialTreatment - Treatment applied to the credential, such as MD5() or PASSWORD()
*
* @var string
*/
protected $_credentialTreatment = null;
/**
* $_authenticateResultInfo
*
* @var array
*/
protected $_authenticateResultInfo = null;
/**
* $_resultRow - Results of database authentication query
*
* @var array
*/
protected $_resultRow = null;
/**
* __construct() - Sets configuration options
*
* @param Zend_Db_Adapter_Abstract $zendDb
* @param string $tableName
* @param string $identityColumn
* @param string $credentialColumn
* @param string $credentialTreatment
* @return void
*/
public function __construct(Zend_Db_Adapter_Abstract $zendDb, $tableName = null, $identityColumn = null,
$credentialColumn = null, $credentialTreatment = null)
{
$this->_zendDb = $zendDb;
if (null !== $tableName) {
$this->setTableName($tableName);
}
if (null !== $identityColumn) {
$this->setIdentityColumn($identityColumn);
}
if (null !== $credentialColumn) {
$this->setCredentialColumn($credentialColumn);
}
if (null !== $credentialTreatment) {
$this->setCredentialTreatment($credentialTreatment);
}
}
/**
* setTableName() - set the table name to be used in the select query
*
* @param string $tableName
* @return Zend_Auth_Adapter_DbTable Provides a fluent interface
*/
public function setTableName($tableName)
{
$this->_tableName = $tableName;
return $this;
}
/**
* setIdentityColumn() - set the column name to be used as the identity column
*
* @param string $identityColumn
* @return Zend_Auth_Adapter_DbTable Provides a fluent interface
*/
public function setIdentityColumn($identityColumn)
{
$this->_identityColumn = $identityColumn;
return $this;
}
/**
* setCredentialColumn() - set the column name to be used as the credential column
*
* @param string $credentialColumn
* @return Zend_Auth_Adapter_DbTable Provides a fluent interface
*/
public function setCredentialColumn($credentialColumn)
{
$this->_credentialColumn = $credentialColumn;
return $this;
}
/**
* setCredentialTreatment() - allows the developer to pass a parameterized string that is
* used to transform or treat the input credential data.
*
* In many cases, passwords and other sensitive data are encrypted, hashed, encoded,
* obscured, or otherwise treated through some function or algorithm. By specifying a
* parameterized treatment string with this method, a developer may apply arbitrary SQL
* upon input credential data.
*
* Examples:
*
* 'PASSWORD(?)'
* 'MD5(?)'
*
* @param string $treatment
* @return Zend_Auth_Adapter_DbTable Provides a fluent interface
*/
public function setCredentialTreatment($treatment)
{
$this->_credentialTreatment = $treatment;
return $this;
}
/**
* setIdentity() - set the value to be used as the identity
*
* @param string $value
* @return Zend_Auth_Adapter_DbTable Provides a fluent interface
*/
public function setIdentity($value)
{
$this->_identity = $value;
return $this;
}
/**
* setCredential() - set the credential value to be used, optionally can specify a treatment
* to be used, should be supplied in parameterized form, such as 'MD5(?)' or 'PASSWORD(?)'
*
* @param string $credential
* @return Zend_Auth_Adapter_DbTable Provides a fluent interface
*/
public function setCredential($credential)
{
$this->_credential = $credential;
return $this;
}
/**
* getDbSelect() - Return the preauthentication Db Select object for userland select query modification
*
* @return Zend_Db_Select
*/
public function getDbSelect()
{
if ($this->_dbSelect == null) {
$this->_dbSelect = $this->_zendDb->select();
}
return $this->_dbSelect;
}
/**
* getResultRowObject() - Returns the result row as a stdClass object
*
* @param string|array $returnColumns
* @param string|array $omitColumns
* @return stdClass|boolean
*/
public function getResultRowObject($returnColumns = null, $omitColumns = null)
{
if (!$this->_resultRow) {
return false;
}
$returnObject = new stdClass();
if (null !== $returnColumns) {
$availableColumns = array_keys($this->_resultRow);
foreach ( (array) $returnColumns as $returnColumn) {
if (in_array($returnColumn, $availableColumns)) {
$returnObject->{$returnColumn} = $this->_resultRow[$returnColumn];
}
}
return $returnObject;
} elseif (null !== $omitColumns) {
$omitColumns = (array) $omitColumns;
foreach ($this->_resultRow as $resultColumn => $resultValue) {
if (!in_array($resultColumn, $omitColumns)) {
$returnObject->{$resultColumn} = $resultValue;
}
}
return $returnObject;
} else {
foreach ($this->_resultRow as $resultColumn => $resultValue) {
$returnObject->{$resultColumn} = $resultValue;
}
return $returnObject;
}
}
/**
* authenticate() - defined by Zend_Auth_Adapter_Interface. This method is called to
* attempt an authentication. Previous to this call, this adapter would have already
* 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_Auth_Adapter_Exception if answering the authentication query is impossible
* @return Zend_Auth_Result
*/
public function authenticate()
{
$this->_authenticateSetup();
$dbSelect = $this->_authenticateCreateSelect();
$resultIdentities = $this->_authenticateQuerySelect($dbSelect);
if ( ($authResult = $this->_authenticateValidateResultset($resultIdentities)) instanceof Zend_Auth_Result) {
return $authResult;
}
$authResult = $this->_authenticateValidateResult(array_shift($resultIdentities));
return $authResult;
}
/**
* _authenticateSetup() - This method abstracts the steps involved with
* making sure that this adapter was indeed setup properly with all
* required pieces of information.
*
* @throws Zend_Auth_Adapter_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.';
} elseif ($this->_identityColumn == '') {
$exception = 'An identity column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
} elseif ($this->_credentialColumn == '') {
$exception = 'A credential column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
} elseif ($this->_identity == '') {
$exception = 'A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
} elseif ($this->_credential === null) {
$exception = 'A credential value was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
}
if (null !== $exception) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception($exception);
}
$this->_authenticateResultInfo = array(
'code' => Zend_Auth_Result::FAILURE,
'identity' => $this->_identity,
'messages' => array()
);
return true;
}
/**
* _authenticateCreateSelect() - This method creates a Zend_Db_Select object that
* is completely configured to be queried against the database.
*
* @return Zend_Db_Select
*/
protected function _authenticateCreateSelect()
{
// build credential expression
if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, '?') === false)) {
$this->_credentialTreatment = '?';
}
$credentialExpression = new Zend_Db_Expr(
'(CASE WHEN ' .
$this->_zendDb->quoteInto(
$this->_zendDb->quoteIdentifier($this->_credentialColumn, true)
. ' = ' . $this->_credentialTreatment, $this->_credential
)
. ' THEN 1 ELSE 0 END) AS '
. $this->_zendDb->quoteIdentifier(
$this->_zendDb->foldCase('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);
return $dbSelect;
}
/**
* _authenticateQuerySelect() - This method accepts a Zend_Db_Select object and
* performs a query against the database with that object.
*
* @param Zend_Db_Select $dbSelect
* @throws Zend_Auth_Adapter_Exception - when an invalid select
* object is encountered
* @return array
*/
protected function _authenticateQuerySelect(Zend_Db_Select $dbSelect)
{
try {
if ($this->_zendDb->getFetchMode() != Zend_DB::FETCH_ASSOC) {
$origDbFetchMode = $this->_zendDb->getFetchMode();
$this->_zendDb->setFetchMode(Zend_DB::FETCH_ASSOC);
}
$resultIdentities = $this->_zendDb->fetchAll($dbSelect->__toString());
if (isset($origDbFetchMode)) {
$this->_zendDb->setFetchMode($origDbFetchMode);
unset($origDbFetchMode);
}
} catch (Exception $e) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('The supplied parameters to Zend_Auth_Adapter_DbTable failed to '
. 'produce a valid sql statement, please check table and column names '
. 'for validity.', 0, $e);
}
return $resultIdentities;
}
/**
* _authenticateValidateResultSet() - This method attempts to make
* certain that only one record was returned in the resultset
*
* @param array $resultIdentities
* @return true|Zend_Auth_Result
*/
protected function _authenticateValidateResultSet(array $resultIdentities)
{
if (count($resultIdentities) < 1) {
$this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
$this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.';
return $this->_authenticateCreateAuthResult();
} elseif (count($resultIdentities) > 1) {
$this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
$this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.';
return $this->_authenticateCreateAuthResult();
}
return true;
}
/**
* _authenticateValidateResult() - This method attempts to validate that
* the record in the resultset is indeed a record that matched the
* identity provided to this adapter.
*
* @param array $resultIdentity
* @return Zend_Auth_Result
*/
protected function _authenticateValidateResult($resultIdentity)
{
$zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match');
if ($resultIdentity[$zendAuthCredentialMatchColumn] != '1') {
$this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
$this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
return $this->_authenticateCreateAuthResult();
}
unset($resultIdentity[$zendAuthCredentialMatchColumn]);
$this->_resultRow = $resultIdentity;
$this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS;
$this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
return $this->_authenticateCreateAuthResult();
}
/**
* _authenticateCreateAuthResult() - Creates a Zend_Auth_Result object from
* the information that has been collected during the authenticate() attempt.
*
* @return Zend_Auth_Result
*/
protected function _authenticateCreateAuthResult()
{
return new Zend_Auth_Result(
$this->_authenticateResultInfo['code'],
$this->_authenticateResultInfo['identity'],
$this->_authenticateResultInfo['messages']
);
}
}

View file

@ -0,0 +1,230 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Digest.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Auth_Adapter_Interface
*/
require_once 'Zend/Auth/Adapter/Interface.php';
/**
* @category Zend
* @package Zend_Auth
* @subpackage Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_Digest implements Zend_Auth_Adapter_Interface
{
/**
* Filename against which authentication queries are performed
*
* @var string
*/
protected $_filename;
/**
* Digest authentication realm
*
* @var string
*/
protected $_realm;
/**
* Digest authentication user
*
* @var string
*/
protected $_username;
/**
* Password for the user of the realm
*
* @var string
*/
protected $_password;
/**
* Sets adapter options
*
* @param mixed $filename
* @param mixed $realm
* @param mixed $username
* @param mixed $password
* @return void
*/
public function __construct($filename = null, $realm = null, $username = null, $password = null)
{
$options = array('filename', 'realm', 'username', 'password');
foreach ($options as $option) {
if (null !== $$option) {
$methodName = 'set' . ucfirst($option);
$this->$methodName($$option);
}
}
}
/**
* Returns the filename option value or null if it has not yet been set
*
* @return string|null
*/
public function getFilename()
{
return $this->_filename;
}
/**
* Sets the filename option value
*
* @param mixed $filename
* @return Zend_Auth_Adapter_Digest Provides a fluent interface
*/
public function setFilename($filename)
{
$this->_filename = (string) $filename;
return $this;
}
/**
* Returns the realm option value or null if it has not yet been set
*
* @return string|null
*/
public function getRealm()
{
return $this->_realm;
}
/**
* Sets the realm option value
*
* @param mixed $realm
* @return Zend_Auth_Adapter_Digest Provides a fluent interface
*/
public function setRealm($realm)
{
$this->_realm = (string) $realm;
return $this;
}
/**
* Returns the username option value or null if it has not yet been set
*
* @return string|null
*/
public function getUsername()
{
return $this->_username;
}
/**
* Sets the username option value
*
* @param mixed $username
* @return Zend_Auth_Adapter_Digest Provides a fluent interface
*/
public function setUsername($username)
{
$this->_username = (string) $username;
return $this;
}
/**
* Returns the password option value or null if it has not yet been set
*
* @return string|null
*/
public function getPassword()
{
return $this->_password;
}
/**
* Sets the password option value
*
* @param mixed $password
* @return Zend_Auth_Adapter_Digest Provides a fluent interface
*/
public function setPassword($password)
{
$this->_password = (string) $password;
return $this;
}
/**
* Defined by Zend_Auth_Adapter_Interface
*
* @throws Zend_Auth_Adapter_Exception
* @return Zend_Auth_Result
*/
public function authenticate()
{
$optionsRequired = array('filename', 'realm', 'username', 'password');
foreach ($optionsRequired as $optionRequired) {
if (null === $this->{"_$optionRequired"}) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception("Option '$optionRequired' must be set before authentication");
}
}
if (false === ($fileHandle = @fopen($this->_filename, 'r'))) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception("Cannot open '$this->_filename' for reading");
}
$id = "$this->_username:$this->_realm";
$idLength = strlen($id);
$result = array(
'code' => Zend_Auth_Result::FAILURE,
'identity' => array(
'realm' => $this->_realm,
'username' => $this->_username,
),
'messages' => array()
);
while ($line = trim(fgets($fileHandle))) {
if (substr($line, 0, $idLength) === $id) {
if (substr($line, -32) === md5("$this->_username:$this->_realm:$this->_password")) {
$result['code'] = Zend_Auth_Result::SUCCESS;
} else {
$result['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
$result['messages'][] = 'Password incorrect';
}
return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
}
}
$result['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
$result['messages'][] = "Username '$this->_username' and realm '$this->_realm' combination not found";
return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
}
}

View file

@ -0,0 +1,38 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* Zend_Auth_Exception
*/
require_once 'Zend/Auth/Exception.php';
/**
* @category Zend
* @package Zend_Auth
* @subpackage Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_Exception extends Zend_Auth_Exception
{}

View file

@ -0,0 +1,847 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter_Http
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Http.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Auth_Adapter_Interface
*/
require_once 'Zend/Auth/Adapter/Interface.php';
/**
* HTTP Authentication Adapter
*
* Implements a pretty good chunk of RFC 2617.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter_Http
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @todo Support auth-int
* @todo Track nonces, nonce-count, opaque for replay protection and stale support
* @todo Support Authentication-Info header
*/
class Zend_Auth_Adapter_Http implements Zend_Auth_Adapter_Interface
{
/**
* Reference to the HTTP Request object
*
* @var Zend_Controller_Request_Http
*/
protected $_request;
/**
* Reference to the HTTP Response object
*
* @var Zend_Controller_Response_Http
*/
protected $_response;
/**
* Object that looks up user credentials for the Basic scheme
*
* @var Zend_Auth_Adapter_Http_Resolver_Interface
*/
protected $_basicResolver;
/**
* Object that looks up user credentials for the Digest scheme
*
* @var Zend_Auth_Adapter_Http_Resolver_Interface
*/
protected $_digestResolver;
/**
* List of authentication schemes supported by this class
*
* @var array
*/
protected $_supportedSchemes = array('basic', 'digest');
/**
* List of schemes this class will accept from the client
*
* @var array
*/
protected $_acceptSchemes;
/**
* Space-delimited list of protected domains for Digest Auth
*
* @var string
*/
protected $_domains;
/**
* The protection realm to use
*
* @var string
*/
protected $_realm;
/**
* Nonce timeout period
*
* @var integer
*/
protected $_nonceTimeout;
/**
* Whether to send the opaque value in the header. True by default
*
* @var boolean
*/
protected $_useOpaque;
/**
* List of the supported digest algorithms. I want to support both MD5 and
* MD5-sess, but MD5-sess won't make it into the first version.
*
* @var array
*/
protected $_supportedAlgos = array('MD5');
/**
* The actual algorithm to use. Defaults to MD5
*
* @var string
*/
protected $_algo;
/**
* List of supported qop options. My intetion is to support both 'auth' and
* 'auth-int', but 'auth-int' won't make it into the first version.
*
* @var array
*/
protected $_supportedQops = array('auth');
/**
* Whether or not to do Proxy Authentication instead of origin server
* authentication (send 407's instead of 401's). Off by default.
*
* @var boolean
*/
protected $_imaProxy;
/**
* Flag indicating the client is IE and didn't bother to return the opaque string
*
* @var boolean
*/
protected $_ieNoOpaque;
/**
* Constructor
*
* @param array $config Configuration settings:
* 'accept_schemes' => 'basic'|'digest'|'basic digest'
* 'realm' => <string>
* 'digest_domains' => <string> Space-delimited list of URIs
* 'nonce_timeout' => <int>
* 'use_opaque' => <bool> Whether to send the opaque value in the header
* 'alogrithm' => <string> See $_supportedAlgos. Default: MD5
* 'proxy_auth' => <bool> Whether to do authentication as a Proxy
* @throws Zend_Auth_Adapter_Exception
* @return void
*/
public function __construct(array $config)
{
if (!extension_loaded('hash')) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception(__CLASS__ . ' requires the \'hash\' extension');
}
$this->_request = null;
$this->_response = null;
$this->_ieNoOpaque = false;
if (empty($config['accept_schemes'])) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Config key \'accept_schemes\' is required');
}
$schemes = explode(' ', $config['accept_schemes']);
$this->_acceptSchemes = array_intersect($schemes, $this->_supportedSchemes);
if (empty($this->_acceptSchemes)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('No supported schemes given in \'accept_schemes\'. Valid values: '
. implode(', ', $this->_supportedSchemes));
}
// Double-quotes are used to delimit the realm string in the HTTP header,
// and colons are field delimiters in the password file.
if (empty($config['realm']) ||
!ctype_print($config['realm']) ||
strpos($config['realm'], ':') !== false ||
strpos($config['realm'], '"') !== false) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Config key \'realm\' is required, and must contain only printable '
. 'characters, excluding quotation marks and colons');
} else {
$this->_realm = $config['realm'];
}
if (in_array('digest', $this->_acceptSchemes)) {
if (empty($config['digest_domains']) ||
!ctype_print($config['digest_domains']) ||
strpos($config['digest_domains'], '"') !== false) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Config key \'digest_domains\' is required, and must contain '
. 'only printable characters, excluding quotation marks');
} else {
$this->_domains = $config['digest_domains'];
}
if (empty($config['nonce_timeout']) ||
!is_numeric($config['nonce_timeout'])) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Config key \'nonce_timeout\' is required, and must be an '
. 'integer');
} else {
$this->_nonceTimeout = (int) $config['nonce_timeout'];
}
// We use the opaque value unless explicitly told not to
if (isset($config['use_opaque']) && false == (bool) $config['use_opaque']) {
$this->_useOpaque = false;
} else {
$this->_useOpaque = true;
}
if (isset($config['algorithm']) && in_array($config['algorithm'], $this->_supportedAlgos)) {
$this->_algo = $config['algorithm'];
} else {
$this->_algo = 'MD5';
}
}
// Don't be a proxy unless explicitly told to do so
if (isset($config['proxy_auth']) && true == (bool) $config['proxy_auth']) {
$this->_imaProxy = true; // I'm a Proxy
} else {
$this->_imaProxy = false;
}
}
/**
* Setter for the _basicResolver property
*
* @param Zend_Auth_Adapter_Http_Resolver_Interface $resolver
* @return Zend_Auth_Adapter_Http Provides a fluent interface
*/
public function setBasicResolver(Zend_Auth_Adapter_Http_Resolver_Interface $resolver)
{
$this->_basicResolver = $resolver;
return $this;
}
/**
* Getter for the _basicResolver property
*
* @return Zend_Auth_Adapter_Http_Resolver_Interface
*/
public function getBasicResolver()
{
return $this->_basicResolver;
}
/**
* Setter for the _digestResolver property
*
* @param Zend_Auth_Adapter_Http_Resolver_Interface $resolver
* @return Zend_Auth_Adapter_Http Provides a fluent interface
*/
public function setDigestResolver(Zend_Auth_Adapter_Http_Resolver_Interface $resolver)
{
$this->_digestResolver = $resolver;
return $this;
}
/**
* Getter for the _digestResolver property
*
* @return Zend_Auth_Adapter_Http_Resolver_Interface
*/
public function getDigestResolver()
{
return $this->_digestResolver;
}
/**
* Setter for the Request object
*
* @param Zend_Controller_Request_Http $request
* @return Zend_Auth_Adapter_Http Provides a fluent interface
*/
public function setRequest(Zend_Controller_Request_Http $request)
{
$this->_request = $request;
return $this;
}
/**
* Getter for the Request object
*
* @return Zend_Controller_Request_Http
*/
public function getRequest()
{
return $this->_request;
}
/**
* Setter for the Response object
*
* @param Zend_Controller_Response_Http $response
* @return Zend_Auth_Adapter_Http Provides a fluent interface
*/
public function setResponse(Zend_Controller_Response_Http $response)
{
$this->_response = $response;
return $this;
}
/**
* Getter for the Response object
*
* @return Zend_Controller_Response_Http
*/
public function getResponse()
{
return $this->_response;
}
/**
* Authenticate
*
* @throws Zend_Auth_Adapter_Exception
* @return Zend_Auth_Result
*/
public function authenticate()
{
if (empty($this->_request) ||
empty($this->_response)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling '
. 'authenticate()');
}
if ($this->_imaProxy) {
$getHeader = 'Proxy-Authorization';
} else {
$getHeader = 'Authorization';
}
$authHeader = $this->_request->getHeader($getHeader);
if (!$authHeader) {
return $this->_challengeClient();
}
list($clientScheme) = explode(' ', $authHeader);
$clientScheme = strtolower($clientScheme);
// The server can issue multiple challenges, but the client should
// answer with only the selected auth scheme.
if (!in_array($clientScheme, $this->_supportedSchemes)) {
$this->_response->setHttpResponseCode(400);
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_UNCATEGORIZED,
array(),
array('Client requested an incorrect or unsupported authentication scheme')
);
}
// client sent a scheme that is not the one required
if (!in_array($clientScheme, $this->_acceptSchemes)) {
// challenge again the client
return $this->_challengeClient();
}
switch ($clientScheme) {
case 'basic':
$result = $this->_basicAuth($authHeader);
break;
case 'digest':
$result = $this->_digestAuth($authHeader);
break;
default:
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Unsupported authentication scheme');
}
return $result;
}
/**
* Challenge Client
*
* Sets a 401 or 407 Unauthorized response code, and creates the
* appropriate Authenticate header(s) to prompt for credentials.
*
* @return Zend_Auth_Result Always returns a non-identity Auth result
*/
protected function _challengeClient()
{
if ($this->_imaProxy) {
$statusCode = 407;
$headerName = 'Proxy-Authenticate';
} else {
$statusCode = 401;
$headerName = 'WWW-Authenticate';
}
$this->_response->setHttpResponseCode($statusCode);
// Send a challenge in each acceptable authentication scheme
if (in_array('basic', $this->_acceptSchemes)) {
$this->_response->setHeader($headerName, $this->_basicHeader());
}
if (in_array('digest', $this->_acceptSchemes)) {
$this->_response->setHeader($headerName, $this->_digestHeader());
}
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
array(),
array('Invalid or absent credentials; challenging client')
);
}
/**
* Basic Header
*
* Generates a Proxy- or WWW-Authenticate header value in the Basic
* authentication scheme.
*
* @return string Authenticate header value
*/
protected function _basicHeader()
{
return 'Basic realm="' . $this->_realm . '"';
}
/**
* Digest Header
*
* Generates a Proxy- or WWW-Authenticate header value in the Digest
* authentication scheme.
*
* @return string Authenticate header value
*/
protected function _digestHeader()
{
$wwwauth = 'Digest realm="' . $this->_realm . '", '
. 'domain="' . $this->_domains . '", '
. 'nonce="' . $this->_calcNonce() . '", '
. ($this->_useOpaque ? 'opaque="' . $this->_calcOpaque() . '", ' : '')
. 'algorithm="' . $this->_algo . '", '
. 'qop="' . implode(',', $this->_supportedQops) . '"';
return $wwwauth;
}
/**
* Basic Authentication
*
* @param string $header Client's Authorization header
* @throws Zend_Auth_Adapter_Exception
* @return Zend_Auth_Result
*/
protected function _basicAuth($header)
{
if (empty($header)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required');
}
if (empty($this->_basicResolver)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('A basicResolver object must be set before doing Basic '
. 'authentication');
}
// Decode the Authorization header
$auth = substr($header, strlen('Basic '));
$auth = base64_decode($auth);
if (!$auth) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Unable to base64_decode Authorization header value');
}
// See ZF-1253. Validate the credentials the same way the digest
// implementation does. If invalid credentials are detected,
// re-challenge the client.
if (!ctype_print($auth)) {
return $this->_challengeClient();
}
// Fix for ZF-1515: Now re-challenges on empty username or password
$creds = array_filter(explode(':', $auth));
if (count($creds) != 2) {
return $this->_challengeClient();
}
$password = $this->_basicResolver->resolve($creds[0], $this->_realm);
if ($password && $password == $creds[1]) {
$identity = array('username'=>$creds[0], 'realm'=>$this->_realm);
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
} else {
return $this->_challengeClient();
}
}
/**
* Digest Authentication
*
* @param string $header Client's Authorization header
* @throws Zend_Auth_Adapter_Exception
* @return Zend_Auth_Result Valid auth result only on successful auth
*/
protected function _digestAuth($header)
{
if (empty($header)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required');
}
if (empty($this->_digestResolver)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('A digestResolver object must be set before doing Digest authentication');
}
$data = $this->_parseDigestAuth($header);
if ($data === false) {
$this->_response->setHttpResponseCode(400);
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_UNCATEGORIZED,
array(),
array('Invalid Authorization header format')
);
}
// See ZF-1052. This code was a bit too unforgiving of invalid
// usernames. Now, if the username is bad, we re-challenge the client.
if ('::invalid::' == $data['username']) {
return $this->_challengeClient();
}
// Verify that the client sent back the same nonce
if ($this->_calcNonce() != $data['nonce']) {
return $this->_challengeClient();
}
// The opaque value is also required to match, but of course IE doesn't
// play ball.
if (!$this->_ieNoOpaque && $this->_calcOpaque() != $data['opaque']) {
return $this->_challengeClient();
}
// Look up the user's password hash. If not found, deny access.
// This makes no assumptions about how the password hash was
// constructed beyond that it must have been built in such a way as
// to be recreatable with the current settings of this object.
$ha1 = $this->_digestResolver->resolve($data['username'], $data['realm']);
if ($ha1 === false) {
return $this->_challengeClient();
}
// If MD5-sess is used, a1 value is made of the user's password
// hash with the server and client nonce appended, separated by
// colons.
if ($this->_algo == 'MD5-sess') {
$ha1 = hash('md5', $ha1 . ':' . $data['nonce'] . ':' . $data['cnonce']);
}
// Calculate h(a2). The value of this hash depends on the qop
// option selected by the client and the supported hash functions
switch ($data['qop']) {
case 'auth':
$a2 = $this->_request->getMethod() . ':' . $data['uri'];
break;
case 'auth-int':
// Should be REQUEST_METHOD . ':' . uri . ':' . hash(entity-body),
// but this isn't supported yet, so fall through to default case
default:
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Client requested an unsupported qop option');
}
// Using hash() should make parameterizing the hash algorithm
// easier
$ha2 = hash('md5', $a2);
// Calculate the server's version of the request-digest. This must
// match $data['response']. See RFC 2617, section 3.2.2.1
$message = $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $ha2;
$digest = hash('md5', $ha1 . ':' . $message);
// If our digest matches the client's let them in, otherwise return
// a 401 code and exit to prevent access to the protected resource.
if ($digest == $data['response']) {
$identity = array('username'=>$data['username'], 'realm'=>$data['realm']);
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
} else {
return $this->_challengeClient();
}
}
/**
* Calculate Nonce
*
* @return string The nonce value
*/
protected function _calcNonce()
{
// Once subtle consequence of this timeout calculation is that it
// actually divides all of time into _nonceTimeout-sized sections, such
// that the value of timeout is the point in time of the next
// approaching "boundary" of a section. This allows the server to
// consistently generate the same timeout (and hence the same nonce
// value) across requests, but only as long as one of those
// "boundaries" is not crossed between requests. If that happens, the
// nonce will change on its own, and effectively log the user out. This
// would be surprising if the user just logged in.
$timeout = ceil(time() / $this->_nonceTimeout) * $this->_nonceTimeout;
$nonce = hash('md5', $timeout . ':' . $this->_request->getServer('HTTP_USER_AGENT') . ':' . __CLASS__);
return $nonce;
}
/**
* Calculate Opaque
*
* The opaque string can be anything; the client must return it exactly as
* it was sent. It may be useful to store data in this string in some
* applications. Ideally, a new value for this would be generated each time
* a WWW-Authenticate header is sent (in order to reduce predictability),
* but we would have to be able to create the same exact value across at
* least two separate requests from the same client.
*
* @return string The opaque value
*/
protected function _calcOpaque()
{
return hash('md5', 'Opaque Data:' . __CLASS__);
}
/**
* Parse Digest Authorization header
*
* @param string $header Client's Authorization: HTTP header
* @return array|false Data elements from header, or false if any part of
* the header is invalid
*/
protected function _parseDigestAuth($header)
{
$temp = null;
$data = array();
// See ZF-1052. Detect invalid usernames instead of just returning a
// 400 code.
$ret = preg_match('/username="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])
|| !ctype_print($temp[1])
|| strpos($temp[1], ':') !== false) {
$data['username'] = '::invalid::';
} else {
$data['username'] = $temp[1];
}
$temp = null;
$ret = preg_match('/realm="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (!ctype_print($temp[1]) || strpos($temp[1], ':') !== false) {
return false;
} else {
$data['realm'] = $temp[1];
}
$temp = null;
$ret = preg_match('/nonce="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (!ctype_xdigit($temp[1])) {
return false;
} else {
$data['nonce'] = $temp[1];
}
$temp = null;
$ret = preg_match('/uri="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
// Section 3.2.2.5 in RFC 2617 says the authenticating server must
// verify that the URI field in the Authorization header is for the
// same resource requested in the Request Line.
$rUri = @parse_url($this->_request->getRequestUri());
$cUri = @parse_url($temp[1]);
if (false === $rUri || false === $cUri) {
return false;
} else {
// Make sure the path portion of both URIs is the same
if ($rUri['path'] != $cUri['path']) {
return false;
}
// Section 3.2.2.5 seems to suggest that the value of the URI
// Authorization field should be made into an absolute URI if the
// Request URI is absolute, but it's vague, and that's a bunch of
// code I don't want to write right now.
$data['uri'] = $temp[1];
}
$temp = null;
$ret = preg_match('/response="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (32 != strlen($temp[1]) || !ctype_xdigit($temp[1])) {
return false;
} else {
$data['response'] = $temp[1];
}
$temp = null;
// The spec says this should default to MD5 if omitted. OK, so how does
// that square with the algo we send out in the WWW-Authenticate header,
// if it can easily be overridden by the client?
$ret = preg_match('/algorithm="?(' . $this->_algo . ')"?/', $header, $temp);
if ($ret && !empty($temp[1])
&& in_array($temp[1], $this->_supportedAlgos)) {
$data['algorithm'] = $temp[1];
} else {
$data['algorithm'] = 'MD5'; // = $this->_algo; ?
}
$temp = null;
// Not optional in this implementation
$ret = preg_match('/cnonce="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (!ctype_print($temp[1])) {
return false;
} else {
$data['cnonce'] = $temp[1];
}
$temp = null;
// If the server sent an opaque value, the client must send it back
if ($this->_useOpaque) {
$ret = preg_match('/opaque="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
// Big surprise: IE isn't RFC 2617-compliant.
if (false !== strpos($this->_request->getHeader('User-Agent'), 'MSIE')) {
$temp[1] = '';
$this->_ieNoOpaque = true;
} else {
return false;
}
}
// This implementation only sends MD5 hex strings in the opaque value
if (!$this->_ieNoOpaque &&
(32 != strlen($temp[1]) || !ctype_xdigit($temp[1]))) {
return false;
} else {
$data['opaque'] = $temp[1];
}
$temp = null;
}
// Not optional in this implementation, but must be one of the supported
// qop types
$ret = preg_match('/qop="?(' . implode('|', $this->_supportedQops) . ')"?/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (!in_array($temp[1], $this->_supportedQops)) {
return false;
} else {
$data['qop'] = $temp[1];
}
$temp = null;
// Not optional in this implementation. The spec says this value
// shouldn't be a quoted string, but apparently some implementations
// quote it anyway. See ZF-1544.
$ret = preg_match('/nc="?([0-9A-Fa-f]{8})"?/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (8 != strlen($temp[1]) || !ctype_xdigit($temp[1])) {
return false;
} else {
$data['nc'] = $temp[1];
}
$temp = null;
return $data;
}
}

View file

@ -0,0 +1,40 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter_Http
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Auth_Exception
*/
require_once 'Zend/Auth/Exception.php';
/**
* HTTP Auth Resolver Exception
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter_Http
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_Http_Resolver_Exception extends Zend_Auth_Exception
{}

View file

@ -0,0 +1,167 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter_Http
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: File.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Auth_Adapter_Http_Resolver_Interface
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Interface.php';
/**
* HTTP Authentication File Resolver
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter_Http
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_Http_Resolver_File implements Zend_Auth_Adapter_Http_Resolver_Interface
{
/**
* Path to credentials file
*
* @var string
*/
protected $_file;
/**
* Constructor
*
* @param string $path Complete filename where the credentials are stored
* @return void
*/
public function __construct($path = '')
{
if (!empty($path)) {
$this->setFile($path);
}
}
/**
* Set the path to the credentials file
*
* @param string $path
* @throws Zend_Auth_Adapter_Http_Resolver_Exception
* @return Zend_Auth_Adapter_Http_Resolver_File Provides a fluent interface
*/
public function setFile($path)
{
if (empty($path) || !is_readable($path)) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Path not readable: ' . $path);
}
$this->_file = $path;
return $this;
}
/**
* Returns the path to the credentials file
*
* @return string
*/
public function getFile()
{
return $this->_file;
}
/**
* Resolve credentials
*
* Only the first matching username/realm combination in the file is
* returned. If the file contains credentials for Digest authentication,
* the returned string is the password hash, or h(a1) from RFC 2617. The
* returned string is the plain-text password for Basic authentication.
*
* The expected format of the file is:
* username:realm:sharedSecret
*
* That is, each line consists of the user's username, the applicable
* authentication realm, and the password or hash, each delimited by
* colons.
*
* @param string $username Username
* @param string $realm Authentication Realm
* @throws Zend_Auth_Adapter_Http_Resolver_Exception
* @return string|false User's shared secret, if the user is found in the
* realm, false otherwise.
*/
public function resolve($username, $realm)
{
if (empty($username)) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username is required');
} else if (!ctype_print($username) || strpos($username, ':') !== false) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username must consist only of printable characters, '
. 'excluding the colon');
}
if (empty($realm)) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm is required');
} else if (!ctype_print($realm) || strpos($realm, ':') !== false) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm must consist only of printable characters, '
. 'excluding the colon.');
}
// Open file, read through looking for matching credentials
$fp = @fopen($this->_file, 'r');
if (!$fp) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Unable to open password file: ' . $this->_file);
}
// No real validation is done on the contents of the password file. The
// assumption is that we trust the administrators to keep it secure.
while (($line = fgetcsv($fp, 512, ':')) !== false) {
if ($line[0] == $username && $line[1] == $realm) {
$password = $line[2];
fclose($fp);
return $password;
}
}
fclose($fp);
return false;
}
}

View file

@ -0,0 +1,47 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter_Http
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Interface.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* Auth HTTP Resolver Interface
*
* Defines an interace to resolve a username/realm combination into a shared
* secret usable by HTTP Authentication.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter_Http
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Auth_Adapter_Http_Resolver_Interface
{
/**
* Resolve username/realm to password/hash/etc.
*
* @param string $username Username
* @param string $realm Authentication Realm
* @return string|false User's shared secret, if the user is found in the
* realm, false otherwise.
*/
public function resolve($username, $realm);
}

View file

@ -0,0 +1,261 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: InfoCard.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Auth_Adapter_Interface
*/
require_once 'Zend/Auth/Adapter/Interface.php';
/**
* @see Zend_Auth_Result
*/
require_once 'Zend/Auth/Result.php';
/**
* @see Zend_InfoCard
*/
require_once 'Zend/InfoCard.php';
/**
* A Zend_Auth Authentication Adapter allowing the use of Information Cards as an
* authentication mechanism
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_InfoCard implements Zend_Auth_Adapter_Interface
{
/**
* The XML Token being authenticated
*
* @var string
*/
protected $_xmlToken;
/**
* The instance of Zend_InfoCard
*
* @var Zend_InfoCard
*/
protected $_infoCard;
/**
* Constructor
*
* @param string $strXmlDocument The XML Token provided by the client
* @return void
*/
public function __construct($strXmlDocument)
{
$this->_xmlToken = $strXmlDocument;
$this->_infoCard = new Zend_InfoCard();
}
/**
* Sets the InfoCard component Adapter to use
*
* @param Zend_InfoCard_Adapter_Interface $a
* @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
*/
public function setAdapter(Zend_InfoCard_Adapter_Interface $a)
{
$this->_infoCard->setAdapter($a);
return $this;
}
/**
* Retrieves the InfoCard component adapter being used
*
* @return Zend_InfoCard_Adapter_Interface
*/
public function getAdapter()
{
return $this->_infoCard->getAdapter();
}
/**
* Retrieves the InfoCard public key cipher object being used
*
* @return Zend_InfoCard_Cipher_PKI_Interface
*/
public function getPKCipherObject()
{
return $this->_infoCard->getPKCipherObject();
}
/**
* Sets the InfoCard public key cipher object to use
*
* @param Zend_InfoCard_Cipher_PKI_Interface $cipherObj
* @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
*/
public function setPKICipherObject(Zend_InfoCard_Cipher_PKI_Interface $cipherObj)
{
$this->_infoCard->setPKICipherObject($cipherObj);
return $this;
}
/**
* Retrieves the Symmetric cipher object being used
*
* @return Zend_InfoCard_Cipher_Symmetric_Interface
*/
public function getSymCipherObject()
{
return $this->_infoCard->getSymCipherObject();
}
/**
* Sets the InfoCard symmetric cipher object to use
*
* @param Zend_InfoCard_Cipher_Symmetric_Interface $cipherObj
* @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
*/
public function setSymCipherObject(Zend_InfoCard_Cipher_Symmetric_Interface $cipherObj)
{
$this->_infoCard->setSymCipherObject($cipherObj);
return $this;
}
/**
* Remove a Certificate Pair by Key ID from the search list
*
* @param string $key_id The Certificate Key ID returned from adding the certificate pair
* @throws Zend_InfoCard_Exception
* @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
*/
public function removeCertificatePair($key_id)
{
$this->_infoCard->removeCertificatePair($key_id);
return $this;
}
/**
* Add a Certificate Pair to the list of certificates searched by the component
*
* @param string $private_key_file The path to the private key file for the pair
* @param string $public_key_file The path to the certificate / public key for the pair
* @param string $type (optional) The URI for the type of key pair this is (default RSA with OAEP padding)
* @param string $password (optional) The password for the private key file if necessary
* @throws Zend_InfoCard_Exception
* @return string A key ID representing this key pair in the component
*/
public function addCertificatePair($private_key_file, $public_key_file, $type = Zend_InfoCard_Cipher::ENC_RSA_OAEP_MGF1P, $password = null)
{
return $this->_infoCard->addCertificatePair($private_key_file, $public_key_file, $type, $password);
}
/**
* Return a Certificate Pair from a key ID
*
* @param string $key_id The Key ID of the certificate pair in the component
* @throws Zend_InfoCard_Exception
* @return array An array containing the path to the private/public key files,
* the type URI and the password if provided
*/
public function getCertificatePair($key_id)
{
return $this->_infoCard->getCertificatePair($key_id);
}
/**
* Set the XML Token to be processed
*
* @param string $strXmlToken The XML token to process
* @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
*/
public function setXmlToken($strXmlToken)
{
$this->_xmlToken = $strXmlToken;
return $this;
}
/**
* Get the XML Token being processed
*
* @return string The XML token to be processed
*/
public function getXmlToken()
{
return $this->_xmlToken;
}
/**
* Authenticates the XML token
*
* @return Zend_Auth_Result The result of the authentication
*/
public function authenticate()
{
try {
$claims = $this->_infoCard->process($this->getXmlToken());
} catch(Exception $e) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE , null, array('Exception Thrown',
$e->getMessage(),
$e->getTraceAsString(),
serialize($e)));
}
if(!$claims->isValid()) {
switch($claims->getCode()) {
case Zend_infoCard_Claims::RESULT_PROCESSING_FAILURE:
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$claims,
array(
'Processing Failure',
$claims->getErrorMsg()
)
);
break;
case Zend_InfoCard_Claims::RESULT_VALIDATION_FAILURE:
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
$claims,
array(
'Validation Failure',
$claims->getErrorMsg()
)
);
break;
default:
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$claims,
array(
'Unknown Failure',
$claims->getErrorMsg()
)
);
break;
}
}
return new Zend_Auth_Result(
Zend_Auth_Result::SUCCESS,
$claims
);
}
}

View file

@ -0,0 +1,46 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Interface.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Auth_Result
*/
require_once 'Zend/Auth/Result.php';
/**
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Auth_Adapter_Interface
{
/**
* Performs an authentication attempt
*
* @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
* @return Zend_Auth_Result
*/
public function authenticate();
}

View file

@ -0,0 +1,526 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Ldap.php 21320 2010-03-04 16:05:09Z sgehrig $
*/
/**
* @see Zend_Auth_Adapter_Interface
*/
require_once 'Zend/Auth/Adapter/Interface.php';
/**
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_Ldap implements Zend_Auth_Adapter_Interface
{
/**
* The Zend_Ldap context.
*
* @var Zend_Ldap
*/
protected $_ldap = null;
/**
* The array of arrays of Zend_Ldap options passed to the constructor.
*
* @var array
*/
protected $_options = null;
/**
* The username of the account being authenticated.
*
* @var string
*/
protected $_username = null;
/**
* The password of the account being authenticated.
*
* @var string
*/
protected $_password = null;
/**
* The DN of the authenticated account. Used to retrieve the account entry on request.
*
* @var string
*/
protected $_authenticatedDn = null;
/**
* Constructor
*
* @param array $options An array of arrays of Zend_Ldap options
* @param string $username The username of the account being authenticated
* @param string $password The password of the account being authenticated
* @return void
*/
public function __construct(array $options = array(), $username = null, $password = null)
{
$this->setOptions($options);
if ($username !== null) {
$this->setUsername($username);
}
if ($password !== null) {
$this->setPassword($password);
}
}
/**
* Returns the array of arrays of Zend_Ldap options of this adapter.
*
* @return array|null
*/
public function getOptions()
{
return $this->_options;
}
/**
* Sets the array of arrays of Zend_Ldap options to be used by
* this adapter.
*
* @param array $options The array of arrays of Zend_Ldap options
* @return Zend_Auth_Adapter_Ldap Provides a fluent interface
*/
public function setOptions($options)
{
$this->_options = is_array($options) ? $options : array();
return $this;
}
/**
* Returns the username of the account being authenticated, or
* NULL if none is set.
*
* @return string|null
*/
public function getUsername()
{
return $this->_username;
}
/**
* Sets the username for binding
*
* @param string $username The username for binding
* @return Zend_Auth_Adapter_Ldap Provides a fluent interface
*/
public function setUsername($username)
{
$this->_username = (string) $username;
return $this;
}
/**
* Returns the password of the account being authenticated, or
* NULL if none is set.
*
* @return string|null
*/
public function getPassword()
{
return $this->_password;
}
/**
* Sets the passwort for the account
*
* @param string $password The password of the account being authenticated
* @return Zend_Auth_Adapter_Ldap Provides a fluent interface
*/
public function setPassword($password)
{
$this->_password = (string) $password;
return $this;
}
/**
* setIdentity() - set the identity (username) to be used
*
* Proxies to {@see setUsername()}
*
* Closes ZF-6813
*
* @param string $identity
* @return Zend_Auth_Adapter_Ldap Provides a fluent interface
*/
public function setIdentity($identity)
{
return $this->setUsername($identity);
}
/**
* setCredential() - set the credential (password) value to be used
*
* Proxies to {@see setPassword()}
*
* Closes ZF-6813
*
* @param string $credential
* @return Zend_Auth_Adapter_Ldap Provides a fluent interface
*/
public function setCredential($credential)
{
return $this->setPassword($credential);
}
/**
* Returns the LDAP Object
*
* @return Zend_Ldap The Zend_Ldap object used to authenticate the credentials
*/
public function getLdap()
{
if ($this->_ldap === null) {
/**
* @see Zend_Ldap
*/
require_once 'Zend/Ldap.php';
$this->_ldap = new Zend_Ldap();
}
return $this->_ldap;
}
/**
* Set an Ldap connection
*
* @param Zend_Ldap $ldap An existing Ldap object
* @return Zend_Auth_Adapter_Ldap Provides a fluent interface
*/
public function setLdap(Zend_Ldap $ldap)
{
$this->_ldap = $ldap;
$this->setOptions(array($ldap->getOptions()));
return $this;
}
/**
* Returns a domain name for the current LDAP options. This is used
* for skipping redundant operations (e.g. authentications).
*
* @return string
*/
protected function _getAuthorityName()
{
$options = $this->getLdap()->getOptions();
$name = $options['accountDomainName'];
if (!$name)
$name = $options['accountDomainNameShort'];
return $name ? $name : '';
}
/**
* Authenticate the user
*
* @throws Zend_Auth_Adapter_Exception
* @return Zend_Auth_Result
*/
public function authenticate()
{
/**
* @see Zend_Ldap_Exception
*/
require_once 'Zend/Ldap/Exception.php';
$messages = array();
$messages[0] = ''; // reserved
$messages[1] = ''; // reserved
$username = $this->_username;
$password = $this->_password;
if (!$username) {
$code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
$messages[0] = 'A username is required';
return new Zend_Auth_Result($code, '', $messages);
}
if (!$password) {
/* A password is required because some servers will
* treat an empty password as an anonymous bind.
*/
$code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
$messages[0] = 'A password is required';
return new Zend_Auth_Result($code, '', $messages);
}
$ldap = $this->getLdap();
$code = Zend_Auth_Result::FAILURE;
$messages[0] = "Authority not found: $username";
$failedAuthorities = array();
/* Iterate through each server and try to authenticate the supplied
* credentials against it.
*/
foreach ($this->_options as $name => $options) {
if (!is_array($options)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Adapter options array not an array');
}
$adapterOptions = $this->_prepareOptions($ldap, $options);
$dname = '';
try {
if ($messages[1])
$messages[] = $messages[1];
$messages[1] = '';
$messages[] = $this->_optionsToString($options);
$dname = $this->_getAuthorityName();
if (isset($failedAuthorities[$dname])) {
/* If multiple sets of server options for the same domain
* are supplied, we want to skip redundant authentications
* where the identity or credentials where found to be
* invalid with another server for the same domain. The
* $failedAuthorities array tracks this condition (and also
* serves to supply the original error message).
* This fixes issue ZF-4093.
*/
$messages[1] = $failedAuthorities[$dname];
$messages[] = "Skipping previously failed authority: $dname";
continue;
}
$canonicalName = $ldap->getCanonicalAccountName($username);
$ldap->bind($canonicalName, $password);
/*
* Fixes problem when authenticated user is not allowed to retrieve
* group-membership information or own account.
* This requires that the user specified with "username" and optionally
* "password" in the Zend_Ldap options is able to retrieve the required
* information.
*/
$requireRebind = false;
if (isset($options['username'])) {
$ldap->bind();
$requireRebind = true;
}
$dn = $ldap->getCanonicalAccountName($canonicalName, Zend_Ldap::ACCTNAME_FORM_DN);
$groupResult = $this->_checkGroupMembership($ldap, $canonicalName, $dn, $adapterOptions);
if ($groupResult === true) {
$this->_authenticatedDn = $dn;
$messages[0] = '';
$messages[1] = '';
$messages[] = "$canonicalName authentication successful";
if ($requireRebind === true) {
// rebinding with authenticated user
$ldap->bind($dn, $password);
}
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $canonicalName, $messages);
} else {
$messages[0] = 'Account is not a member of the specified group';
$messages[1] = $groupResult;
$failedAuthorities[$dname] = $groupResult;
}
} catch (Zend_Ldap_Exception $zle) {
/* LDAP based authentication is notoriously difficult to diagnose. Therefore
* we bend over backwards to capture and record every possible bit of
* information when something goes wrong.
*/
$err = $zle->getCode();
if ($err == Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH) {
/* This error indicates that the domain supplied in the
* username did not match the domains in the server options
* and therefore we should just skip to the next set of
* server options.
*/
continue;
} else if ($err == Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) {
$code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
$messages[0] = "Account not found: $username";
$failedAuthorities[$dname] = $zle->getMessage();
} else if ($err == Zend_Ldap_Exception::LDAP_INVALID_CREDENTIALS) {
$code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
$messages[0] = 'Invalid credentials';
$failedAuthorities[$dname] = $zle->getMessage();
} else {
$line = $zle->getLine();
$messages[] = $zle->getFile() . "($line): " . $zle->getMessage();
$messages[] = str_replace($password, '*****', $zle->getTraceAsString());
$messages[0] = 'An unexpected failure occurred';
}
$messages[1] = $zle->getMessage();
}
}
$msg = isset($messages[1]) ? $messages[1] : $messages[0];
$messages[] = "$username authentication failed: $msg";
return new Zend_Auth_Result($code, $username, $messages);
}
/**
* Sets the LDAP specific options on the Zend_Ldap instance
*
* @param Zend_Ldap $ldap
* @param array $options
* @return array of auth-adapter specific options
*/
protected function _prepareOptions(Zend_Ldap $ldap, array $options)
{
$adapterOptions = array(
'group' => null,
'groupDn' => $ldap->getBaseDn(),
'groupScope' => Zend_Ldap::SEARCH_SCOPE_SUB,
'groupAttr' => 'cn',
'groupFilter' => 'objectClass=groupOfUniqueNames',
'memberAttr' => 'uniqueMember',
'memberIsDn' => true
);
foreach ($adapterOptions as $key => $value) {
if (array_key_exists($key, $options)) {
$value = $options[$key];
unset($options[$key]);
switch ($key) {
case 'groupScope':
$value = (int)$value;
if (in_array($value, array(Zend_Ldap::SEARCH_SCOPE_BASE,
Zend_Ldap::SEARCH_SCOPE_ONE, Zend_Ldap::SEARCH_SCOPE_SUB), true)) {
$adapterOptions[$key] = $value;
}
break;
case 'memberIsDn':
$adapterOptions[$key] = ($value === true ||
$value === '1' || strcasecmp($value, 'true') == 0);
break;
default:
$adapterOptions[$key] = trim($value);
break;
}
}
}
$ldap->setOptions($options);
return $adapterOptions;
}
/**
* Checks the group membership of the bound user
*
* @param Zend_Ldap $ldap
* @param string $canonicalName
* @param string $dn
* @param array $adapterOptions
* @return string|true
*/
protected function _checkGroupMembership(Zend_Ldap $ldap, $canonicalName, $dn, array $adapterOptions)
{
if ($adapterOptions['group'] === null) {
return true;
}
if ($adapterOptions['memberIsDn'] === false) {
$user = $canonicalName;
} else {
$user = $dn;
}
/**
* @see Zend_Ldap_Filter
*/
require_once 'Zend/Ldap/Filter.php';
$groupName = Zend_Ldap_Filter::equals($adapterOptions['groupAttr'], $adapterOptions['group']);
$membership = Zend_Ldap_Filter::equals($adapterOptions['memberAttr'], $user);
$group = Zend_Ldap_Filter::andFilter($groupName, $membership);
$groupFilter = $adapterOptions['groupFilter'];
if (!empty($groupFilter)) {
$group = $group->addAnd($groupFilter);
}
$result = $ldap->count($group, $adapterOptions['groupDn'], $adapterOptions['groupScope']);
if ($result === 1) {
return true;
} else {
return 'Failed to verify group membership with ' . $group->toString();
}
}
/**
* getAccountObject() - Returns the result entry as a stdClass object
*
* This resembles the feature {@see Zend_Auth_Adapter_DbTable::getResultRowObject()}.
* Closes ZF-6813
*
* @param array $returnAttribs
* @param array $omitAttribs
* @return stdClass|boolean
*/
public function getAccountObject(array $returnAttribs = array(), array $omitAttribs = array())
{
if (!$this->_authenticatedDn) {
return false;
}
$returnObject = new stdClass();
$omitAttribs = array_map('strtolower', $omitAttribs);
$entry = $this->getLdap()->getEntry($this->_authenticatedDn, $returnAttribs, true);
foreach ($entry as $attr => $value) {
if (in_array($attr, $omitAttribs)) {
// skip attributes marked to be omitted
continue;
}
if (is_array($value)) {
$returnObject->$attr = (count($value) > 1) ? $value : $value[0];
} else {
$returnObject->$attr = $value;
}
}
return $returnObject;
}
/**
* Converts options to string
*
* @param array $options
* @return string
*/
private function _optionsToString(array $options)
{
$str = '';
foreach ($options as $key => $val) {
if ($key === 'password')
$val = '*****';
if ($str)
$str .= ',';
$str .= $key . '=' . $val;
}
return $str;
}
}

View file

@ -0,0 +1,284 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: OpenId.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Auth_Adapter_Interface
*/
require_once 'Zend/Auth/Adapter/Interface.php';
/**
* @see Zend_OpenId_Consumer
*/
require_once 'Zend/OpenId/Consumer.php';
/**
* A Zend_Auth Authentication Adapter allowing the use of OpenID protocol as an
* authentication mechanism
*
* @category Zend
* @package Zend_Auth
* @subpackage Zend_Auth_Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_OpenId implements Zend_Auth_Adapter_Interface
{
/**
* The identity value being authenticated
*
* @var string
*/
private $_id = null;
/**
* Reference to an implementation of a storage object
*
* @var Zend_OpenId_Consumer_Storage
*/
private $_storage = null;
/**
* The URL to redirect response from server to
*
* @var string
*/
private $_returnTo = null;
/**
* The HTTP URL to identify consumer on server
*
* @var string
*/
private $_root = null;
/**
* Extension object or array of extensions objects
*
* @var string
*/
private $_extensions = null;
/**
* The response object to perform HTTP or HTML form redirection
*
* @var Zend_Controller_Response_Abstract
*/
private $_response = null;
/**
* Enables or disables interaction with user during authentication on
* OpenID provider.
*
* @var bool
*/
private $_check_immediate = false;
/**
* HTTP client to make HTTP requests
*
* @var Zend_Http_Client $_httpClient
*/
private $_httpClient = null;
/**
* Constructor
*
* @param string $id the identity value
* @param Zend_OpenId_Consumer_Storage $storage an optional implementation
* of a storage object
* @param string $returnTo HTTP URL to redirect response from server to
* @param string $root HTTP URL to identify consumer on server
* @param mixed $extensions extension object or array of extensions objects
* @param Zend_Controller_Response_Abstract $response an optional response
* object to perform HTTP or HTML form redirection
* @return void
*/
public function __construct($id = null,
Zend_OpenId_Consumer_Storage $storage = null,
$returnTo = null,
$root = null,
$extensions = null,
Zend_Controller_Response_Abstract $response = null) {
$this->_id = $id;
$this->_storage = $storage;
$this->_returnTo = $returnTo;
$this->_root = $root;
$this->_extensions = $extensions;
$this->_response = $response;
}
/**
* Sets the value to be used as the identity
*
* @param string $id the identity value
* @return Zend_Auth_Adapter_OpenId Provides a fluent interface
*/
public function setIdentity($id)
{
$this->_id = $id;
return $this;
}
/**
* Sets the storage implementation which will be use by OpenId
*
* @param Zend_OpenId_Consumer_Storage $storage
* @return Zend_Auth_Adapter_OpenId Provides a fluent interface
*/
public function setStorage(Zend_OpenId_Consumer_Storage $storage)
{
$this->_storage = $storage;
return $this;
}
/**
* Sets the HTTP URL to redirect response from server to
*
* @param string $returnTo
* @return Zend_Auth_Adapter_OpenId Provides a fluent interface
*/
public function setReturnTo($returnTo)
{
$this->_returnTo = $returnTo;
return $this;
}
/**
* Sets HTTP URL to identify consumer on server
*
* @param string $root
* @return Zend_Auth_Adapter_OpenId Provides a fluent interface
*/
public function setRoot($root)
{
$this->_root = $root;
return $this;
}
/**
* Sets OpenID extension(s)
*
* @param mixed $extensions
* @return Zend_Auth_Adapter_OpenId Provides a fluent interface
*/
public function setExtensions($extensions)
{
$this->_extensions = $extensions;
return $this;
}
/**
* Sets an optional response object to perform HTTP or HTML form redirection
*
* @param string $root
* @return Zend_Auth_Adapter_OpenId Provides a fluent interface
*/
public function setResponse($response)
{
$this->_response = $response;
return $this;
}
/**
* Enables or disables interaction with user during authentication on
* OpenID provider.
*
* @param bool $check_immediate
* @return Zend_Auth_Adapter_OpenId Provides a fluent interface
*/
public function setCheckImmediate($check_immediate)
{
$this->_check_immediate = $check_immediate;
return $this;
}
/**
* Sets HTTP client object to make HTTP requests
*
* @param Zend_Http_Client $client HTTP client object to be used
*/
public function setHttpClient($client) {
$this->_httpClient = $client;
}
/**
* Authenticates the given OpenId identity.
* Defined by Zend_Auth_Adapter_Interface.
*
* @throws Zend_Auth_Adapter_Exception If answering the authentication query is impossible
* @return Zend_Auth_Result
*/
public function authenticate() {
$id = $this->_id;
if (!empty($id)) {
$consumer = new Zend_OpenId_Consumer($this->_storage);
$consumer->setHttpClient($this->_httpClient);
/* login() is never returns on success */
if (!$this->_check_immediate) {
if (!$consumer->login($id,
$this->_returnTo,
$this->_root,
$this->_extensions,
$this->_response)) {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$id,
array("Authentication failed", $consumer->getError()));
}
} else {
if (!$consumer->check($id,
$this->_returnTo,
$this->_root,
$this->_extensions,
$this->_response)) {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$id,
array("Authentication failed", $consumer->getError()));
}
}
} else {
$params = (isset($_SERVER['REQUEST_METHOD']) &&
$_SERVER['REQUEST_METHOD']=='POST') ? $_POST: $_GET;
$consumer = new Zend_OpenId_Consumer($this->_storage);
$consumer->setHttpClient($this->_httpClient);
if ($consumer->verify(
$params,
$id,
$this->_extensions)) {
return new Zend_Auth_Result(
Zend_Auth_Result::SUCCESS,
$id,
array("Authentication successful"));
} else {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$id,
array("Authentication failed", $consumer->getError()));
}
}
}
}