Use Horde_Db and Horde_Ldap where appropriate.
require_once 'Horde/Group.php';
$groups = Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
$form = null;
$reload = false;
// Login to horde if username & password are set.
if (!empty($username) && !empty($password)) {
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->authenticate($username, array('password' => $password))) {
$cli->fatal(_("Username or password is incorrect."));
} else {
// Login to horde if username & password are set.
if (!empty($username) && !empty($password)) {
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->authenticate($username, array('password' => $password))) {
$error = _("Login is incorrect.");
Horde::logMessage($error, 'ERR');
// Login to horde if username & password are set.
if (!empty($username) && !empty($password)) {
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->authenticate($username, array('password' => $password))) {
$cli->fatal(_("Username or password is incorrect."));
} else {
$username = Horde_Util::getFormData('username');
$password = Horde_Util::getFormData('password');
if ($username && $password) {
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $injector->getInstance('Horde_Auth')->getOb();
if ($auth->authenticate($username,
array('password' => $password))) {
$cmd = 'list';
// Login to horde if username & password are set and load module.
} elseif (!empty($username) && !empty($password)) {
-
require_once HORDE_BASE . '/lib/base.php';
- $auth = &Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->authenticate($username, array('password' => $password))) {
$error = _("Login is incorrect.");
Horde::logMessage($error, 'ERR');
}
// Make sure auth backend allows passwords to be reset.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->hasCapability('resetpassword')) {
$notification->push(_("Cannot reset password automatically, contact your administrator."), 'horde.error');
Horde_Auth::authenticateFailure('folks');
require_once dirname(__FILE__) . '/tabs.php';
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
// Make sure signups are enabled before proceeding
if ($conf['signup']['allow'] !== true ||
$folks_authentication = 'none';
require_once dirname(__FILE__) . '/../lib/base.php';
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
$vars = Horde_Variables::getDefaultVariables();
$tabs = new Horde_Ui_Tabs('what', $vars);
/*
// Make sure auth backend allows passwords to be updated.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->hasCapability('resetpassword')) {
$notification->push(_("Cannot update password, contact your administrator."), 'horde.error');
Horde_Auth::authenticateFailure('folks');
}
// Check if users exits
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
if (!$auth->exists($user)) {
return PEAR::raiseError(sprintf(_("User \"%s\" does not exits"), $user));
}
}
// Check if users exits
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
if (!$auth->exists($friend)) {
return PEAR::raiseError(sprintf(_("User \"%s\" does not exits"), $friend));
}
$shares = $GLOBALS['injector']->getInstance('Horde_Share')->getScope();
$groups = &Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
$reload = false;
$actionID = Horde_Util::getFormData('actionID', 'edit');
$folks_authentication = 'none';
require_once dirname(__FILE__) . '/../lib/base.php';
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if (!Horde_Auth::getAuth() &&
(!isset($_SERVER['PHP_AUTH_USER']) ||
!$auth->authenticate($_SERVER['PHP_AUTH_USER'], array('password' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null)))) {
$folks_authentication = 'none';
require_once dirname(__FILE__) . '/../lib/base.php';
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if (!Horde_Auth::getAuth() &&
(!isset($_SERVER['PHP_AUTH_USER']) ||
!$auth->authenticate($_SERVER['PHP_AUTH_USER'], array('password' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null)))) {
$folks_authentication = 'none';
require_once dirname(__FILE__) . '/../lib/base.php';
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if (!Horde_Auth::getAuth() &&
(!isset($_SERVER['PHP_AUTH_USER']) ||
!$auth->authenticate($_SERVER['PHP_AUTH_USER'], array('password' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null)))) {
// Login to horde if username & password are set.
if (!empty($username) && !empty($password)) {
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->authenticate($username, array('password' => $password))) {
$error = _("Login is incorrect.");
Horde::logMessage($error, 'ERR');
{
$this->_logger->info('Horde_ActiveSync_Driver_Horde::logon attempt for: ' . $username);
parent::logon($username, $password, $domain);
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
return $auth->authenticate($username, array('password' => $password));
}
* @author Chuck Hagenbuch <chuck@horde.org>
* @author Michael Slusarz <slusarz@horde.org>
* @category Horde
- * @package Horde_Auth
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth
{
static public $dnsResolver;
/**
- * Singleton instances.
- *
- * @var array
- */
- static protected $_instances = array();
-
- /**
* The logout reason information.
*
* @var array
static public function factory($driver, $params = null)
{
$driver = str_replace(' ', '_' , ucwords(str_replace('_', ' ', basename($driver))));
- if (empty($params)) {
- $params = Horde::getDriverConfig('auth', $driver);
- }
-
$class = __CLASS__ . '_' . $driver;
+
if (class_exists($class)) {
return new $class($params);
}
}
/**
- * Attempts to return a reference to a concrete instance based on $driver.
- * It will only create a new instance if no instance with the same
- * parameters currently exists.
- *
- * This method must be invoked as: $var = Horde_Auth::singleton()
- *
- * @param mixed $driver The type of concrete Horde_Auth_Base subclass
- * to return.
- * @param array $params A hash containing any additional configuration or
- * connection parameters a subclass might need.
- *
- * @return Horde_Auth_Base The concrete reference.
- * @throws Horde_Auth_Exception
- */
- static public function singleton($driver, $params = array())
- {
- ksort($params);
- $signature = hash('md5', serialize(array($driver, $params)));
-
- if (!isset(self::$_instances[$signature])) {
- self::$_instances[$signature] = self::factory($driver, $params);
- }
-
- return self::$_instances[$signature];
- }
-
- /**
* Formats a password using the current encryption.
*
* @param string $plaintext The plaintext password to encrypt.
/* Try transparent authentication. */
$auth = (empty($options['app']) || ($options['app'] == 'horde'))
- ? self::singleton($GLOBALS['conf']['auth']['driver'])
- : self::singleton('application', array('app' => $options['app']));
+ ? $GLOBALS['injector']->getInstance('Horde_Auth')->getOb()
+ : $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('application', array('app' => $options['app']));
return $auth->transparent();
}
*/
static public function requireAuth($app)
{
- if ($app == 'horde') {
- return false;
- }
-
- $app_auth = self::singleton('application', array('app' => $app));
- return $app_auth->requireAuth();
+ return ($app == 'horde')
+ ? false
+ : $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('application', array('app' => $app))->requireAuth();
}
/**
}
}
- $auth = self::singleton($GLOBALS['conf']['auth']['driver']);
- return $auth->checkExistingAuth();
+ return $GLOBALS['injector']->getInstance('Horde_Auth')->getOb()->checkExistingAuth();
}
/**
* application-provided Horde authentication which fits inside the
* Horde_Auth:: API.
*
- * Required parameters:
- * <pre>
- * 'app' - (string) The application which is providing authentication.
- * </pre>
- *
* Copyright 2002-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Application extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
- * @throws Horde_Exception
+ * @param array $params Required parameters:
+ * <pre>
+ * 'app' - (string) The application which is providing authentication.
+ * </pre>
+ *
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- Horde::assertDriverConfig($params, 'auth', array('app'), 'authentication application');
+ if (!isset($params['app'])) {
+ throw new InvalidArgumentException('Missing app parameter.');
+ }
$this->_app = $params['app'];
+
parent::__construct($params);
}
* This is only for use in testing or behind a firewall; it should NOT be
* used on a public, production machine.
*
- * Optional parameters:
- * <pre>
- * 'password' - (string) The password to record in the user's credentials.
- * DEFAULT: none
- * 'requestuser' - (boolean) If true, allow username to be passed by GET, POST
- * or cookie.
- * DEFAULT: No
- * 'username' - (string) The username to authenticate everyone as.
- * DEFAULT: 'horde_user'
- * </pre>
- *
* Copyright 1999-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Auto extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing parameters.
+ * @param array $params Optional parameters:
+ * <pre>
+ * 'password' - (string) The password to record in the user's credentials.
+ * DEFAULT: none
+ * 'requestuser' - (boolean) If true, allow username to be passed by GET,
+ * POST or cookie.
+ * DEFAULT: No
+ * 'username' - (string) The username to authenticate everyone as.
+ * DEFAULT: 'horde_user'
+ * </pre>
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- parent::__construct($params);
+ $params = array_merge(array(
+ 'password' => '',
+ 'requestuser' => false,
+ 'username' => 'horde_user'
+ ), $params);
- if (!isset($this->_params['username'])) {
- $this->_params['username'] = 'horde_user';
- }
+ parent::__construct($params);
}
/**
*/
protected function _authenticate($userId, $credentials)
{
- throw new Horde_Auth_Exception('unsupported');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Michael Slusarz <slusarz@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @author Michael Slusarz <slusarz@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
abstract class Horde_Auth_Base
{
/**
* Current application for authentication.
*
- * @param string
+ * @var string
*/
protected $_app = 'horde';
/**
+ * Logger object.
+ *
+ * @var Horde_Log_Logger
+ */
+ protected $_logger;
+
+ /**
* Constructor.
*
- * @param array $params A hash containing parameters.
+ * @param array $params Optional parameters:
+ * <pre>
+ * 'logger' - (Horde_Log_Logger) A logger object.
+ * 'notify_expire' - (callback) Callback function to output notification
+ * when password is about to expire. Passed one
+ * argument: UNIX timestamp of when password expires.
+ * </pre>
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
+ if (isset($params['logger'])) {
+ $this->_logger = $params['logger'];
+ unset($params['logger']);
+ }
+
$this->_params = $params;
}
*/
public function addUser($userId, $credentials)
{
- throw new Horde_Auth_Exception('unsupported');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
*/
public function updateUser($oldID, $newID, $credentials)
{
- throw new Horde_Auth_Exception('unsupported');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
*/
public function removeUser($userId)
{
- throw new Horde_Auth_Exception('unsupported');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
*/
public function listUsers()
{
- throw new Horde_Auth_Exception('unsupported');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
*/
public function resetPassword($userId)
{
- throw new Horde_Auth_Exception('unsupported');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
* The Horde_Auth_Composite class provides a way to combine two separate
* drivers for admin vs. authentication purposes.
*
- * Required parameters:
- * <pre>
- * 'admin_driver' - (string) TODO
- * 'admin_driver_config' - (array) TODO
- * 'auth_driver' - (string) TODO
- * 'auth_driver_config' - (string) TODO
- * </pre>
- *
* Copyright 2002-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Composite extends Horde_Auth_Base
{
/**
- * Hash containing any instantiated drivers.
+ * Constructor.
+ *
+ * @param array $params Required parameters:
+ * <pre>
+ * 'admin_driver' - (Horde_Auth_Base) The admin driver.
+ * 'auth_driver' - (Horde_Auth_Base) The auth driver.
+ * </pre>
*
- * @var array
+ * @throws InvalidArgumentException
*/
- protected $_drivers = array();
+ public function __construct(array $params = array())
+ {
+ foreach (array('admin_driver', 'auth_driver') as $val) {
+ if (!isset($params[$val])) {
+ throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+ }
+ }
+
+ parent::__construct($params);
+ }
/**
* Find out if a set of login credentials are valid.
*/
protected function _authenticate($userId, $credentials)
{
- $driver = $this->_loadDriver('auth');
- return $driver->authenticate($userId, $credentials, false);
+ return $this->_params['auth_driver']->authenticate($userId, $credentials, false);
}
/**
public function hasCapability($capability)
{
try {
- $driver = $this->_loadDriver('admin');
- return $driver->hasCapability($capability);
+ return $this->_params['admin_driver']->hasCapability($capability);
} catch (Horde_Auth_Exception $e) {
return false;
}
protected function _transparent()
{
try {
- $driver = $this->_loadDriver('auth');
- return $driver->transparent();
+ return $this->_params['auth_driver']->transparent();
} catch (Horde_Auth_Exception $e) {
return false;
}
*/
public function addUser($userId, $credentials)
{
- $driver = $this->_loadDriver('admin');
- $driver->addUser($userId, $credentials);
+ $this->_params['admin_driver']->addUser($userId, $credentials);
}
/**
*/
public function updateUser($oldID, $newID, $credentials)
{
- $driver = $this->_loadDriver('admin');
- $driver->updateUser($oldID, $newID, $credentials);
+ $this->_params['admin_driver']->updateUser($oldID, $newID, $credentials);
}
/**
*
* @param string $userId The user id for which to reset the password.
*
- * @return mixed The new password on success or a PEAR_Error object on
- * failure.
+ * @return string The new password on success.
+ * @throws Horde_Auth_Exception
*/
public function resetPassword($userId)
{
- $driver = $this->_loadDriver('admin');
- $driver->resetPassword($userId);
+ return $this->_params['admin_driver']->resetPassword($userId);
}
/**
*/
public function removeUser($userId)
{
- $driver = $this->_loadDriver('admin');
- $driver->removeUser($userId);
+ $this->_params['admin_driver']->removeUser($userId);
}
/**
*/
public function listUsers()
{
- $driver = $this->_loadDriver('admin');
- return $driver->listUsers();
+ return $this->_params['admin_driver']->listUsers();
}
/**
public function exists($userId)
{
try {
- $driver = $this->_loadDriver('admin');
- return $driver->exists($userId);
+ return $this->_params['admin_driver']->exists($userId);
} catch (Horde_Auth_Exception $e) {
return false;
}
}
- /**
- * Loads one of the drivers in our configuration array, if it isn't already
- * loaded.
- *
- * @param string $driver The name of the driver to load.
- *
- * @throws Horde_Auth_Exception
- */
- protected function _loadDriver($driver)
- {
- if (empty($this->_drivers[$driver])) {
- $this->_drivers[$driver] = Horde_Auth::singleton($this->_params[$driver . '_driver'], $this->_params[$driver . '_driver_config']);
- }
-
- return $this->_drivers[$driver];
- }
-
}
* The Horde_Auth_Customsql class provides a sql implementation of the Horde
* authentication system with the possibility to set custom-made queries.
*
- * Required parameters: See Horde_Auth_Sql driver.
- * <pre>
- * Some special tokens can be used in the sql query. They are replaced
- * at the query stage:
- *
- * - '\L' will be replaced by the user's login
- * - '\P' will be replaced by the user's password.
- * - '\O' will be replaced by the old user's login (required for update)
- *
- * Eg: "SELECT * FROM users WHERE uid = \L
- * AND passwd = \P
- * AND billing = 'paid'
- *
- * 'query_auth' Authenticate the user. '\L' & '\P'
- * 'query_add' Add user. '\L' & '\P'
- * 'query_getpw' Get one user's password. '\L'
- * 'query_update' Update user. '\O', '\L' & '\P'
- * 'query_resetpassword' Reset password. '\L', & '\P'
- * 'query_remove' Remove user. '\L'
- * 'query_list' List user.
- * 'query_exists' Check for existance of user. '\L'
- * </pre>
- *
- * Optional parameters: See Horde_Auth_Sql driver.
- *
* Copyright 2002 Ronnie Garcia <ronnie@mk2.net>
+ * Copyright 2002-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Ronnie Garcia <ronnie@mk2.net>
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Joel Vandal <joel@scopserv.com>
- * @package Horde_Auth
+ * @author Ronnie Garcia <ronnie@mk2.net>
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @author Joel Vandal <joel@scopserv.com>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php
+ * @package Auth
*/
class Horde_Auth_Customsql extends Horde_Auth_Sql
{
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * Some special tokens can be used in the SQL query. They are replaced
+ * at the query stage:
+ * '\L' will be replaced by the user's login
+ * '\P' will be replaced by the user's password.
+ * '\O' will be replaced by the old user's login (required for update)
+ *
+ * Eg: "SELECT * FROM users WHERE uid = \L
+ * AND passwd = \P
+ * AND billing = 'paid'
+ *
+ * @param array $params Configuration parameters:
+ * <pre>
+ * 'query_auth' - (string) Authenticate the user. ('\L' & '\P')
+ * 'query_add' - (string) Add user. ('\L' & '\P')
+ * 'query_getpw' - (string) Get one user's password. ('\L')
+ * 'query_update' - (string) Update user. ('\O', '\L' & '\P')
+ * 'query_resetpassword' - (string) Reset password. ('\L', & '\P')
+ * 'query_remove' - (string) Remove user. ('\L')
+ * 'query_list' - (string) List user.
+ * 'query_exists' - (string) Check for existance of user. ('\L')
+ * </pre>
+ *
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- Horde::assertDriverConfig($params, 'auth',
- array('query_auth'),
- 'authentication custom SQL');
+ foreach (array('query_auth', 'query_add', 'query_getpw',
+ 'query_update', 'query_resetpassword', 'query_remove',
+ 'query_list', 'query_exists') as $val) {
+ if (!isset($params[$val])) {
+ throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+ }
+ }
parent::__construct($params);
}
*/
protected function _authenticate($userId, $credentials)
{
- try {
- $this->_connect();
- } catch (Horde_Auth_Exception $e) {
- throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
- }
-
/* Build a custom query, based on the config file. */
- $query = $this->_params['query_auth'];
- $query = str_replace('\L', $this->_db->quote($userId), $query);
- $query = str_replace('\P', $this->_db->quote(Horde_Auth::getCryptedPassword(
- $credentials['password'],
- $this->_getPassword($userId),
- $this->_params['encryption'],
- $this->_params['show_encryption'])), $query);
+ $query = str_replace(
+ array('\L', '\P'),
+ array(
+ $this->_db->quote($userId),
+ $this->_db->quote(Horde_Auth::getCryptedPassword($credentials['password'], $this->_getPassword($userId), $this->_params['encryption'], $this->_params['show_encryption']))
+ ),
+ $this->_params['query_auth']
+ );
- $result = $this->_db->query($query);
- if ($result instanceof PEAR_Error) {
+ try {
+ if ($this->_db->selectValue($query)) {
+ return;
+ }
+ throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
+ } catch (Horde_Db_Exception $e) {
throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
}
-
- $row = $result->fetchRow(DB_GETMODE_ASSOC);
-
- /* If we have at least one returned row, then the user is valid. */
- if (is_array($row)) {
- $result->free();
- return;
- }
-
- $result->free();
- throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
}
/**
*/
public function addUser($userId, $credentials)
{
- $this->_connect();
-
/* Build a custom query, based on the config file. */
- $query = $this->_params['query_add'];
- $query = str_replace('\L', $this->_db->quote($userId), $query);
- $query = str_replace('\P', $this->_db->quote(Horde_Auth::getCryptedPassword(
- $credentials['password'], '',
- $this->_params['encryption'],
- $this->_params['show_encryption'])), $query);
+ $query = str_replace(
+ array('\L', 'P'),
+ array(
+ $this->_db->quote($userId),
+ $this->_db->quote(Horde_Auth::getCryptedPassword($credentials['password'], '', $this->_params['encryption'], $this->_params['show_encryption']))
+ ),
+ $this->_params['query_add']
+ );
- $result = $this->_db->query($query);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $this->_db->insert($query);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
}
*
* @throws Horde_Auth_Exception
*/
- function updateUser($oldId, $newId, $credentials)
+ public function updateUser($oldId, $newId, $credentials)
{
- $this->_connect();
-
/* Build a custom query, based on the config file. */
- $query = $this->_params['query_update'];
- $query = str_replace('\O', $this->_db->quote($oldId), $query);
- $query = str_replace('\L', $this->_db->quote($newId), $query);
- $query = str_replace('\P', $this->_db->quote(Horde_Auth::getCryptedPassword(
- $credentials['password'],
- $this->_getPassword($oldId),
- $this->_params['encryption'],
- $this->_params['show_encryption'])), $query);
+ $query = str_replace(
+ array('\O', '\L', '\P'),
+ array(
+ $this->_db->quote($oldId),
+ $this->_db->quote($newId),
+ $this->_db->quote(Horde_Auth::getCryptedPassword($credentials['password'], $this->_getPassword($oldId), $this->_params['encryption'], $this->_params['show_encryption']))
+ ),
+ $this->_params['query_update']
+ );
- $result = $this->_db->query($query);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $this->_db->update($query);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
}
*/
public function resetPassword($userId)
{
- $this->_connect();
-
/* Get a new random password. */
$password = Horde_Auth::genRandomPassword();
/* Build the SQL query. */
- $query = $this->_params['query_resetpassword'];
- $query = str_replace('\L', $this->_db->quote($userId), $query);
- $query = str_replace('\P', $this->_db->quote(Horde_Auth::getCryptedPassword($password,
- '',
- $this->_params['encryption'],
- $this->_params['show_encryption'])), $query);
+ $query = str_replace(
+ array('\L', '\P'),
+ array(
+ $this->_db->quote($userId),
+ $this->_db->quote(Horde_Auth::getCryptedPassword($password, '', $this->_params['encryption'], $this->_params['show_encryption']))
+ ),
+ $this->_params['query_resetpassword']
+ );
- $result = $this->_db->query($query);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $this->_db->update($query);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
return $password;
*/
public function removeUser($userId)
{
- $this->_connect();
-
/* Build a custom query, based on the config file. */
- $query = $this->_params['query_remove'];
- $query = str_replace('\L', $this->_db->quote($userId), $query);
+ $query = str_replace(
+ '\L',
+ $this->_db->quote($userId),
+ $this->_params['query_remove']
+ );
- $result = $this->_db->query($query);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $this->_db->delete($query);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
- $this->removeUserData($userId);
+ Horde_Auth::removeUserData($userId);
}
/**
*/
public function listUsers()
{
- $this->_connect();
-
/* Build a custom query, based on the config file. */
- $query = $this->_params['query_list'];
- $query = str_replace('\L', $this->_db->quote(Horde_Auth::getAuth()), $query);
+ $query = str_replace(
+ '\L',
+ $this->_db->quote(Horde_Auth::getAuth()),
+ $this->_params['query_list']
+ );
- $result = $this->_db->getAll($query, null, DB_FETCHMODE_ORDERED);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $result = $this->_db->selectAll($query);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
/* Loop through and build return array. */
*/
public function exists($userId)
{
+ /* Build a custom query, based on the config file. */
+ $query = str_replace(
+ '\L',
+ $this->_db->quote($userId),
+ $this->_params['query_exists']
+ );
+
try {
- $this->_connect();
- } catch (Horde_Auth_Exception $e) {
+ return (bool)$this->_db->selectValue($query);
+ } catch (Horde_Db_Exception $e) {
return false;
}
-
- /* Build a custom query, based on the config file. */
- $query = $this->_params['query_exists'];
- $query = str_replace('\L', $this->_db->quote($userId), $query);
-
- $result = $this->_db->getOne($query);
-
- return ($result instanceof PEAR_Error)
- ? false
- : (bool)$result;
}
/**
* Fetch $userId's current password - needed for the salt with some
* encryption schemes when doing authentication or updates.
*
- * @param string $userId TODO
+ * @param string $userId The userId to query.
*
* @return string $userId's current password.
*/
protected function _getPassword($userId)
{
/* Retrieve the old password in case we need the salt. */
- $query = $this->_params['query_getpw'];
- $query = str_replace('\L', $this->_db->quote($userId), $query);
- $pw = $this->_db->getOne($query);
- if ($pw instanceof PEAR_Error) {
- Horde::logMessage($pw, 'ERR');
- return '';
- }
+ $query = str_replace(
+ '\L',
+ $this->_db->quote($userId),
+ $this->_params['query_getpw']
+ );
- return $pw;
+ try {
+ return $this->_db->selectValue($query);
+ } catch (Horde_Db_Exception $e) {
+ return null;
+ }
}
}
* is the same as for the SQL class; only what is different overrides the
* parent class implementations.
*
- * Required parameters: See Horde_Auth_Sql driver.
- * <pre>
- * 'cyradmin' The username of the cyrus administrator.
- * 'cyrpass' The password for the cyrus administrator.
- * 'hostspec' The hostname or IP address of the server.
- * DEFAULT: 'localhost'
- * 'port' The server port to which we will connect.
- * IMAP is generally 143, while IMAP-SSL is generally 993.
- * DEFAULT: Encryption port default
- * 'secure' The encryption to use. Either 'none', 'ssl', or 'tls'.
- * DEFAULT: 'none'
- * </pre>
- *
- * Optional parameters: See Horde_Auth_Sql driver.
- * <pre>
- * 'domain_field' If set to anything other than 'none' this is used as
- * field name where domain is stored.
- * DEFAULT: 'domain_name'
- * 'hidden_accounts' An array of system accounts to hide from the user
- * interface.
- * 'folders' An array of folders to create under username.
- * DEFAULT: NONE
- * 'quota' The quota (in kilobytes) to grant on the mailbox.
- * DEFAULT: NONE
- * 'unixhier' The value of imapd.conf's unixhierarchysep setting.
- * Set this to true if the value is true in imapd.conf.
- * </pre>
- *
* The table structure for the auth system is as follows:
* <pre>
* CREATE TABLE accountuser (
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Ilya Krel <mail@krel.org>
- * @author Jan Schneider <jan@horde.org>
- * @package Horde_Auth
+ * @author Ilya Krel <mail@krel.org>
+ * @author Jan Schneider <jan@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Cyrsql extends Horde_Auth_Sql
{
*
* @var Horde_Imap_Client_Base
*/
- protected $_ob;
+ protected $_imap;
/**
* Hierarchy separator to use (e.g., is it user/mailbox or user.mailbox)
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Parameters:
+ * <pre>
+ * 'domain_field' - (string) If set to anything other than 'none' this is
+ * used as field name where domain is stored.
+ * DEFAULT: 'domain_name'
+ * 'folders' - (array) An array of folders to create under username.
+ * DEFAULT: NONE
+ * 'hidden_accounts' - (array) An array of system accounts to hide from
+ * the user interface.
+ * DEFAULT: None.
+ * 'imap' - (Horde_Imap_Client_Base) [REQUIRED] An IMAP client object.
+ * 'quota' - (integer) The quota (in kilobytes) to grant on the mailbox.
+ * DEFAULT: NONE
+ * 'unixhier' - (boolean) The value of imapd.conf's unixhierarchysep
+ * setting. Set this to true if the value is true in
+ * imapd.conf.
+ * DEFAULT: false
+ * </pre>
+ *
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- parent::__construct($params);
+ if (!isset($params['imap']) ||
+ !($params['imap'] instanceof Horde_Imap_Client_Base)) {
+ throw new InvalidArgumentException('Missing imap parameter.');
+ }
+ $this->_imap = $params['imap'];
+ unset($params['imap']);
- $admin_params = array(
- 'admin_user' => $params['cyradmin'],
- 'admin_password' => $params['cyrpass'],
- 'dsn' => $params['imap_dsn']
- );
+ $params = array_merge(array(
+ 'domain_field' => 'domain_name',
+ 'folders' => array(),
+ 'hidden_accounts' => array('cyrus'),
+ 'quota' => null
+ ), $params);
- if (!empty($this->_params['unixhier'])) {
- $admin_params['userhierarchy'] = 'user/';
- }
+ parent::__construct($params);
if (!empty($this->_params['unixhier'])) {
+ $this->_params['userhierarchy'] = 'user/';
$this->_separator = '/';
}
}
*/
protected function _authenticate($userId, $credentials)
{
- try {
- $this->_connect();
- } catch (Horde_Auth_Exception $e) {
- Horde::logMessage($e, 'ERR');
- throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
- }
-
if (!empty($this->_params['domain_field']) &&
($this->_params['domain_field'] != 'none')) {
/* Build the SQL query with domain. */
$values = array($userId);
}
- Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::_authenticate(): ' . $query, 'DEBUG');
-
- $result = $this->_db->query($query, $values);
- if ($result instanceof PEAR_Error) {
- Horde::logMessage($result, 'ERR');
+ try {
+ $row = $this->_db->selectOne($query, $values);
+ } catch (Horde_Db_Exception $e) {
throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
}
- $row = $result->fetchRow(DB_GETMODE_ASSOC);
- if (is_array($row)) {
- $result->free();
- } else {
- throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
- }
-
- if (!$this->_comparePasswords($row[$this->_params['password_field']],
- $credentials['password'])) {
+ if (!$row ||
+ !$this->_comparePasswords($row[$this->_params['password_field']], $credentials['password'])) {
throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
}
*/
public function addUser($userId, $credentials)
{
- $this->_connect();
-
if (!empty($this->_params['domain_field']) &&
($this->_params['domain_field'] != 'none')) {
list($name, $domain) = explode('@', $userId);
- /* Build the SQL query. */
+
$query = sprintf('INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)',
$this->_params['table'],
$this->_params['username_field'],
$this->_params['domain_field'],
$this->_params['password_field']);
- $values = array($name,
- $domain,
- Horde_Auth::getCryptedPassword($credentials['password'],
- '',
- $this->_params['encryption'],
- $this->_params['show_encryption']));
-
- Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::addUser(): ' . $query, 'DEBUG');
-
- $dbresult = $this->_db->query($query, $values);
- $query = 'INSERT INTO virtual (alias, dest, username, status) VALUES (?, ?, ?, 1)';
- $values = array($userId, $userId, $name);
-
- Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::addUser(): ' . $query, 'DEBUG');
+ $values = array(
+ $name,
+ $domain,
+ Horde_Auth::getCryptedPassword($credentials['password'],
+ '',
+ $this->_params['encryption'],
+ $this->_params['show_encryption'])
+ );
+
+ $query2 = 'INSERT INTO virtual (alias, dest, username, status) VALUES (?, ?, ?, 1)';
+ $values2 = array($userId, $userId, $name);
- $dbresult2 = $this->_db->query($query, $values);
- if ($dbresult2 instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($dbresult2);
+ try {
+ $this->_db->insert($query, $values);
+ $this->_db->insert($query2, $values2);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
} else {
parent::addUser($userId, $credentials);
try {
$mailbox = Horde_String::convertCharset($this->_params['userhierarchy'] . $userId, Horde_Nls::getCharset(), 'utf7-imap');
- $ob->createMailbox($mailbox);
- $ob->setACL($mailbox, $this->_params['cyradm'], 'lrswipcda');
+ $this->_imap->createMailbox($mailbox);
+ $this->_imap->setACL($mailbox, $this->_params['cyradm'], 'lrswipcda');
} catch (Horde_Imap_Client_Exception $e) {
throw new Horde_Auth_Exception($e);
}
}
$tmp = Horde_String::convertCharset($tmp, Horde_Nls::getCharset(), 'utf7-imap');
- $ob->createMailbox($tmp);
- $ob->setACL($tmp, $this->_params['cyradm'], 'lrswipcda');
+ $this->_imap->createMailbox($tmp);
+ $this->_oimap>setACL($tmp, $this->_params['cyradm'], 'lrswipcda');
}
if (isset($this->_params['quota']) &&
($this->_params['quota'] >= 0)) {
try {
- $this->_ob->setQuota($mailbox, array('storage' => $this->_params['quota']));
+ $this->_imap->setQuota($mailbox, array('storage' => $this->_params['quota']));
} catch (Horde_Imap_Client_Exception $e) {
throw new Horde_Auth_Exception($e);
}
}
-
- if (isset($this->_params['quota']) &&
- ($this->_params['quota'] >= 0) &&
- !@imap_set_quota($this->_imapStream, 'user' . $this->_separator . $userId, $this->_params['quota'])) {
- throw new Horde_Auth_Exception(sprintf(_("IMAP mailbox quota creation failed: %s"), imap_last_error()));
- }
}
/**
*
* @throws Horde_Auth_Exception
*/
- function removeUser($userId)
+ public function removeUser($userId)
{
- $this->_connect();
-
if (!empty($this->_params['domain_field']) &&
($this->_params['domain_field'] != 'none')) {
list($name, $domain) = explode('@', $userId);
+
/* Build the SQL query. */
$query = sprintf('DELETE FROM %s WHERE %s = ? and %s = ?',
$this->_params['table'],
$this->_params['domain_field']);
$values = array($name, $domain);
- Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::removeUser(): ' . $query, 'DEBUG');
-
- $dbresult = $this->_db->query($query, $values);
- $query = 'DELETE FROM virtual WHERE dest = ?';
- $values = array($userId);
+ $query2 = 'DELETE FROM virtual WHERE dest = ?';
+ $values2 = array($userId);
- Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::removeUser(): ' . $query, 'DEBUG');
-
- $dbresult2 = $this->_db->query($query, $values);
- if ($dbresult2 instanceof PEAR_Error) {
- return $dbresult2;
+ try {
+ $this->_db->delete($query, $values);
+ $this->_db->delete($query2, $values2);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
} else {
parent::removeUser($userId);
list($admin) = explode('@', $this->_params['cyradmin']);
try {
- $this->_ob->setACL($mailbox, $admin, array('rights' => 'lrswipcda'));
- $this->_ob->deleteMailbox($mailbox);
+ $this->_imap->setACL($mailbox, $admin, array('rights' => 'lrswipcda'));
+ $this->_imap->deleteMailbox($mailbox);
} catch (Horde_Imap_Client_Exception $e) {
throw new Horde_Auth_Exception($e);
}
*/
public function listUsers()
{
- $this->_connect();
-
if (!empty($this->_params['domain_field']) &&
($this->_params['domain_field'] != 'none')) {
/* Build the SQL query with domain. */
$this->_params['username_field']);
}
- Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::listUsers(): ' . $query, 'DEBUG');
-
- $result = $this->_db->getAll($query, null, DB_FETCHMODE_ORDERED);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $result = $this->_db->selectAll($query);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
/* Loop through and build return array. */
$users = array();
- if (!empty($this->_params['domain_field'])
- && ($this->_params['domain_field'] != 'none')) {
+ if (!empty($this->_params['domain_field']) &&
+ ($this->_params['domain_field'] != 'none')) {
foreach ($result as $ar) {
if (!in_array($ar[0], $this->_params['hidden_accounts'])) {
$users[] = $ar[0] . '@' . $ar[1];
*/
public function updateUser($oldID, $newID, $credentials)
{
- $this->_connect();
-
if (!empty($this->_params['domain_field']) &&
($this->_params['domain_field'] != 'none')) {
list($name, $domain) = explode('@', $oldID);
$oldID);
}
- Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::updateUser(): ' . $query, 'DEBUG');
-
- $res = $this->_db->query($query, $values);
- if ($res instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($res);
- }
- }
-
- /**
- * Attempts to open connections to the SQL and IMAP servers.
- *
- * @throws Horde_Auth_Exception
- */
- public function _connect()
- {
- if ($this->_connected) {
- return;
- }
-
- parent::_connect();
-
- if (!isset($this->_params['hidden_accounts'])) {
- $this->_params['hidden_accounts'] = array('cyrus');
- }
-
- // Reset the $_connected flag; we haven't yet successfully
- // opened everything.
- $this->_connected = false;
-
- $imap_config = array(
- 'hostspec' => empty($this->_params['hostspec']) ? null : $this->_params['hostspec'],
- 'password' => $this->_params['cyrpass'],
- 'port' => empty($this->_params['port']) ? null : $this->_params['port'],
- 'secure' => ($this->_params['secure'] == 'none') ? null : $this->_params['secure'],
- 'username' => $this->_params['cyradmin']
- );
-
try {
- $this->_ob = Horde_Imap_Client::factory('Socket', $imap_config);
- $this->_ob->login();
- } catch (Horde_Imap_Client_Exception $e) {
+ $this->_db->update($query, $values);
+ } catch (Horde_Db_Exception $e) {
throw new Horde_Auth_Exception($e);
}
-
- $this->_connected = true;
}
}
* administrating a Cyrus mail server authentications against another backend
* that Horde can update (eg SQL or LDAP).
*
- * Required parameters:
- * <pre>
- * 'backend' The complete hash for the Auth_* driver that cyrus
- * authenticates against (eg SQL, LDAP).
- * 'cyradmin' The username of the cyrus administrator
- * 'cyrpass' The password for the cyrus administrator
- * 'hostspec' The hostname or IP address of the server.
- * DEFAULT: 'localhost'
- * 'port' The server port to which we will connect.
- * IMAP is generally 143, while IMAP-SSL is generally 993.
- * DEFAULT: Encryption port default
- * 'secure' The encryption to use. Either 'none', 'ssl', or 'tls'.
- * DEFAULT: 'none'
- * </pre>
- *
* Optional values:
* <pre>
- * 'folders' An array of folders to create under username.
- * Doesn't create subfolders by default.
- * 'quota' The quota (in kilobytes) to grant on the mailbox.
- * Does not establish quota by default.
- * 'separator' Hierarchy separator to use (e.g., is it user/mailbox or
- * user.mailbox)
- * 'unixhier' The value of imapd.conf's unixhierarchysep setting.
- * Set this to 'true' if the value is true in imapd.conf
- * </pre>
*
- * Example Usage:
- * <pre>
- * $conf['auth']['driver'] = 'composite';
- * $conf['auth']['params']['admin_driver'] = 'cyrus';
- * $conf['auth']['params']['drivers']['imp'] = array(
- * 'driver' => 'application',
- * 'params' => array('app' => 'imp')
- * );
- * $conf['auth']['params']['drivers']['cyrus'] = array(
- * 'driver' => 'cyrus',
- * 'params' => array(
- * 'cyradmin' => 'cyrus',
- * 'cyrpass' => 'password',
- * 'hostspec' => 'imap.example.com',
- * 'secure' => 'none'
- * 'separator' => '.'
- * )
- * );
- * $conf['auth']['params']['drivers']['cyrus']['params']['backend'] = array(
- * 'driver' => 'sql',
- * 'params' => array(
- * 'phptype' => 'mysql',
- * 'hostspec' => 'database.example.com',
- * 'protocol' => 'tcp',
- * 'username' => 'username',
- * 'password' => 'password',
- * 'database' => 'mail',
- * 'table' => 'accountuser',
- * 'encryption' => 'md5-hex',
- * 'username_field' => 'username',
- * 'password_field' => 'password'
- * )
- * );
* </pre>
*
* Copyright 2002-2010 The Horde Project (http://www.horde.org/)
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Ilya Krel <mail@krel.org>
- * @author Mike Cochrane <mike@graftonhall.co.nz>
- * @package Horde_Auth
+ * @author Ilya Krel <mail@krel.org>
+ * @author Mike Cochrane <mike@graftonhall.co.nz>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Cyrus extends Horde_Auth_Base
{
*
* @var Horde_Imap_Client_Base
*/
- protected $_ob;
+ protected $_imap;
/**
* Pointer to another backend that Cyrus authenticates against.
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
- *
- * @throws Horde_Exception
+ * @param array $params Parameters:
+ * <pre>
+ * TODO
+ * 'backend' - (Horde_Auth_Base) [REQUIRED] The backend object.
+ * 'folders' - (array) An array of folders to create under username.
+ * DEFAULT: NONE
+ * 'imap' - (Horde_Imap_Client_Base) [REQUIRED] An IMAP client object.
+ * 'quota' - (integer) The quota (in kilobytes) to grant on the mailbox.
+ * DEFAULT: NONE
+ * 'separator' - (string) Hierarchy separator to use (e.g., is it
+ * user/mailbox or user.mailbox)
+ * DEFAULT: '.'
+ * 'unixhier' - (boolean) The value of imapd.conf's unixhierarchysep
+ * setting. Set this to true if the value is true in
+ * imapd.conf.
+ * DEFAULT: false
+ * </pre>
+ *
+ * @throws InvalidArgumentException
+ * @throws Horde_Auth_Exception
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- parent::__construct($params);
-
- if (!isset($this->_params['separator'])) {
- $this->_params['separator'] = '.';
+ foreach (array('backend', 'imap') as $val) {
+ if (!isset($params[$val])) {
+ throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+ }
}
+ $this->_backend = $params['backend'];
+ $this->_ob = $params['imap'];
+ unset($params['backend']);
+
+ $params = array_merge(array(
+ 'separator' => '.',
+ ), $params);
+
+ parent::__construct($params);
+
if (isset($this->_params['unixhier']) &&
$this->_params['unixhier'] == true) {
$this->_params['separator'] = '/';
}
- // Create backend instance.
- $this->_backend = Horde_Auth::singleton($this->_params['backend']['driver'], $this->_params['backend']['params']);
-
// Check the capabilities of the backend.
if (!$this->_backend->hasCapability('add') ||
!$this->_backend->hasCapability('update') ||
!$this->_backend->hasCapability('remove')) {
- throw new Horde_Exception('Horde_Auth_Cyrus: Backend does not have required capabilites.');
+ throw new Horde_Auth_Exception(__CLASS__ . ': Backend does not have required capabilites.');
}
$this->_capabilities['list'] = $this->_backend->hasCapability('list');
*/
public function addUser($userId, $credentials)
{
- $this->_connect();
-
$this->_backend->addUser($userId, $credentials);
$mailbox = Horde_String::convertCharset('user' . $this->_params['separator'] . $userId, Horde_Nls::getCharset(), 'utf7-imap');
try {
- $this->_ob->createMailbox($mailbox);
+ $this->_imap->createMailbox($mailbox);
} catch (Horde_Imap_Client_Exception $e) {
throw new Horde_Auth_Exception($e);
}
is_array($this->_params['folders'])) {
foreach ($this->_params['folders'] as $folder) {
try {
- $this->_ob->createMailbox($mailbox . Horde_String::convertCharset($this->_params['separator'] . $folder, Horde_Nls::getCharset(), 'utf7-imap'));
+ $this->_imap->createMailbox($mailbox . Horde_String::convertCharset($this->_params['separator'] . $folder, Horde_Nls::getCharset(), 'utf7-imap'));
} catch (Horde_Imap_Client_Exception $e) {}
}
}
if (isset($this->_params['quota']) &&
($this->_params['quota'] >= 0)) {
try {
- $this->_ob->setQuota($mailbox, array('storage' => $this->_params['quota']));
+ $this->_imap->setQuota($mailbox, array('storage' => $this->_params['quota']));
} catch (Horde_Imap_Client_Exception $e) {
throw new Horde_Auth_Exception($e);
}
*/
public function removeUser($userId)
{
- $this->_connect();
-
$this->_backend->removeUser($userId);
$mailbox = Horde_String::convertCharset('user' . $this->_params['separator'] . $userId, Horde_Nls::getCharset(), 'utf7-imap');
list($admin) = explode('@', $this->_params['cyradmin']);
try {
- $this->_ob->setACL($mailbox, $admin, array('rights' => 'lrswipcda'));
- $this->_ob->deleteMailbox($mailbox);
+ $this->_imap->setACL($mailbox, $admin, array('rights' => 'lrswipcda'));
+ $this->_imap->deleteMailbox($mailbox);
} catch (Horde_Imap_Client_Exception $e) {
throw new Horde_Auth_Exception($e);
}
}
/**
- * Attempts to open connections to the IMAP servers.
- *
- * @throws Horde_Auth_Exception
- */
- protected function _connect()
- {
- if ($this->_ob) {
- return;
- }
-
- $imap_config = array(
- 'hostspec' => empty($this->_params['hostspec']) ? null : $this->_params['hostspec'],
- 'password' => $pass,
- 'port' => empty($this->_params['port']) ? null : $this->_params['port'],
- 'secure' => ($this->_params['secure'] == 'none') ? null : $this->_params['secure'],
- 'username' => $user
- );
-
- try {
- $this->_ob = Horde_Imap_Client::factory('Socket', $imap_config);
- $this->_ob->login();
- } catch (Horde_Imap_Client_Exception $e) {
- throw new Horde_Auth_Exception($e);
- }
- }
-
- /**
* List all users in the system.
*
* @return array The array of userIds.
*/
protected function _authenticate($userId, $credentials)
{
- throw new Horde_Auth_Exception('Not implemented!');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
<?php
/**
- * Authentication exceptions.
+ * Exceptions class for the horde/Auth package.
*
- * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
+ * Copyright 2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Michael Slusarz <slusarz@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @author Michael Slusarz <slusarz@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Exception extends Horde_Exception_Prior
{
* The Horde_Auth_Ftp class provides an FTP implementation of the Horde
* authentication system.
*
- * Optional parameters:
- * <pre>
- * 'hostspec' - (string) The hostname or IP address of the FTP server.
- * DEFAULT: 'localhost'
- * 'port' - (integer) The server port to connect to.
- * DEFAULT: 21
- * </pre>
- *
* Copyright 1999-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Max Kalika <max@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @author Max Kalika <max@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Ftp extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Optional parameters:
+ * <pre>
+ * 'hostspec' - (string) The hostname or IP address of the FTP server.
+ * DEFAULT: 'localhost'
+ * 'port' - (integer) The server port to connect to.
+ * DEFAULT: 21
+ * </pre>
*
* @throws Horde_Auth_Exception
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
if (!Horde_Util::extensionExists('ftp')) {
- throw new Horde_Auth_Exception('Horde_Auth_Ftp: Required FTP extension not found. Compile PHP with the --enable-ftp switch.');
+ throw new Horde_Auth_Exception(__CLASS__ ': Required FTP extension not found. Compile PHP with the --enable-ftp switch.');
}
$params = array_merge(array(
* The Horde_Auth_Http class transparently logs users in to Horde using
* already present HTTP authentication headers.
*
- * The 'encryption' parameter specifies what kind of passwords are in
- * the .htpasswd file. The supported options are 'crypt-des' (standard
- * crypted htpasswd entries) and 'aprmd5'. This information is used if
- * you want to directly authenticate users with this driver, instead
- * of relying on transparent auth.
- *
* Copyright 1999-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Http extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing parameters.
+ * @param array $params Optional parameters:
+ * <pre>
+ * 'encryption' - (string) Kind of passwords in the .htpasswd file.
+ * Either 'crypt-des' (standard crypted htpasswd entries)
+ * [DEFAULT] or 'aprmd5'. This information is used if
+ * you want to directly authenticate users with this
+ * driver, instead of relying on transparent auth.
+ * 'htpasswd_file' - (string) TODO
+ * </pre>
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- parent::__construct($params);
+ $params = array_merge(array(
+ 'encryption' => 'crypt-des'
+ ), $params);
- // Default to DES passwords.
- if (empty($this->_params['encryption'])) {
- $this->_params['encryption'] = 'crypt-des';
- }
+ parent::__construct($params);
if (!empty($this->_params['htpasswd_file'])) {
$users = file($this->_params['htpasswd_file']);
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Duck <duck@obala.net>
- * @package Horde_Auth
+ * @author Duck <duck@obala.net>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Http_Remote extends Horde_Auth_Base
{
/**
+ * Constructor.
+ *
+ * @param array $params Configuration parameters:
+ * <pre>
+ * 'proxy' - (array) TODO
+ * 'url' - (string) [REQUIRED] TODO
+ * </pre>
+ *
+ * @throws InvalidArgumentException
+ */
+ public function __construct(array $params = array())
+ {
+ if (!isset($params['url'])) {
+ throw new InvalidArgumentException();
+ }
+
+ $params = array_merge(array(
+ 'proxy' => array()
+ ), $params);
+
+ parent::__construct($params);
+ }
+
+ /**
* Find out if a set of login credentials are valid.
*
* @param string $userId The userId to check.
*/
protected function _authenticate($userId, $credentials)
{
- $options = array(
+ $options = array_merge(array(
'allowRedirects' => true,
'method' => 'GET',
'timeout' => 5
- );
-
- if (!empty($GLOBALS['conf']['http']['proxy']['proxy_host'])) {
- $options = array_merge($options, $GLOBALS['conf']['http']['proxy']);
- }
+ ), $this->_params['proxy']);
$request = new HTTP_Request($this->_params['url'], $options);
$request->setBasicAuth($userId, $credentials['password']);
* The Horde_Auth_Imap:: class provides an IMAP implementation of the Horde
* authentication system.
*
- * Optional parameters:
- * <pre>
- * 'admin_password' The password of the adminstrator.
- * DEFAULT: null
- * 'admin_user' The name of a user with admin privileges.
- * DEFAULT: null
- * 'hostspec' The hostname or IP address of the server.
- * DEFAULT: 'localhost'
- * 'port' The server port to which we will connect.
- * IMAP is generally 143, while IMAP-SSL is generally 993.
- * DEFAULT: Encryption port default
- * 'secure' The encryption to use. Either 'none', 'ssl', or 'tls'.
- * DEFAULT: 'none'
- * 'userhierarchy' The hierarchy where user mailboxes are stored.
- * DEFAULT: 'user.'
- * </pre>
- *
- * If setting up as Horde auth handler in conf.php, this is a sample entry:
- * <pre>
- * $conf['auth']['params']['hostspec'] = 'imap.example.com';
- * $conf['auth']['params']['port'] = 143;
- * $conf['auth']['params']['secure'] = 'none';
- * </pre>
- *
* Copyright 1999-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Gaudenz Steinlin <gaudenz@soziologie.ch>
- * @author Jan Schneider <jan@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @author Gaudenz Steinlin <gaudenz@soziologie.ch>
+ * @author Jan Schneider <jan@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Imap extends Horde_Auth_Base
{
/**
- * Cached Horde_Imap_Client_Base object.
+ * Imap client objects.
*
- * @var Horde_Imap_Client_Base
+ * @var array()
*/
- protected $_ob;
+ protected $_imap = array();
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Optional parameters:
+ * <pre>
+ * 'admin_password' - (string) The password of the adminstrator.
+ * DEFAULT: null
+ * 'admin_user' - (string) The name of a user with admin privileges.
+ * DEFAULT: null
+ * 'hostspec' - (string) The hostname or IP address of the server.
+ * DEFAULT: 'localhost'
+ * 'port' - (integer) The server port to which we will connect.
+ * IMAP is generally 143, while IMAP-SSL is generally 993.
+ * DEFAULT: Encryption port default
+ * 'secure' - (string) The encryption to use. Either 'none', 'ssl', or
+ * 'tls'.
+ * DEFAULT: 'none'
+ * 'userhierarchy' - (string) The hierarchy where user mailboxes are
+ * stored.
+ * DEFAULT: 'user.'
+ * </pre>
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
$params = array_merge(array(
'admin_password' => null,
'admin_user' => null,
'hostspec' => '',
- 'port' => '',
+ 'port' => null,
'secure' => 'none',
'userhierarchy' => 'user.'
), $params);
parent::__construct($params);
if (!empty($this->_params['admin_user'])) {
- $this->_capabilities['add'] = true;
- $this->_capabilities['remove'] = true;
- $this->_capabilities['list'] = true;
+ $this->_capabilities = array_merge($this->_capabilities, array(
+ 'add' => true,
+ 'list' => true,
+ 'remove' => true
+ ));
}
}
/**
* Get Horde_Imap_Client object.
*
+ * @param string $user Username.
+ * @param string $pass Password.
+ *
* @return Horde_Imap_Client_Base IMAP client object.
* @throws Horde_Exception
*/
protected function _getOb($user, $pass)
{
- if (!$this->_ob) {
+ $sig = hash('md5', serialize(array($user, $pass)));
+
+ if (!isset($this->_ob[$sig])) {
$imap_config = array(
'hostspec' => empty($this->_params['hostspec']) ? null : $this->_params['hostspec'],
'password' => $pass,
'username' => $user
);
- $this->_ob = Horde_Imap_Client::factory('Socket', $imap_config);
+ $this->_ob[$sig] = Horde_Imap_Client::factory('Socket', $imap_config);
}
- return $this->_ob;
+ return $this->_ob[$sig];
}
}
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Michael Rubinsky <mrubinsk@horde.org>
- * @package Horde_Auth
+ * @author Michael Rubinsky <mrubinsk@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
-class Horde_Auth_imsp extends Horde_Auth_Base
+class Horde_Auth_Imsp extends Horde_Auth_Base
{
/**
* Private authentication function.
* for times when you want a block of IPs to be able to access a site,
* and that access is simply on/off - no preferences, etc.
*
- * Optional Parameters:
- * <pre>
- * 'blocks' - (array) CIDR masks which are allowed access.
- * </pre>
- *
* Copyright 1999-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Ipbasic extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing parameters.
+ * @param array $params Optional Parameters:
+ * <pre>
+ * 'blocks' - (array) CIDR masks which are allowed access.
+ * </pre>
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
if (empty($params['blocks'])) {
$params['blocks'] = array();
*/
protected function _transparent()
{
- if (!isset($_SERVER['REMOTE_ADDR'])) {
- return false;
- }
-
- foreach ($this->_params['blocks'] as $cidr) {
- if ($this->_addressWithinCIDR($_SERVER['REMOTE_ADDR'], $cidr)) {
- $this->_credentials['userId'] = $cidr;
- return true;
+ if (isset($_SERVER['REMOTE_ADDR'])) {
+ foreach ($this->_params['blocks'] as $cidr) {
+ if ($this->_addressWithinCIDR($_SERVER['REMOTE_ADDR'], $cidr)) {
+ $this->_credentials['userId'] = $cidr;
+ return true;
+ }
}
}
*/
protected function _authenticate($userId, $credentials)
{
- throw new Horde_Auth_Exception('Not implemented!');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Stuart Binge <s.binge@codefusion.co.za>
- * @author Gunnar Wrobel <wrobel@pardus.de>
- * @package Horde_Auth
+ * @author Stuart Binge <s.binge@codefusion.co.za>
+ * @author Gunnar Wrobel <wrobel@pardus.de>
+ * @category Horde
+ * @package Auth
*/
class Horde_Auth_Kolab extends Horde_Auth_Base
{
* @var array
*/
protected $_capabilities = array(
- 'authenticate' => true,
- 'list' => true,
- /** @todo These would only work if we allow manager login */
- 'add' => false,
- 'remove' => false,
- 'update' => false
+ 'authenticate' => true
);
/**
+ * Constructor.
+ *
+ * @params array $params Parameters:
+ * <pre>
+ * 'kolab' - (Horde_Kolab_Session) [REQUIRED] TODO
+ * </pre>
+ *
+ * @throws InvalidArgumentException
+ */
+ public function __construct(array $params = array())
+ {
+ if (!isset($params['kolab'])) {
+ throw new InvalidArgumentException('Missing ' . $params . ' parameter.');
+ }
+
+ parent::__construct($params);
+ }
+
+ /**
* Find out if a set of login credentials are valid.
*
* For Kolab this requires to identify the IMAP server the user should
protected function _authenticate($userId, $credentials)
{
try {
- $session = $GLOBALS['injector']->getInstance('Horde_Kolab_Session');
- $session->connect($userId, $credentials);
+ $this->_params['kolab']->connect($userId, $credentials);
} catch (Horde_Kolab_Session_Exception_Badlogin $e) {
throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
} catch (Horde_Kolab_Session_Exception $e) {
- Horde::logMessage($e, 'ERR');
+ if ($this->_logger) {
+ $this->_logger->log($e, 'ERR');
+ }
throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
}
- $this->_credentials['userId'] = $session->getMail();
+ $this->_credentials['userId'] = $this->_params['kolab']->getMail();
return true;
-
-/* if (!isset($conf['auth']['params']) || */
-/* $conf['auth']['params']['login_block'] != 1) { */
-/* // Return if feature is disabled. */
-/* return $session->auth; */
-/* } */
-
-/* if ($session->auth !== true && */
-/* class_exists('Horde_History')) { */
-/* $history = $GLOBALS['injector']->getInstance('Horde_History'); */
-
-/* $history_identifier = "$userId@logins.kolab"; */
-/* $history_log = $history->getHistory($history_identifier); */
-/* $history_list = array(); */
-
-/* // Extract history list from log. */
-/* if ($history_log && !($history_log instanceof PEAR_Error)) { */
-/* $data = $history_log->getData(); */
-/* if (!empty($data)) { */
-/* $entry = array_shift($data); */
-/* $history_list = $entry['history_list']; */
-/* } */
-/* } */
-
-/* // Calculate the time range. */
-/* $start_time = (time() - $conf['auth']['params']['login_block_time'] * 60); */
-
-/* $new_history_list = array(); */
-/* $count = 0; */
-
-/* // Copy and count all relevant timestamps. */
-/* foreach ($history_list as $entry) { */
-/* $timestamp = $entry[ 'timestamp' ]; */
-
-/* if ($timestamp > $start_time) { */
-/* $new_history_list[] = $entry; */
-/* $count++; */
-/* } */
-/* } */
-
-/* $max_count = $conf['auth']['params']['login_block_count']; */
-
-/* if ($count > $max_count) { */
-/* // Add entry for current failed login. */
-/* $entry = array(); */
-/* $entry[ 'timestamp' ] = time(); */
-/* $new_history_list[] = $entry; */
-
-/* // Write back history. */
-/* $history->log($history_identifier, */
-/* array('action' => 'add', 'who' => $userId, */
-/* 'history_list' => $new_history_list), true); */
-
-/* if ($count > $max_count) { */
-/* throw new Horde_Auth_Exception(_("Too many invalid logins during the last minutes.")); */
-/* } */
-
-/* throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN); */
-/* } */
-/* } */
-
-/* return ($session->auth === true); */
}
-/* /\** */
-/* * List Users */
-/* * */
-/* * @return array List of Users */
-/* * @throws Horde_Auth_Exception */
-/* *\/ */
-/* public function listUsers() */
-/* { */
-/* $session = Horde_Kolab_Session_Singleton::singleton(); */
-/* $server = $session->getServer(); */
-/* if ($server instanceof PEAR_Error) { */
-/* return $server; */
-/* } */
-/* $users = $server->listObjects(KOLAB_OBJECT_USER); */
-/* $mails = array(); */
-/* foreach ($users as $user) { */
-/* $mails[] = $user->get(KOLAB_ATTR_MAIL); */
-/* } */
-
-/* return $mails; */
-/* } */
-
-/* /\** */
-/* * Add a set of authentication credentials. */
-/* * */
-/* * @param string $userId The userId to add. */
-/* * @param array $credentials The credentials to be set. */
-/* * */
-/* * @throws Horde_Auth_Exception */
-/* *\/ */
-/* public function addUser($userId, $credentials) */
-/* { */
-/* $session = Horde_Kolab_Session::singleton(); */
-/* $server = $session->getServer(); */
-/* if ($server instanceof PEAR_Error) { */
-/* return $server; */
-/* } */
-
-/* $result = $server->store(KOLAB_OBJECT_USER, $userId, $credentials); */
-
-/* if (is_a($result, KOLAB_OBJECT_USER)) { */
-/* return true; */
-/* } else if ($result instanceof PEAR_Error) { */
-/* return $result; */
-/* } */
-
-/* throw new Horde_Auth_Exception(sprintf('The new Kolab object is a %s rather than a ' . KOLAB_OBJECT_USER, get_class($result))); */
-/* } */
-
}
* The Horde_Auth_Ldap class provides an LDAP implementation of the Horde
* authentication system.
*
- * Required parameters:
- * <pre>
- * 'basedn' The base DN for the LDAP server.
- * 'hostspec' The hostname of the LDAP server.
- * 'uid' The username search key.
- * 'filter' The LDAP formatted search filter to search for users. This
- * setting overrides the 'objectclass' method below.
- * 'objectclass' The objectclass filter used to search for users. Can be a
- * single objectclass or an array.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'binddn' The DN used to bind to the LDAP server
- * 'password' The password used to bind to the LDAP server
- * 'version' The version of the LDAP protocol to use.
- * DEFAULT: NONE (system default will be used)
- * </pre>
- *
* 'preauthenticate' hook should return LDAP connection information in the
* 'ldap' credentials key.
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Jon Parise <jon@horde.org>
- * @package Horde_Auth
+ * @author Jon Parise <jon@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Ldap extends Horde_Auth_Base
{
);
/**
- * LDAP connection handle.
+ * LDAP object
*
- * @var resource
+ * @var Horde_Ldap
*/
- protected $_ds;
+ protected $_ldap;
/**
- * Construct.
+ * Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Required parameters:
+ * <pre>
+ * 'basedn' - (string) The base DN for the LDAP server.
+ * 'filter' - (string) The LDAP formatted search filter to search for
+ * users. This setting overrides the 'objectclass' method
+ * below.
+ * 'ldap' - (Horde_Ldap) Horde LDAP object.
+ * 'objectclass' - (mixed) The objectclass filter used to search for
+ * users. Can be a single objectclass or an array.
+ * 'uid' - (string) The username search key.
+ * </pre>
*
* @throws Horde_Auth_Exception
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- if (!Horde_Util::extensionExists('ldap')) {
- throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Required LDAP extension not found."));
- }
-
- /* Ensure we've been provided with all of the necessary parameters. */
- Horde::assertDriverConfig($params, 'auth',
- array('hostspec', 'basedn', 'uid'),
- 'authentication LDAP');
-
- parent::__construct($params);
- }
-
- /**
- * Does an ldap connect and binds as the guest user or as the optional dn.
- *
- * @throws Horde_Auth_Exception
- */
- protected function _connect()
- {
- /* Connect to the LDAP server. */
- $this->_ds = @ldap_connect($this->_params['hostspec']);
- if (!$this->_ds) {
- throw new Horde_Auth_Exception(_("Failed to connect to LDAP server."));
- }
-
- if (isset($this->_params['version'])) {
- if (!ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION,
- $this->_params['version'])) {
- Horde::logMessage(
- sprintf('Set LDAP protocol version to %d failed: [%d] %s',
- $this->_params['version'],
- @ldap_errno($this->_ds),
- @ldap_error($this->_ds)),
- 'ERR');
- }
- }
-
- /* Start TLS if we're using it. */
- if (!empty($this->_params['tls'])) {
- if (!@ldap_start_tls($this->_ds)) {
- Horde::logMessage(
- sprintf('STARTTLS failed: [%d] %s',
- @ldap_errno($this->_ds),
- @ldap_error($this->_ds)),
- 'ERR');
- }
- }
-
- /* Work around Active Directory quirk. */
- if (!empty($this->_params['ad'])) {
- if (!ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, false)) {
- Horde::logMessage(
- sprintf('Unable to disable directory referrals on this connection to Active Directory: [%d] %s',
- @ldap_errno($this->_ds),
- @ldap_error($this->_ds)),
- 'ERR');
+ foreach (array('basedn', 'filter', 'ldap', 'objectclass', 'uid') as $val) {
+ if (!isset($params[$val])) {
+ throw new InvalidArgumentException(__CLASS__ . ': Missing ' . $val . ' parameter.');
}
}
- $bind = isset($this->_params['binddn'])
- ? @ldap_bind($this->_ds, $this->_params['binddn'], $this->_params['password'])
- : @ldap_bind($this->_ds);
+ $this->_ldap = $params['ldap'];
+ unset($params['ldap']);
- if (!$bind) {
- throw new Horde_Auth_Exception(_("Could not bind to LDAP server."));
- }
+ parent::__construct($params);
}
/**
- * Find the user dn
+ * Find the user dn.
*
* @param string $userId The userId to find.
*
- * @return string The users full DN
+ * @return string The user's full DN
* @throws Horde_Auth_Exception
*/
protected function _findDN($userId)
$filter = '(&(' . $this->_params['uid'] . '=' . $userId . ')' .
$filter . ')';
- $func = ($this->_params['scope'] == 'one')
- ? 'ldap_list'
- : 'ldap_search';
-
- $search = @$func($this->_ds, $this->_params['basedn'], $filter,
- array($this->_params['uid']));
- if (!$search) {
- Horde::logMessage(ldap_error($this->_ds), 'ERR');
- throw new Horde_Auth_Exception(_("Could not search the LDAP server."));
+ try {
+ $search = $this->_ldap->search(null, $filter, array('attributes' => array($this->_params['uid'])));
+ } catch (Horde_Ldap_Exception $e) {
+ throw new Horde_Auth_Exception('Could not search the LDAP server.');
}
- $result = @ldap_get_entries($this->_ds, $search);
- if (is_array($result) && (count($result) > 1)) {
- $dn = $result[0]['dn'];
- } else {
- throw new Horde_Auth_Exception(_("Empty result."));
+ if (!$search->count()) {
+ throw new Horde_Auth_Exception('Empty result.');
}
- return $dn;
+ return $search[0]['dn'];
}
/**
* pwdlastset: Active Directory
* shadow*: shadowUser schema
* passwordexpirationtime: Sun and Fedora Directory Server */
- $result = @ldap_read($this->_ds, $dn, '(objectClass=*)',
- array('pwdlastset', 'shadowmax', 'shadowmin',
- 'shadowlastchange', 'shadowwarning',
- 'passwordexpirationtime'));
- if ($result) {
- $information = @ldap_get_entries($this->_ds, $result);
-
- if ($this->_params['ad']) {
- if (isset($information[0]['pwdlastset'][0])) {
- /* Active Directory handles timestamps a bit differently.
- * Convert the timestamp to a UNIX timestamp. */
- $lookupshadow['shadowlastchange'] = floor((($information[0]['pwdlastset'][0] / 10000000) - 11644406783) / 86400) - 1;
-
- /* Password expiry attributes are in a policy. We cannot
- * read them so use the Horde config. */
- $lookupshadow['shadowwarning'] = $this->_params['warnage'];
- $lookupshadow['shadowmin'] = $this->_params['minage'];
- $lookupshadow['shadowmax'] = $this->_params['maxage'];
- }
- } elseif (isset($information[0]['passwordexpirationtime'][0])) {
- /* Sun/Fedora Directory Server uses a special attribute
- * passwordexpirationtime. It has precedence over shadow*
- * because it actually locks the expired password at the LDAP
- * server level. The correct way to check expiration should
- * be using LDAP controls, unfortunately PHP doesn't support
- * controls on bind() responses. */
- $ldaptimepattern = "/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})Z/";
- if (preg_match($ldaptimepattern, $information[0]['passwordexpirationtime'][0], $regs)) {
- /* Sun/Fedora Directory Server return expiration time, not
- * last change time. We emulate the behaviour taking it
- * back to maxage. */
- $lookupshadow['shadowlastchange'] = floor(mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]) / 86400) - $this->_params['maxage'];
-
- /* Password expiry attributes are in not accessible policy
- * entry. */
- $lookupshadow['shadowwarning'] = $this->_params['warnage'];
- $lookupshadow['shadowmin'] = $this->_params['minage'];
- $lookupshadow['shadowmax'] = $this->_params['maxage'];
- } else {
- Horde::logMessage('Wrong time format: ' . $information[0]['passwordexpirationtime'][0], 'ERR');
- }
- } else {
- if (isset($information[0]['shadowmax'][0])) {
- $lookupshadow['shadowmax'] =
- $information[0]['shadowmax'][0];
- }
- if (isset($information[0]['shadowmin'][0])) {
- $lookupshadow['shadowmin'] =
- $information[0]['shadowmin'][0];
- }
- if (isset($information[0]['shadowlastchange'][0])) {
- $lookupshadow['shadowlastchange'] =
- $information[0]['shadowlastchange'][0];
- }
- if (isset($information[0]['shadowwarning'][0])) {
- $lookupshadow['shadowwarning'] =
- $information[0]['shadowwarning'][0];
- }
+ try {
+ $result = $this->_ldap->search(null, '(objectClass=*)', array(
+ 'attributes' => array(
+ 'pwdlastset',
+ 'shadowmax',
+ 'shadowmin',
+ 'shadowlastchange',
+ 'shadowwarning',
+ 'passwordexpirationtime'
+ ),
+ 'scope' => 'base'
+ ));
+ } catch (Horde_Ldap_Exception $e) {
+ return $lookupshadow;
+ }
+
+ if (!$result) {
+ return $lookupshadow;
+ }
+
+ $info = reset($result);
+
+ // TODO: 'ad'?
+ if ($this->_params['ad']) {
+ if (isset($info['pwdlastset'][0])) {
+ /* Active Directory handles timestamps a bit differently.
+ * Convert the timestamp to a UNIX timestamp. */
+ $lookupshadow['shadowlastchange'] = floor((($info['pwdlastset'][0] / 10000000) - 11644406783) / 86400) - 1;
+
+ /* Password expiry attributes are in a policy. We cannot
+ * read them so use the Horde config. */
+ $lookupshadow['shadowwarning'] = $this->_params['warnage'];
+ $lookupshadow['shadowmin'] = $this->_params['minage'];
+ $lookupshadow['shadowmax'] = $this->_params['maxage'];
+ }
+ } elseif (isset($info['passwordexpirationtime'][0])) {
+ /* Sun/Fedora Directory Server uses a special attribute
+ * passwordexpirationtime. It has precedence over shadow*
+ * because it actually locks the expired password at the LDAP
+ * server level. The correct way to check expiration should
+ * be using LDAP controls, unfortunately PHP doesn't support
+ * controls on bind() responses. */
+ $ldaptimepattern = "/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})Z/";
+ if (preg_match($ldaptimepattern, $info['passwordexpirationtime'][0], $regs)) {
+ /* Sun/Fedora Directory Server return expiration time, not
+ * last change time. We emulate the behaviour taking it
+ * back to maxage. */
+ $lookupshadow['shadowlastchange'] = floor(mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]) / 86400) - $this->_params['maxage'];
+
+ /* Password expiry attributes are in not accessible policy
+ * entry. */
+ $lookupshadow['shadowwarning'] = $this->_params['warnage'];
+ $lookupshadow['shadowmin'] = $this->_params['minage'];
+ $lookupshadow['shadowmax'] = $this->_params['maxage'];
+ } elseif ($this->_logger) {
+ $this->_logger->log('Wrong time format: ' . $info['passwordexpirationtime'][0], 'ERR');
+ }
+ } else {
+ if (isset($info['shadowmax'][0])) {
+ $lookupshadow['shadowmax'] = $info['shadowmax'][0];
+ }
+ if (isset($info['shadowmin'][0])) {
+ $lookupshadow['shadowmin'] = $info['shadowmin'][0];
+ }
+ if (isset($info['shadowlastchange'][0])) {
+ $lookupshadow['shadowlastchange'] = $info['shadowlastchange'][0];
+ }
+ if (isset($info['shadowwarning'][0])) {
+ $lookupshadow['shadowwarning'] = $info['shadowwarning'][0];
}
}
*/
protected function _authenticate($userId, $credentials)
{
- /* Connect to the LDAP server. */
- $this->_connect();
-
/* Search for the user's full DN. */
$dn = $this->_findDN($userId);
/* Attempt to bind to the LDAP server as the user. */
- $bind = @ldap_bind($this->_ds, $dn, $credentials['password']);
- if ($bind == false) {
- @ldap_close($this->_ds);
+ $bind = clone $this->_ldap;
+ try {
+ if (!$bind->bind($dn, $credentials['password'])) {
+ throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
+ }
+ } catch (Horde_Ldap_Exception $e) {
throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
}
if ($shadow['shadowmax'] && $shadow['shadowlastchange'] &&
$shadow['shadowwarning']) {
$today = floor(time() / 86400);
- $warnday = $shadow['shadowlastchange'] +
- $shadow['shadowmax'] - $shadow['shadowwarning'];
$toexpire = $shadow['shadowlastchange'] +
$shadow['shadowmax'] - $today;
- if ($today >= $warnday) {
- $GLOBALS['notification']->push(sprintf(ngettext("%d day until your password expires.", "%d days until your password expires.", $toexpire), $toexpire), 'horde.warning');
+ if ($this->_params['notify_expire']) {
+ $warnday = $shadow['shadowlastchange'] +
+ $shadow['shadowmax'] - $shadow['shadowwarning'];
+ if ($today >= $warnday) {
+ call_user_func($this->_params['notify_expire'], $toexpire);
+ }
}
if ($toexpire == 0) {
}
}
}
-
- @ldap_close($this->_ds);
}
/**
public function addUser($userId, $credentials)
{
if ($this->_params['ad']) {
- throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Adding users is not supported for Active Directory"));
+ throw new Horde_Auth_Exception(__CLASS__ . ': Adding users is not supported for Active Directory.');
}
- /* Connect to the LDAP server. */
- $this->_connect();
-
list($userId, $credentials) = Horde_Auth::runHook($userId, $credentials, $this->_app, 'preauthenticate', 'admin');
if (isset($credentials['ldap'])) {
$entry = $credentials['ldap'];
}
}
- $result = @ldap_add($this->_ds, $dn, $entry);
-
- if (!$result) {
- throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Ldap: Unable to add user \"%s\". This is what the server said: "), $userId) . @ldap_error($this->_ds));
+ try {
+ $this->_ldap->add(Horde_Ldap_Entry::createFresh($dn, $entry));
+ } catch (Horde_Ldap_Exception $e) {
+ throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to add user "%s". This is what the server said: ', $userId) . $e->getMessage());
}
-
- @ldap_close($this->_ds);
}
/**
public function removeUser($userId)
{
if ($this->_params['ad']) {
- throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Removing users is not supported for Active Directory"));
+ throw new Horde_Auth_Exception(__CLASS__ . ': Removing users is not supported for Active Directory');
}
- /* Connect to the LDAP server. */
- $this->_connect();
-
list($userId, $credentials) = Horde_Auth::runHook($userId, array(), $this->_app, 'preauthenticate', 'admin');
if (isset($credentials['ldap'])) {
$dn = $credentials['ldap']['dn'];
$dn = $this->_findDN($userId);
}
- $result = @ldap_delete($this->_ds, $dn);
- if (!$result) {
- throw new Horde_Auth_Exception(sprintf(_("Auth_ldap: Unable to remove user \"%s\""), $userId));
+ try {
+ $this->_ldap->delete($dn);
+ } catch (Horde_Ldap_Exception $e) {
+ throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to remove user "%s"', $userId));
}
- @ldap_close($this->_ds);
-
Horde_Auth::removeUserData($userId);
}
public function updateUser($oldID, $newID, $credentials)
{
if ($this->_params['ad']) {
- throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Updating users is not supported for Active Directory."));
+ throw new Horde_Auth_Exception(__CLASS__ . ': Updating users is not supported for Active Directory.');
}
- /* Connect to the LDAP server. */
- $this->_connect();
-
list($oldID, $old_credentials) = Horde_Auth::runHook($oldID, $credentials, $this->_app, 'preauthenticate', 'admin');
if (isset($old_credentials['ldap'])) {
$olddn = $old_credentials['ldap']['dn'];
if ($shadow['shadowlastchange'] &&
$shadow['shadowmin'] &&
($shadow['shadowlastchange'] + $shadow['shadowmin'] > (time() / 86400))) {
- throw new Horde_Auth_Exception(_("Minimum password age has not yet expired"));
+ throw new Horde_Auth_Exception('Minimum password age has not yet expired');
}
/* Set the lastchange field */
'true');
}
- if ($oldID != $newID) {
- if (LDAP_OPT_PROTOCOL_VERSION == 3) {
- ldap_rename($this->_ds, $olddn, $newdn,
- $this->_params['basedn'], true);
-
- $result = ldap_modify($this->_ds, $newdn, $entry);
+ try {
+ if ($oldID != $newID) {
+ $this->_ldap->move($olddn, $newdn);
+ $this->_ldap->modify($newdn, $entry);
} else {
- /* Get the complete old record first */
- $result = @ldap_read($this->_ds, $olddn, 'objectClass=*');
-
- if ($result) {
- $information = @ldap_get_entries($this->_ds, $result);
-
- /* Remove the count elements from the array */
- $counter = 0;
- $newrecord = array();
- while (isset($information[0][$counter])) {
- if ($information[0][$information[0][$counter]]['count'] == 1) {
- $newrecord[$information[0][$counter]] = $information[0][$information[0][$counter]][0];
- } else {
- $newrecord[$information[0][$counter]] = $information[0][$information[0][$counter]];
- unset($newrecord[$information[0][$counter]]['count']);
- }
- $counter++;
- }
-
- /* Adjust the changed parameters */
- unset($newrecord['dn']);
- $newrecord[$this->_params['uid']] = $newID;
- $newrecord['userpassword'] = $entry['userpassword'];
- if (isset($entry['shadowlastchange'])) {
- $newrecord['shadowlastchange'] = $entry['shadowlastchange'];
- }
-
- $result = ldap_add($this->_ds, $newdn, $newrecord);
- if ($result) {
- $result = @ldap_delete($this->_ds, $olddn);
- }
- }
+ $this->_ldap->modify($olddn, $entry);
}
- } else {
- $result = @ldap_modify($this->_ds, $olddn, $entry);
+ } catch (Horde_Ldap_Exception $e) {
+ throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to update user "%s"', $newID));
}
-
- if (!$result) {
- throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Ldap: Unable to update user \"%s\""), $newID));
- }
-
- @ldap_close($this->_ds);
}
/**
*/
public function listUsers()
{
- /* Connect to the LDAP server. */
- $this->_connect();
-
$filter = $this->_getParamFilter();
- $func = ($this->_params['scope'] == 'one')
- ? 'ldap_list'
- : 'ldap_search';
+ $params = array(
+ 'attributes' => array($this->_params['uid']),
+ 'scope' => $this->_params['scope'],
+ 'sizelimit' => isset($this->_params['sizelimit']) ? $this->_params['sizelimit'] : 0
+ );
/* Add a sizelimit, if specified. Default is 0, which means no limit.
* Note: You cannot override a server-side limit with this. */
- $sizelimit = isset($this->_params['sizelimit']) ? $this->_params['sizelimit'] : 0;
- $search = @$func($this->_ds, $this->_params['basedn'], $filter,
- array($this->_params['uid']), 0, $sizelimit);
-
- $entries = @ldap_get_entries($this->_ds, $search);
$userlist = array();
- $uid = Horde_String::lower($this->_params['uid']);
- for ($i = 0; $i < $entries['count']; $i++) {
- $userlist[$i] = $entries[$i][$uid][0];
- }
+ try {
+ $search = $this->_ldap->search($this->_params['basedn'], $filter, $params);
+
+ $uid = Horde_String::lower($this->_params['uid']);
+ foreach ($search as $val) {
+ $userlist[] = $val[$uid][0];
+ }
+ } catch (Horde_Ldap_Exception $e) {}
return $userlist;
}
}
return $filter;
}
+
}
/**
* The Horde_Auth_login:: class provides a system login implementation of
* the Horde authentication system.
+ *
* This Auth driver is useful if you have a shadow password system
* where the Horde_Auth_Passwd driver doesn't work.
*
- * Optional parameters:
- * <pre>
- * 'location' - (string) Location of the su binary.
- * DEFAULT: /bin/su
- * </pre>
- *
* Copyright 2004-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Jan Schneider <jan@horde.org>
- * @package Horde_Auth
+ * @author Jan Schneider <jan@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Login extends Horde_Auth_Base
{
/**
* Constructs a new Login authentication object.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Optional parameters:
+ * <pre>
+ * 'location' - (string) Location of the su binary.
+ * DEFAULT: /bin/su
+ * </pre>
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
if (empty($params['location'])) {
$params['location'] = '/bin/su';
* The Horde_Auth_Msad class provides an experimental MSAD extension of the
* LDAP implementation of the Horde authentication system.
*
- * Required parameters: See Horde_Auth_Ldap.
- *
- * Optional parameters: See Horde_Auth_Ldap.
- *
* Copyright 2007-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Francois Helly <fhelly@bebop-design.net>
- * @package Horde_Auth
+ * @author Francois Helly <fhelly@bebop-design.net>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Msad extends Horde_Auth_Ldap
{
*/
public function __construct($params = array())
{
- if (!Horde_Util::extensionExists('ldap')) {
- throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Required LDAP extension not found."));
- }
-
$params = array_merge(array(
'adduser' => true,
'authId' => 'initials',
}
/* Ensure we've been provided with all of the necessary parameters. */
- Horde::assertDriverConfig($params, 'auth',
- array('hostspec', 'basedn'), 'authentication MSAD');
+ //Horde::assertDriverConfig($params, 'auth',
+ // array('hostspec', 'basedn'), 'authentication MSAD');
- $this->_params = $params;
/* Adjust capabilities: depending on if SSL encryption is
* enabled or not */
$this->_capabilities = array(
$success = @ldap_add($this->_ds, $dn, $entry);
if (!$success) {
- throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Msad: Unable to add user \"%s\". This is what the server said: "), $accountName) . ldap_error($this->_ds));
+ throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to add user "%s". This is what the server said: ', $accountName) . ldap_error($this->_ds));
}
@ldap_close($this->_ds);
}
if (!@ldap_delete($this->_ds, $dn)) {
- throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Msad: Unable to remove user \"%s\""), $accountName));
+ throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to remove user "%s"', $accountName));
}
@ldap_close($this->_ds);
}
if (!$success) {
- throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Msad: Unable to update user \"%s\""), $newID), __FILE__, __LINE__);
+ throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to update user "%s"', $newID));
}
@ldap_close($this->_ds);
/* Get a new random password. */
$password = Horde_Auth::genRandomPassword() . '/';
$this->updateUser($user_id, $user_id, array('userPassword' => $password));
+
return $password;
}
$ssl = ($this->_params['ssl']) ? 'ldaps://' : '';
$this->_ds = ldap_connect($ssl . $this->_params['hostspec'], $this->_params['port']);
if (!$this->_ds) {
- throw new Horde_Auth_Exception(_("Failed to connect to MSAD server."));
+ throw new Horde_Auth_Exception('Failed to connect to MSAD server.');
}
- if (!ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
- Horde::logMessage(
- sprintf('Set MSAD protocol version to %d failed: [%d] %s',
- 3,
- ldap_errno($conn),
- ldap_error($conn),
- __FILE__, __LINE__));
- }
- if (!ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, 0)) {
- Horde::logMessage(
- sprintf('Set MSAD referrals option to %d failed: [%d] %s',
- 0,
- ldap_errno($conn),
- ldap_error($conn),
- __FILE__, __LINE__));
+ if ($this->_logger) {
+ if (!ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
+ $this->_logger->log(sprintf('Set MSAD protocol version to %d failed: [%d] %s', 3, ldap_errno($conn), ldap_error($conn)));
+ }
+ if (!ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, 0)) {
+ $this->_logger->log(sprintf('Set MSAD referrals option to %d failed: [%d] %s', 0, ldap_errno($conn), ldap_error($conn)));
+ }
}
if (isset($this->_params['binddn'])) {
}
if (!$bind) {
- throw new Horde_Auth_Exception(_("Could not bind to MSAD server."));
+ throw new Horde_Auth_Exception('Could not bind to MSAD server.');
}
-
- return true;
}
/**
);
/* Searching the tree is not successful */
if (!$search) {
- throw new Horde_Auth_Exception(_("Could not search the MSAD server."));
+ throw new Horde_Auth_Exception('Could not search the MSAD server.');
}
/* Fetch the search result */
}
if (!is_array($result) || (count($result) <= 1)) {
- throw new Horde_Auth_Exception(_("Empty result."));
+ throw new Horde_Auth_Exception('Empty result.');
}
/* Be sure the horde userId is the configured one */
*
* http://pecl.php.net/package/PAM
*
- * Optional parameters:
- * <pre>
- * 'service' - (string) The name of the PAM service to use when
- * authenticating.
- * DEFAULT: php
- * </pre>
- *
* Copyright 2004-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Jon Parise <jon@horde.org>
- * @package Horde_Auth
+ * @author Jon Parise <jon@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Pam extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Optional parameters:
+ * <pre>
+ * 'service' - (string) The name of the PAM service to use when
+ * authenticating.
+ * DEFAULT: php
+ * </pre>
*
* @throws Horde_Auth_Exception
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- if (!Horde_Util::extensionExists('pam_auth') && !Horde_Util::extensionExists('pam')) {
- throw new Horde_Auth_Exception(_("PAM authentication is not available."));
+ if (!Horde_Util::extensionExists('pam_auth') &&
+ !Horde_Util::extensionExists('pam')) {
+ throw new Horde_Auth_Exception('PAM authentication is not available.');
}
if (!empty($params['service'])) {
* The Horde_Auth_Passwd:: class provides a passwd-file implementation of
* the Horde authentication system.
*
- * Required parameters:
- * <pre>
- * 'filename' - (string) The passwd file to use.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'encryption' The encryption to use to store the password in
- * the table (e.g. plain, crypt, md5-hex,
- * md5-base64, smd5, sha, ssha, aprmd5).
- * DEFAULT: 'crypt-des'
- * 'lock' Should we lock the passwd file? (boolean) The password
- * file cannot be changed (add, edit, or delete users)
- * unless this is true.
- * DEFAULT: false<
- * 'show_encryption' Whether or not to prepend the encryption in the
- * password field.
- * DEFAULT: 'false'
- * </pre>
- *
* Copyright 1997-2007 Rasmus Lerdorf <rasmus@php.net>
* Copyright 2002-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Rasmus Lerdorf <rasmus@php.net>
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author Rasmus Lerdorf <rasmus@php.net>
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Passwd extends Horde_Auth_Base
{
/**
* Filehandle for lockfile.
*
- * @var integer
+ * @var resource
*/
protected $_fplock;
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Connection parameters:
+ * <pre>
+ * 'encryption' - (string) The encryption to use to store the password in
+ * the table (e.g. plain, crypt, md5-hex, md5-base64, smd5,
+ * sha, ssha, aprmd5).
+ * DEFAULT: 'crypt-des'
+ * 'filename' - (string) [REQUIRED] The passwd file to use.
+ * 'lock' - (boolean) Should we lock the passwd file? The password file
+ * cannot be changed (add, edit, or delete users) unless this is
+ * true.
+ * DEFAULT: false
+ * 'show_encryption' - (boolean) Whether or not to prepend the encryption
+ * in the password field.
+ * DEFAULT: false
+ * </pre>
+ *
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
+ if (!isset($params['filename'])) {
+ throw new InvalidArgumentException('Missing filename parameter.');
+ }
+
$params = array_merge(array(
'encryption' => 'crypt-des',
'lock' => false,
{
if ($this->_locked) {
foreach ($this->_users as $user => $pass) {
+ $data = $user . ':' . $pass;
if ($this->_users[$user]) {
- fputs($this->_fplock, "$user:$pass:" . $this->_users[$user] . "\n");
- } else {
- fputs($this->_fplock, "$user:$pass\n");
+ $data .= ':' . $this->_users[$user];
}
+ fputs($this->_fplock, $data . "\n");
}
rename($this->_lockfile, $this->_params['filename']);
flock($this->_fplock, LOCK_UN);
try {
$this->_read();
} catch (Horde_Auth_Exception $e) {
- Horde::logMessage($e, 'ERR');
+ if ($this->_logger) {
+ $this->_logger->log($e, 'ERR');
+ }
throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
}
/* Get a new random password. */
$password = Horde_Auth::genRandomPassword();
$this->updateUser($userId, $userId, array('password' => $password));
+
return $password;
}
* connection-based protocols.
*
* This driver relies on the PECL sasl package:
- *
- * http://pecl.php.net/package/sasl
- *
- * Optional parameters:
- * <pre>
- * 'app' The name of the authenticating application.
- * DEFAULT: horde
- * 'service' The name of the SASL service to use when authenticating.
- * DEFAULT: php
- * </pre>
+ * http://pecl.php.net/package/sasl
*
* Copyright 2004-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Jon Parise <jon@horde.org>
- * @package Horde_Auth
+ * @author Jon Parise <jon@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Peclsasl extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Optional parameters:
+ * <pre>
+ * 'app' - (string) The name of the authenticating application.
+ * DEFAULT: horde
+ * 'service' - (string) The name of the SASL service to use when
+ * authenticating.
+ * DEFAULT: php
+ * </pre>
*
* @throws Horde_Auth_Exception
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
if (!Horde_Util::extensionExists('sasl')) {
throw new Horde_Auth_Exception('Horde_Auth_Peclsasl:: requires the sasl PECL extension to be loaded.');
$conn = sasl_server_new($this->_params['service']);
if (!is_resource($conn)) {
- throw new Horde_Auth_Exception(_("Failed to create new SASL connection."));
+ throw new Horde_Auth_Exception('Failed to create new SASL connection.');
}
if (!sasl_checkpass($conn, $userId, $credentials['password'])) {
* This class requires the 'radius' PECL extension:
* http://pecl.php.net/package/radius
*
- * On *nix-y machines, this extension can be installed as follows:
- * <pre>
- * pecl install radius
- * </pre>
- *
- * Then, edit your php.ini file and make sure the following line is present:
- * <pre>
- * For Windows machines: extension=php_radius.dll
- * For all others: extension=radius.so
- * </pre>
- *
- * Required parameters:
- * <pre>
- * 'host' - (string) The RADIUS host to use (IP address or fully qualified
- * hostname).
- * 'method' - (string) The RADIUS method to use for validating the request.
- * Either: 'PAP', 'CHAP_MD5', 'MSCHAPv1', or 'MSCHAPv2'.
- * ** CURRENTLY, only 'PAP' is supported. **
- * 'secret' - (string) The RADIUS shared secret string for the host. The
- * RADIUS protocol ignores all but the leading 128 bytes
- * of the shared secret.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'nas' - (string) The RADIUS NAS identifier to use.
- * DEFAULT: The value of $_SERVER['HTTP_HOST'] or, if not
- * defined, then 'localhost'.
- * 'port' - (integer) The port to use on the RADIUS server.
- * DEFAULT: Whatever the local system identifies as the
- * 'radius' UDP port
- * 'retries' - (integer) The maximum number of repeated requests to make
- * before giving up.
- * DEFAULT: 3
- * 'suffix' - (string) The domain name to add to unqualified user names.
- * DEFAULT: NONE
- * 'timeout' - (integer) The timeout for receiving replies from the server (in
- * seconds).
- * DEFAULT: 3
- * </pre>
- *
* Copyright 2002-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Michael Slusarz <slusarz@horde.org>
- * @package Horde_Auth
+ * @author Michael Slusarz <slusarz@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Radius extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Connection parameters.
+ * <pre>
+ * 'host' - (string) [REQUIRED] The RADIUS host to use (IP address or
+ * fully qualified hostname).
+ * 'method' - (string) [REQUIRED] The RADIUS method to use for validating
+ * the request.
+ * Either: 'PAP', 'CHAP_MD5', 'MSCHAPv1', or 'MSCHAPv2'.
+ * ** CURRENTLY, only 'PAP' is supported. **
+ * 'nas' - (string) The RADIUS NAS identifier to use.
+ * DEFAULT: The value of $_SERVER['HTTP_HOST'] or, if not
+ * defined, then 'localhost'.
+ * 'port' - (integer) The port to use on the RADIUS server.
+ * DEFAULT: Whatever the local system identifies as the
+ * 'radius' UDP port
+ * 'retries' - (integer) The maximum number of repeated requests to make
+ * before giving up.
+ * DEFAULT: 3
+ * 'secret' - (string) [REQUIRED] The RADIUS shared secret string for the
+ * host. The RADIUS protocol ignores all but the leading 128
+ * bytes of the shared secret.
+ * 'suffix' - (string) The domain name to add to unqualified user names.
+ * DEFAULT: NONE
+ * 'timeout' - (integer) The timeout for receiving replies from the server
+ * (in seconds).
+ * DEFAULT: 3
+ * </pre>
*
- * @throws Horde_Auth_Exception
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- parent::__construct($params);
-
if (!Horde_Util::extensionExists('radius')) {
- throw new Horde_Auth_Exception('Horde_Auth_Radius:: requires the radius PECL extension to be loaded.');
- }
-
- /* A RADIUS host is required. */
- if (empty($this->_params['host'])) {
- throw new Horde_Auth_Exception('Horde_Auth_Radius:: requires a RADIUS host to connect to.');
- }
-
- /* A RADIUS secret string is required. */
- if (empty($this->_params['secret'])) {
- throw new Horde_Auth_Exception('Horde_Auth_Radius:: requires a RADIUS secret string.');
- }
-
- /* A RADIUS authentication method is required. */
- if (empty($this->_params['method'])) {
- throw new Horde_Auth_Exception('Horde_Auth_Radius:: requires a RADIUS authentication method.');
- }
-
- /* RADIUS NAS Identifier. */
- if (empty($this->_params['nas'])) {
- $this->_params['nas'] = isset($_SERVER['HTTP_HOST'])
- ? $_SERVER['HTTP_HOST']
- : 'localhost';
+ throw new Horde_Auth_Exception(__CLASS__ . ': requires the radius PECL extension to be loaded.');
}
- /* Suffix to add to unqualified user names. */
- if (empty($this->_params['suffix'])) {
- $this->_params['suffix'] = '';
+ foreach (array('host', 'secret', 'method') as $val) {
+ if (!isset($params[$val])) {
+ throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+ }
}
- /* The RADIUS port to use. */
- if (empty($this->_params['port'])) {
- $this->_params['port'] = 0;
- }
-
- /* Maximum number of retries. */
- if (empty($this->_params['retries'])) {
- $this->_params['retries'] = 3;
- }
+ $params = array_merge(array(
+ 'nas' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'),
+ 'port' => 0,
+ 'retries' => 3,
+ 'suffix' => '',
+ 'timeout' => 3
+ ), $params);
- /* RADIUS timeout. */
- if (empty($this->_params['timeout'])) {
- $this->_params['timeout'] = 3;
- }
+ parent::__construct($params);
}
/**
{
/* Password is required. */
if (!isset($credentials['password'])) {
- throw new Horde_Auth_Exception(_("Password required for RADIUS authentication."));
+ throw new Horde_Auth_Exception('Password required for RADIUS authentication.');
}
$res = radius_auth_open();
break;
case RADIUS_ACCESS_REJECT:
- throw new Horde_Auth_Exception(_("Authentication rejected by RADIUS server."));
+ throw new Horde_Auth_Exception('Authentication rejected by RADIUS server.');
default:
throw new Horde_Auth_Exception(radius_strerror($res));
* not provide any actual SP functionality, it just takes the username
* from the HTTP headers that should be set by the Shibboleth SP.
*
- * Required Parameters:
- * <pre>
- * 'username_header' - (string) Name of the header holding the username of the
- * logged in user.
- * </pre>
- *
- * Optional Parameters:
- * <pre>
- * 'password_header' - (string) Name of the header holding the password of the
- * logged in user.
- * 'password_holder' - (string) Where the hordeauth password is stored.
- * 'password_preference' - (string) Name of the Horde preference holding the
- * password of the logged in user.
- * </pre>
- *
* Copyright 9Star Research, Inc. 2006 http://www.protectnetwork.org/
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Cassio Nishiguchi <cassio@protectnetwork.org>
- * @package Horde_Auth
+ * @author Cassio Nishiguchi <cassio@protectnetwork.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Shibboleth extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing parameters.
+ * @param array $params Parameters:
+ * <pre>
+ * 'password_header' - (string) Name of the header holding the password of
+ * the logged in user.
+ * 'password_holder' - (string) Where the hordeauth password is stored.
+ * 'password_preference' - (string) Name of the Horde preference holding
+ * the password of the logged in user.
+ * 'username_header' - (string) [REQUIRED] Name of the header holding the
+ * username of the logged in user.
+ * </pre>
+ *
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- Horde::assertDriverConfig($params, 'auth', array('username_header'), 'authentication Shibboleth');
+ if (!isset($params['username_header'])) {
+ throw new InvalidArgumentException('Missing username_header parameter.');
+ }
$params = array_merge(array(
'password_header' => '',
*/
protected function _authenticate($userId, $credentials)
{
- throw new Horde_Auth_Exception('Not implemented!');
+ throw new Horde_Auth_Exception('Unsupported.');
}
/**
protected function _removeScope($username)
{
$pos = strrpos($username, '@');
- if ($pos !== false) {
- $username = substr($username, 0, $pos);
- }
- return $username;
+
+ return ($pos !== false)
+ ? substr($username, 0, $pos)
+ : $username;
}
}
* and not equal to each other. In other words, to use this module you must
* have a domain with at least one PDC and one BDC.
*
- * Required parameters:
- * <pre>
- * 'hostspec' - IP, DNS Name, or NetBios Name of the SMB server to
- * authenticate with.
- * 'domain' - The domain name to authenticate with.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'group' - Group name that the user must be a member of. Will be
- * ignored if the value passed is a zero length string.
- * </pre>
- *
* Copyright 1999-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Jon Parise <jon@horde.org>
- * @author Marcus I. Ryan <marcus@riboflavin.net>
- * @package Horde_Auth
+ * @author Jon Parise <jon@horde.org>
+ * @author Marcus I. Ryan <marcus@riboflavin.net>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Smb extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Parameters:
+ * <pre>
+ * 'domain' - (string) [REQUIRED] The domain name to authenticate with.
+ * 'group' - Group name that the user must be a member of.
+ * DEFAULT: none
+ * 'hostspec' - (string) [REQUIRED] IP, DNS Name, or NetBios name of the
+ * SMB server to authenticate with.
+ * </pre>
*
* @throws Horde_Auth_Exception
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
if (!Horde_Util::extensionExists('smbauth')) {
- throw new Horde_Auth_Exception(_("Horde_Auth_Smb: Required smbauth extension not found."));
+ throw new Horde_Auth_Exception(__CLASS__ . ': Required smbauth extension not found.');
+ }
+
+ foreach (array('domain', 'hostspec') as $val) {
+ throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
}
- /* Ensure we've been provided with all of the necessary parameters. */
- Horde::assertDriverConfig($params, 'auth',
- array('hostspec', 'domain'),
- 'authentication Samba');
+ $params = array_merge(array(
+ 'group' => null
+ ), $params);
parent::__construct($params);
}
$credentials['password']);
if ($rval === 1) {
- throw new Horde_Auth_Exception(_("Failed to connect to SMB server."));
+ throw new Horde_Auth_Exception('Failed to connect to SMB server.');
} elseif ($rval !== 0) {
throw new Horde_Auth_Exception(err2str());
}
* The Horde_Auth_Smbclient class provides an smbclient implementation of
* the Horde authentication system.
*
- * Required parameters:
- * <pre>
- * 'domain' The domain name to authenticate with.
- * 'hostspec' IP, DNS Name, or NetBios Name of the SMB server to
- * authenticate with.
- * 'smbclient_path' The location of the smbclient(1) utility.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'group' - Group name that the user must be a member of. Will be
- * ignored if the value passed is a zero length string.
- * </pre>
- *
* Copyright 1999-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Jon Parise <jon@horde.org>
- * @author Marcus I. Ryan <marcus@riboflavin.net>
- * @package Horde_Auth
+ * @author Jon Parise <jon@horde.org>
+ * @author Marcus I. Ryan <marcus@riboflavin.net>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Smbclient extends Horde_Auth_Base
{
/**
* Constructor.
*
- * @param array $params A hash containing connection parameters.
+ * @param array $params Parameters:
+ * <pre>
+ * 'domain' - (string) [REQUIRED] The domain name to authenticate with.
+ * 'group' - Group name that the user must be a member of.
+ * DEFAULT: none
+ * 'hostspec' - (string) [REQUIRED] IP, DNS Name, or NetBios name of the
+ * SMB server to authenticate with.
+ * 'smbclient_path' - (string) [REQUIRED] The location of the smbclient
+ * utility.
+ * </pre>
+ *
+ * @throws InvalidArgumentException
*/
- public function __construct($params = array())
+ public function __construct(array $params = array())
{
- /* Ensure we've been provided with all of the necessary parameters. */
- Horde::assertDriverConfig($params, 'auth',
- array('hostspec', 'domain', 'smbclient_path'),
- 'authentication smbclient');
+ foreach (array('hostspec', 'domain', 'smbclient_path') as $val) {
+ throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+ }
parent::__construct($params);
}
}
/* Authenticate. */
- $cmdline = implode(' ', array($this->_params['smbclient_path'],
- '-L',
- $this->_params['hostspec'],
- '-W',
- $this->_params['domain'],
- '-U',
- $userId));
+ $cmdline = implode(' ', array(
+ $this->_params['smbclient_path'],
+ '-L',
+ $this->_params['hostspec'],
+ '-W',
+ $this->_params['domain'],
+ '-U',
+ $userId
+ ));
$sc = popen($cmdline, 'w');
if ($sc === false) {
- throw new Horde_Auth_Exception(_("Unable to execute smbclient."));
+ throw new Horde_Auth_Exception('Unable to execute smbclient.');
}
fwrite($sc, $credentials['password']);
$rc = pclose($sc);
- if ((int)($rc & 0xff) != 0) {
+ if (intval($rc & 0xff) != 0) {
throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
}
}
* The Horde_Auth_Sql class provides a SQL implementation of the Horde
* authentication system.
*
- * Required parameters:
- * <pre>
- * 'phptype' - (string) The database type (ie. 'pgsql', 'mysql', etc.).
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'encryption' - (string) The encryption to use to store the password in
- * the table (e.g. plain, crypt, md5-hex, md5-base64, smd5,
- * sha, ssha, aprmd5).
- * DEFAULT: 'md5-hex'
- * 'hard_expiration_field' - (string) The name of the field containing a date
- * after which the account is no longer valid and
- * the user will not be able to log in at all.
- * DEFAULT: none
- * 'password_field' - (string) The name of the password field in the auth
- * table.
- * DEFAULT: 'user_pass'
- * 'show_encryption' - (boolean) Whether or not to prepend the encryption in
- * the password field.
- * DEFAULT: false
- * 'soft_expiration_field' - (string) The name of the field containing a date
- * after which the system will request the user
- * change his or her password.
- * DEFAULT: none
- * 'table' - (string) The name of the SQL table to use in 'database'.
- * DEFAULT: 'horde_users'
- * 'username_field' - (string) The name of the username field in the auth
- * table.
- * DEFAULT: 'user_uid'
- * </pre>
- *
- * Required by some database implementations:
- * <pre>
- * 'hostspec' The hostname of the database server.
- * 'protocol' The communication protocol ('tcp', 'unix', etc.).
- * 'database' The name of the database.
- * 'username' The username with which to connect to the database.
- * 'password' The password associated with 'username'.
- * 'options' Additional options to pass to the database.
- * 'port' The port on which to connect to the database.
- * 'tty' The TTY on which to connect to the database.
- * </pre>
- *
- * Optional values when using separate read and write servers, for example
- * in replication settings:
- * <pre>
- * 'splitread' Boolean, whether to implement the separation or not.
- * 'read' Array containing the parameters which are different for
- * the read database connection, currently supported
- * only 'hostspec' and 'port' parameters.
- * </pre>
- *
* The table structure for the Auth system is in
* horde/scripts/sql/horde_users.sql.
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
*
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package Auth
*/
class Horde_Auth_Sql extends Horde_Auth_Base
{
/**
* Handle for the current database connection.
*
- * @var DB
+ * @var Horde_Db_Adapter_Base
*/
protected $_db;
/**
- * Handle for the current database connection, used for writing. Defaults
- * to the same handle as $_db if a separate write database is not required.
+ * Constructor
*
- * @var DB
- */
- protected $_write_db;
-
- /**
- * Boolean indicating whether or not we're connected to the SQL server.
+ * @param array $params Parameters:
+ * 'db' - (Horde_Db_Adapter_Base) [REQUIRED] Database object.
+ * <pre>
+ * 'encryption' - (string) The encryption to use to store the password in
+ * the table (e.g. plain, crypt, md5-hex, md5-base64, smd5,
+ * sha, ssha, aprmd5).
+ * DEFAULT: 'md5-hex'
+ * 'hard_expiration_field' - (string) The name of the field containing a
+ * date after which the account is no longer
+ * valid and the user will not be able to log in
+ * at all.
+ * DEFAULT: none
+ * 'password_field' - (string) The name of the password field in the auth
+ * table.
+ * DEFAULT: 'user_pass'
+ * 'show_encryption' - (boolean) Whether or not to prepend the encryption
+ * in the password field.
+ * DEFAULT: false
+ * 'soft_expiration_field' - (string) The name of the field containing a
+ * date after which the system will request the
+ * user change his or her password.
+ * DEFAULT: none
+ * 'table' - (string) The name of the SQL table to use in 'database'.
+ * DEFAULT: 'horde_users'
+ * 'username_field' - (string) The name of the username field in the auth
+ * table.
+ * DEFAULT: 'user_uid'
+ * </pre>
*
- * @var boolean
+ * @throws InvalidArgumentException
*/
- protected $_connected = false;
+ public function __construct(array $params = array())
+ {
+ if (!isset($params['db'])) {
+ throw new InvalidArgumentException('Missing db parameter.');
+ }
+ $this->_db = $params['db'];
+ unset($params['db']);
+
+ $params = array_merge(array(
+ 'encryption' => 'md5-hex',
+ 'password_field' => 'user_pass',
+ 'show_encryption' => false,
+ 'table' => 'horde_users',
+ 'username_field' => 'user_uid'
+ ), $params);
+
+ $params['password_field'] = Horde_String::lower($params['password_field']);
+ $params['username_field'] = Horde_String::lower($params['username_field']);
+
+ parent::__construct($params);
+ }
/**
* Find out if a set of login credentials are valid.
*/
protected function _authenticate($userId, $credentials)
{
- try {
- $this->_connect();
- } catch (Horde_Auth_Exception $e) {
- Horde::logMessage($e, 'ERR');
- throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
- }
-
/* Build the SQL query. */
$query = sprintf('SELECT * FROM %s WHERE %s = ?',
$this->_params['table'],
$this->_params['username_field']);
$values = array($userId);
- Horde::logMessage('SQL Query by Auth_sql::_authenticate(): ' . $query, 'DEBUG');
-
- $result = $this->_db->query($query, $values);
- if ($result instanceof PEAR_Error) {
- Horde::logMessage($result, 'ERR');
+ try {
+ $result = $this->_db->selectOne($query, $values);
+ } catch (Horde_Db_Exception $e) {
throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
}
- $row = $result->fetchRow(DB_GETMODE_ASSOC);
- if (is_array($row)) {
- $result->free();
- } else {
- throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
- }
-
- if (!$this->_comparePasswords($row[$this->_params['password_field']],
- $credentials['password'])) {
+ if (!$result ||
+ !$this->_comparePasswords($row[$this->_params['password_field']], $credentials['password'])) {
throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
}
*/
public function addUser($userId, $credentials)
{
- $this->_connect();
-
/* Build the SQL query. */
$query = sprintf('INSERT INTO %s (%s, %s) VALUES (?, ?)',
$this->_params['table'],
$this->_params['encryption'],
$this->_params['show_encryption']));
- Horde::logMessage('SQL Query by Auth_sql::addUser(): ' . $query, 'DEBUG');
-
- $result = $this->_write_db->query($query, $values);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $this->_db->insert($query, $values);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
}
*/
public function updateUser($oldID, $newID, $credentials)
{
- $this->_connect();
+ $query = sprintf('UPDATE %s SET ', $this->_params['table']);
+ $values = array();
/* Build the SQL query. */
- $tuple = array();
- $tuple[$this->_params['username_field']] = $newID;
- $tuple[$this->_params['password_field']] =
- Horde_Auth::getCryptedPassword($credentials['password'],
- '',
- $this->_params['encryption'],
- $this->_params['show_encryption']);
+ $query .= $this->_params['username_field'] . ' = ? ';
+ $values[] = $newID;
+
+ $query .= $this->_params['password_field'] . ' = ? ';
+ $values[] = Horde_Auth::getCryptedPassword($credentials['password'], '', $this->_params['encryption'], $this->_params['show_encryption']);
if (empty($this->_params['soft_expiration_window'])) {
if (!empty($this->_params['soft_expiration_field'])) {
- $tuple[$this->_params['soft_expiration_field']] = null;
+ $query .= $this->_params['soft_expiration_field'] . ' = ? ';
+ $values[] = null;
}
} else {
- $date = time();
- $datea = localtime($date, true);
+ $datea = localtime(time(), true);
$date = mktime($datea['tm_hour'], $datea['tm_min'],
$datea['tm_sec'], $datea['tm_mon'] + 1,
$datea['tm_mday'] + $this->_params['soft_expiration_window'],
$datea['tm_year']);
- $tuple[$this->_params['soft_expiration_field']] = $date;
+ $query .= $this->_params['soft_expiration_field'] . ' = ? ';
+ $values[] = $date;
- global $notification;
- if (!empty($notification)) {
- $notification->push(strftime(_("New password will expire on %s."), $date), 'horde.message');
+ if ($this->_params['notify_expire']) {
+ call_user_func($this->_params['notify_expire'], $date);
}
+ $query .= $this->_params['soft_expiration_field'] . ' = ? ';
+
if (empty($this->_params['hard_expiration_window'])) {
- $tuple[$this->_params['hard_expiration_field']] = null;
+ $values[] = null;
} else {
$datea = localtime($date, true);
- $date = mktime($datea['tm_hour'], $datea['tm_min'],
- $datea['tm_sec'], $datea['tm_mon'] + 1,
- $datea['tm_mday'] + $this->_params['soft_expiration_window'],
- $datea['tm_year']);
-
- $tuple[$this->_params['hard_expiration_field']] = $date;
+ $values[]= mktime($datea['tm_hour'], $datea['tm_min'],
+ $datea['tm_sec'], $datea['tm_mon'] + 1,
+ $datea['tm_mday'] + $this->_params['soft_expiration_window'],
+ $datea['tm_year']);
}
}
- $query = sprintf('UPDATE %s SET %s WHERE %s = ?',
- $this->_params['table'],
- Horde_SQL::updateValues($this->_write_db, $tuple),
- $this->_params['username_field']);
- $values = array($oldID);
-
- Horde::logMessage('SQL Query by Auth_sql:updateUser(): ' . $query, 'DEBUG');
+ $query = .= sprintf('WHERE %s = ?', $this->_params['username_field']);
+ $values[] = $oldID;
- $result = $this->_write_db->query($query, $values);
- if ($result instanceof PEAR_Error) {
- Horde::logMessage($result, 'ERR');
- throw new Horde_Auth_Exception($result);
+ try {
+ $this->_db->update($query, $values);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
}
*/
public function resetPassword($userId)
{
- $this->_connect();
-
/* Get a new random password. */
$password = Horde_Auth::genRandomPassword();
$this->_params['show_encryption']),
$userId);
- Horde::logMessage('SQL Query by Auth_sql::resetPassword(): ' . $query, 'DEBUG');
-
- $result = $this->_write_db->query($query, $values);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $this->_db->update($query, $values);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
return $password;
*/
public function removeUser($userId)
{
- $this->_connect();
-
/* Build the SQL query. */
$query = sprintf('DELETE FROM %s WHERE %s = ?',
$this->_params['table'],
$this->_params['username_field']);
$values = array($userId);
- Horde::logMessage('SQL Query by Auth_sql::removeUser(): ' . $query, 'DEBUG');
-
- $result = $this->_write_db->query($query, $values);
- if ($result instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($result);
+ try {
+ $this->_db->delete($query, $values);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
Horde_Auth::removeUserData($userId);
*/
public function listUsers()
{
- $this->_connect();
-
/* Build the SQL query. */
$query = sprintf('SELECT %s FROM %s',
$this->_params['username_field'],
$this->_params['table']);
- Horde::logMessage('SQL Query by Auth_sql::listUsers(): ' . $query, 'DEBUG');
-
- $res = $this->_db->getCol($query);
- if ($res instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($res);
+ try {
+ return $this->_db->selectValues($query);
+ } catch (Horde_Db_Exception $e) {
+ throw new Horde_Auth_Exception($e);
}
-
- return $res;
}
/**
*/
public function exists($userId)
{
- $this->_connect();
-
/* Build the SQL query. */
$query = sprintf('SELECT 1 FROM %s WHERE %s = ?',
$this->_params['table'],
$this->_params['username_field']);
$values = array($userId);
- Horde::logMessage('SQL Query by Auth_sql::exists(): ' . $query, 'DEBUG');
-
- $res = $this->_db->getOne($query, $values);
- return ($res instanceof PEAR_Error)
- ? false
- : $res;
+ try {
+ return (bool)$this->_db->selectValue($query, $values);
+ } catch (Horde_Db_Exception $e) {
+ return false;
+ }
}
/**
$this->_params['show_encryption']);
}
- /**
- * Attempts to open a connection to the SQL server.
- *
- * @throws Horde_Auth_Exception
- */
- function _connect()
- {
- if ($this->_connected) {
- return;
- }
-
- Horde::assertDriverConfig($this->_params, 'auth', array('phptype'),
- 'authentication SQL');
-
- if (!isset($this->_params['database'])) {
- $this->_params['database'] = '';
- }
- if (!isset($this->_params['username'])) {
- $this->_params['username'] = '';
- }
- if (!isset($this->_params['password'])) {
- $this->_params['password'] = '';
- }
- if (!isset($this->_params['hostspec'])) {
- $this->_params['hostspec'] = '';
- }
- if (empty($this->_params['encryption'])) {
- $this->_params['encryption'] = 'md5-hex';
- }
- if (!isset($this->_params['show_encryption'])) {
- $this->_params['show_encryption'] = false;
- }
- if (empty($this->_params['table'])) {
- $this->_params['table'] = 'horde_users';
- }
- if (empty($this->_params['username_field'])) {
- $this->_params['username_field'] = 'user_uid';
- } else {
- $this->_params['username_field'] = Horde_String::lower($this->_params['username_field']);
- }
- if (empty($this->_params['password_field'])) {
- $this->_params['password_field'] = 'user_pass';
- } else {
- $this->_params['password_field'] = Horde_String::lower($this->_params['password_field']);
- }
-
- /* Connect to the SQL server using the supplied parameters. */
- $this->_write_db = DB::connect($this->_params,
- array('persistent' => !empty($this->_params['persistent']),
- 'ssl' => !empty($this->_params['ssl'])));
- if ($this->_write_db instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($this->_write_db);
- }
-
- // Set DB portability options.
- switch ($this->_write_db->phptype) {
- case 'mssql':
- $this->_write_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS | DB_PORTABILITY_RTRIM);
- break;
- default:
- $this->_write_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS);
- }
-
- /* Check if we need to set up the read DB connection
- * seperately. */
- if (!empty($this->_params['splitread'])) {
- $params = array_merge($this->_params, $this->_params['read']);
- $this->_db = DB::connect($params,
- array('persistent' => !empty($params['persistent']),
- 'ssl' => !empty($params['ssl'])));
- if ($this->_db instanceof PEAR_Error) {
- throw new Horde_Auth_Exception($this->_db);
- }
-
- switch ($this->_db->phptype) {
- case 'mssql':
- $this->_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS | DB_PORTABILITY_RTRIM);
- break;
- default:
- $this->_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS);
- }
-
- } else {
- /* Default to the same DB handle for reads. */
- $this->_db =& $this->_write_db;
- }
-
- $this->_connected = true;
- }
-
}
<channel>pear.horde.org</channel>
<min>0.2.0</min>
</package>
+ <package>
+ <name>Ldap</name>
+ <channel>pear.horde.org</channel>
+ </package>
+ <package>
+ <name>Net_IMSP</name>
+ <channel>pear.horde.org</channel>
+ </package>
<extension>
<name>gettext</name>
</extension>
--- /dev/null
+<?php
+/**
+ * @category Horde
+ * @package Core
+ */
+class Horde_Core_Binder_Auth implements Horde_Injector_Binder
+{
+ public function create(Horde_Injector $injector)
+ {
+ return new Horde_Core_Factory_Auth($injector);
+ }
+
+ public function equals(Horde_Injector_Binder $binder)
+ {
+ return false;
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * A Horde_Injector:: based Horde_Auth:: factory.
+ *
+ * PHP version 5
+ *
+ * @category Horde
+ * @package Core
+ * @author Michael Slusarz <slusarz@horde.org>
+ * @license http://www.fsf.org/copyleft/lgpl.html LGPL
+ * @link http://pear.horde.org/index.php?package=Core
+ */
+
+/**
+ * A Horde_Injector:: based Horde_Auth:: factory.
+ *
+ * Copyright 2010 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file COPYING for license information (LGPL). If you
+ * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
+ *
+ * @category Horde
+ * @package Core
+ * @author Michael Slusarz <slusarz@horde.org>
+ * @license http://www.fsf.org/copyleft/lgpl.html LGPL
+ * @link http://pear.horde.org/index.php?package=Core
+ */
+class Horde_Core_Factory_Auth
+{
+ /**
+ * The injector.
+ *
+ * @var Horde_Injector
+ */
+ private $_injector;
+
+ /**
+ * Singleton instances.
+ *
+ * @var array
+ */
+ private $_instances = array();
+
+ /**
+ * Constructor.
+ *
+ * @param Horde_Injector $injector The injector to use.
+ */
+ public function __construct(Horde_Injector $injector)
+ {
+ $this->_injector = $injector;
+ }
+
+ /**
+ * Return the Horde_Auth:: instance.
+ *
+ * @param string $driver The driver.
+ * @param array $params Additional parameters to pass to the driver
+ * (will override Horde defaults).
+ *
+ * @return Horde_Auth_Base The singleton instance.
+ * @throws Horde_Auth_Exception
+ */
+ public function getOb($driver = null, array $params = array())
+ {
+ if (is_null($driver)) {
+ $driver = $GLOBALS['conf']['auth']['driver'];
+ }
+
+ $params = array_merge(Horde::getDriverConfig('auth', $driver), $params);
+ ksort($params);
+
+ /* Get proper driver name now that we have grabbed the
+ * configuration. */
+ if (strcasecmp($driver, 'httpremote') === 0) {
+ /* BC */
+ $driver = 'Http_Remote';
+ } elseif (strcasecmp($driver, 'application') === 0) {
+ $driver = 'Horde_Core_Auth_Application';
+ } else {
+ $driver = Horde_String::ucfirst(Horde_String::lower(basename($driver)));
+ }
+
+ $sig = hash('md5', serialize(array($driver, $params)));
+
+ if (!isset($this->_instances[$sig])) {
+ $lc_driver = Horde_String::lower($driver);
+ switch ($lc_driver) {
+ case 'composite':
+ // TODO
+ $params['admin_driver'] = null;
+ $params['auth_driver'] = null;
+ break;
+
+ case 'cyrsql':
+ case 'cyrus':
+ $imap_config = array(
+ 'hostspec' => empty($params['hostspec']) ? null : $params['hostspec'],
+ 'password' => $params['cyrpass'],
+ 'port' => empty($params['port']) ? null : $params['port'],
+ 'secure' => ($params['secure'] == 'none') ? null : $params['secure'],
+ 'username' => $params['cyradmin']
+ );
+
+ try {
+ $ob = Horde_Imap_Client::factory('Socket', $imap_config);
+ $ob->login();
+ $params['imap'] = $ob;
+ } catch (Horde_Imap_Client_Exception $e) {
+ throw new Horde_Auth_Exception($e);
+ }
+ break;
+
+ if ($lc_driver == 'cyrus') {
+ $params['backend'] = $this->getOb($params['backend']['driver'], $params['backend']['params']);
+ }
+ break;
+
+ case 'http_remote':
+ if (!empty($GLOBALS['conf']['http']['proxy']['proxy_host'])) {
+ $params['proxy'] = $GLOBALS['conf']['http']['proxy'];
+ }
+ break;
+
+ case 'kolab':
+ $params['kolab'] = $this->_injector->getInstance('Horde_Kolab_Session');
+ break;
+
+ case 'ldap':
+ $params['ldap'] = $this->_injector->getInstance('Horde_Ldap')->getOb('horde', 'auth');
+ break;
+
+ case 'sql':
+ $params['db'] = $this->_injector->getInstance('Horde_Db')->getOb('auth');
+ break;
+ }
+
+ $params['logger'] = $this->_injector->getInstance('Horde_Log_Logger');
+ $params['notify_expire'] = array($this, 'notifyExpire');
+
+ $this->_instances[$sig] = Horde_Auth::factory($driver, $params);
+ }
+
+ return $this->_instances[$sig];
+ }
+
+ /**
+ * Expire notification callback.
+ *
+ * @param integer $date UNIX timestamp of password expiration.
+ */
+ public function notifyExpire($date)
+ {
+ if (isset($GLOBALS['notification'])) {
+ $toexpire = ($date - time()) / 86400;
+ $GLOBALS['notification']->push(sprintf(ngettext("%d day until your password expires.", "%d days until your password expires.", $toexpire), $toexpire), 'horde.warning');
+ }
+ }
+
+}
/* Users permissions. */
$perm_val = $permission->getUserPermissions();
$this->_form->setSection('users', _("Individual Users"), Horde::img('user.png'), false);
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
if ($auth->hasCapability('list')) {
/* The auth driver has list capabilities so set up an array which
* the matrix field type will recognise to set up an enum box for
/* Define binders. */
$binders = array(
'Horde_Alarm' => new Horde_Core_Binder_Alarm(),
+ 'Horde_Auth' => new Horde_Core_Binder_Auth(),
// 'Horde_Browser' - initialized below
'Horde_Cache' => new Horde_Core_Binder_Cache(),
'Horde_Core_Auth_Signup' => new Horde_Core_Binder_AuthSignup(),
* libraries from other applications. */
$app_lib = $this->get('fileroot', $app) . '/lib';
Horde_Autoloader::addClassPattern('/^' . $app . '(?:$|_)/i', $app_lib);
-
+
$checkPerms = !isset($options['check_perms']) || !empty($options['check_perms']);
/* If permissions checking is requested, return an error if the
</dir> <!-- /lib/Horde/Core/Autoloader -->
<dir name="Binder">
<file name="Alarm.php" role="php" />
+ <file name="Auth.php" role="php" />
<file name="AuthSignup.php" role="php" />
<file name="Cache.php" role="php" />
<file name="Data.php" role="php" />
<file name="Share.php" role="php" />
</dir> <!-- /lib/Horde/Core/Binder -->
<dir name="Factory">
+ <file name="Auth.php" role="php" />
<file name="Db.php" role="php" />
<file name="DbPear.php" role="php" />
<file name="Data.php" role="php" />
<install name="lib/Horde/Core/Autoloader/Callback/Auth.php" as="Horde/Core/Autoloader/Callback/Auth.php" />
<install name="lib/Horde/Core/Autoloader/Callback/Mime.php" as="Horde/Core/Autoloader/Callback/Mime.php" />
<install name="lib/Horde/Core/Binder/Alarm.php" as="Horde/Core/Binder/Alarm.php" />
+ <install name="lib/Horde/Core/Binder/Auth.php" as="Horde/Core/Binder/Auth.php" />
<install name="lib/Horde/Core/Binder/AuthSignup.php" as="Horde/Core/Binder/AuthSignup.php" />
<install name="lib/Horde/Core/Binder/Cache.php" as="Horde/Core/Binder/Cache.php" />
<install name="lib/Horde/Core/Binder/Data.php" as="Horde/Core/Binder/Data.php" />
<install name="lib/Horde/Core/Binder/Vfs.php" as="Horde/Core/Binder/Vfs.php" />
<install name="lib/Horde/Core/Binder/Facebook.php" as="Horde/Core/Binder/Facebook.php" />
<install name="lib/Horde/Core/Binder/Share.php" as="Horde/Core/Binder/Share.php" />
+ <install name="lib/Horde/Core/Factory/Auth.php" as="Horde/Core/Factory/Auth.php" />
<install name="lib/Horde/Core/Factory/Db.php" as="Horde/Core/Factory/Db.php" />
<install name="lib/Horde/Core/Factory/DbPear.php" as="Horde/Core/Factory/DbPear.php" />
<install name="lib/Horde/Core/Factory/Data.php" as="Horde/Core/Factory/Data.php" />
$group_driver = null;
$group_params = null;
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
if ($auth->hasCapability('groups')) {
$group_driver = $auth->getDriver();
$group_params = $auth;
$calendar_user = $conf['kolab']['filter']['calendar_id'] . '@' . $domain;
/* Load the authentication libraries */
- $auth = Horde_Auth::singleton(isset($conf['auth']['driver'])?$conf['auth']['driver']:'kolab');
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb(isset($conf['auth']['driver']) ? null : 'kolab');
$authenticated = $auth->authenticate($calendar_user,
array('password' => $conf['kolab']['filter']['calendar_pass']),
false);
}
// @TODO: inject this
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
if ($this->_request->getServer('PHP_AUTH_USER')) {
$user = $this->_request->getServer('PHP_AUTH_USER');
*/
function check_auth($type, $username, $password)
{
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
return $auth->authenticate($username, array('password' => $password));
}
*/
function _checkAuthentication($username, $password)
{
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
return $auth->authenticate($username, array('password' => $password))
? Horde_Auth::getAuth()
: false;
}
/* Get an Auth object. */
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
/* Make this user an admin for the time beeing to allow deletion of
* user data. */
{
/* Get an Auth object. */
try {
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
} catch (Horde_Exception $e) {
// TODO
}
require_once 'Horde/Group.php';
$groups = Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
$form = null;
$reload = false;
Horde_Registry::appInit('horde', array('authentication' => 'none'));
// Make sure signups are enabled before proceeding
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if ($conf['signup']['allow'] !== true ||
!$auth->hasCapability('add')) {
throw new Horde_Exception(_("User Registration has been disabled for this site."));
require_once dirname(__FILE__) . '/../lib/Application.php';
Horde_Registry::appInit('horde', array('admin' => true));
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if ($conf['signup']['allow'] && $conf['signup']['approve']) {
$signup = $injector->getInstance('Horde_Core_Auth_Signup');
/* Hide appropriate prefGroups. */
try {
- Horde_Auth::singleton($conf['auth']['driver'])->hasCapability('update');
+ $GLOBALS['injector']->getInstance('Horde_Auth')->getOb()->hasCapability('update');
} catch (Horde_Exception $e) {
$ui->suppressGroups[] = 'forgotpass';
}
/* Get an Auth object. */
$auth = ($app && $is_auth)
- ? Horde_Auth::singleton('application', array('app' => $app))
- : Horde_Auth::singleton($conf['auth']['driver']);
+ ? $injector->getInstance('Horde_Auth')->getOb('application', array('app' => $app))
+ : $injector->getInstance('Horde_Auth')->getOb();
/* Build the list of necessary login parameters. */
$loginparams = array(
require_once dirname(__FILE__) . '/../lib/Application.php';
Horde_Registry::appInit('horde', array('authentication' => 'none'));
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
// Check for COOKIE auth.
if (empty($_COOKIE['user']) ||
require_once dirname(__FILE__) . '/../lib/Application.php';
Horde_Registry::appInit('horde', array('authentication' => 'none'));
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
// Check for GET auth.
if (empty($_GET['user']) ||
require_once dirname(__FILE__) . '/../lib/Application.php';
Horde_Registry::appInit('horde');
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
// Check for HTTP auth.
if (empty($_SERVER['PHP_AUTH_USER']) ||
Horde_Registry::appInit('horde', array('nologintasks' => true));
// Make sure auth backend allows passwords to be reset.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->hasCapability('update')) {
$notification->push(_("Changing your password is not supported with the current configuration. Contact your administrator."), 'horde.error');
header('Location: ' . Horde::getServiceLink('login')->add('url', Horde_Util::getFormData('url'))->setRaw(true));
Horde_Registry::appInit('horde', array('authentication' => 'none'));
// Make sure auth backend allows passwords to be reset.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->hasCapability('resetpassword')) {
$notification->push(_("Cannot reset password automatically, contact your administrator."), 'horde.error');
header('Location: ' . Horde::getServiceLink('login')->add('url', Horde_Util::getFormData('url'))->setRaw(true));
$app = Horde_Util::getFormData('app');
$shares = $GLOBALS['injector']->getInstance('Horde_Share')->getScope($app);
$groups = Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if ($registry->hasMethod('shareHelp', $app)) {
$help = $registry->callByPackage($app, 'shareHelp');
} else {
require_once dirname(__FILE__) . '/lib/Application.php';
Horde_Registry::appInit('horde', array('authentication' => 'none'));
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
// Make sure signups are enabled before proceeding
if ($conf['signup']['allow'] !== true ||
$secret = $GLOBALS['injector']->getInstance('Horde_Secret');
$params['admin_password'] = $secret->read($secret->getKey('imp'), $params['admin_password']);
}
- $auth = Horde_Auth::singleton('imap', $params);
- $auth->addUser($userId, $credentials);
+
+ $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('imap', $params)->addUser($userId, $credentials);
}
/**
$secret = $GLOBALS['injector']->getInstance('Horde_Secret');
$params['admin_password'] = $secret->read($secret->getKey('imp'), $params['admin_password']);
}
- $auth = Horde_Auth::singleton('imap', $params);
- $auth->removeUser($userId);
+
+ $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('imap', $params)->removeUser($userId);
}
/**
$secret = $GLOBALS['injector']->getInstance('Horde_Secret');
$params['admin_password'] = $secret->read($secret->getKey('imp'), $params['admin_password']);
}
- $auth = Horde_Auth::singleton('imap', $params);
- return $auth->listUsers();
+
+ return $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('imap', $params)->listUsers();
}
/* Preferences display/handling methods. Code is contained in
Horde_Registry::appInit('ingo', array('authentication' => 'none', 'cli' => true));
// Initialize authentication manager.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
// Initialize storage backend.
$rules_storage = Ingo_Storage::factory();
$this->registry = &$registry;
$this->notification = &$notification;
- $this->auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $this->auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
$this->conf = Horde::loadConfiguration('conf.php', 'conf');
$this->objects = Horde::loadConfiguration('objects.php', 'objects');
/* Authenticate the user if possible. */
if ($this->_argv->user) {
- require_once 'Horde/Auth.php';
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
if (!$auth->authenticate($this->_argv->user,
array('password' => $this->_argv->pass))) {
throw new InvalidArgumentException('Failed to log in!');
'members' => array('credentialsui'),
);
-$auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
-if (is_a($auth, 'Auth') && $auth->hasCapability('update')) {
- $prefGroups['forgotpass'] = array(
- 'column' => _("Your Information"),
- 'label' => _("Account Password"),
- 'desc' => _("Set options to allow you to reset your password if you ever forget it."),
- 'members' => array('security_question', 'security_answer', 'alternate_email')
- );
-}
+try {
+ if ($GLOBALS['injector']->getInstance('Horde_Auth')->getOb()->hasCapability('update')) {
+ $prefGroups['forgotpass'] = array(
+ 'column' => _("Your Information"),
+ 'label' => _("Account Password"),
+ 'desc' => _("Set options to allow you to reset your password if you ever forget it."),
+ 'members' => array('security_question', 'security_answer', 'alternate_email')
+ );
+ }
+} catch (Exception $e) {}
$prefGroups['language'] = array(
'column' => _("Your Information"),
sprintf(_("Permission denied for the requested feed (%s)."),
htmlspecialchars($calendar)));
} else {
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $injector->getInstance('Horde_Auth')->getOb();
if (isset($_SERVER['PHP_AUTH_USER'])) {
$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];
*/
public static function readPermsForm($share)
{
- $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
$perm = $share->getPermission();
$errors = array();
$shares = $GLOBALS['injector']->getInstance('Horde_Share')->getScope();
$groups = Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
$reload = false;
$actionID = Horde_Util::getFormData('actionID', 'edit');
$perm = $share->getPermission();
}
}
-
+
if (!Horde_Auth::getAuth() ||
(isset($share) &&
!Horde_Auth::isAdmin() &&
<?php
-$auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+$auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
require_once 'Horde/Group.php';
$horde_groups = Group::singleton();
if (!empty($GLOBALS['conf']['share']['any_group'])) {
// get the list of all users if we can. If your site
// has a *large* number of users, you may want to comment
// out this section to avoid unnecessary overhead.
-$authDriver = $conf['auth']['driver'];
-$auth = Horde_Auth::singleton($authDriver);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
if ($auth->hasCapability('list')) {
$users = $auth->listUsers();
}
global $conf, $whups_driver;
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
if ($auth->hasCapability('list')) {
$queue = $vars->get('queue');
$current = $whups_driver->getQueueUsers($queue);
*/
static protected function _findAuthUser($from)
{
- global $conf;
-
- $auth = Horde_Auth::singleton($conf['auth']['driver'], Horde::getDriverConfig('auth', $conf['auth']['driver']));
+ $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
if ($auth->hasCapability('list')) {
foreach ($auth->listUsers() as $user) {
// Login to horde if username & password are set.
if (!empty($username) && !empty($password)) {
- $auth = Horde_Auth::singleton($conf['auth']['driver']);
+ $auth = $injector->getInstance('Horde_Auth')->getOb();
if (!$auth->authenticate($username, array('password' => $password))) {
$error = _("Login is incorrect.");
Horde::logMessage($error, 'ERR');