1
0
mirror of https://github.com/e107inc/e107.git synced 2025-08-01 20:30:39 +02:00

Issue #84 - review/tidy up alt_auth plugin.

Further testing needed.
This commit is contained in:
SteveD
2013-01-21 22:08:48 +00:00
parent 25da842c5e
commit 5457247787
14 changed files with 2599 additions and 2489 deletions

View File

@@ -2,7 +2,7 @@
/* /*
* e107 website system * e107 website system
* *
* Copyright (C) 2008-2012 e107 Inc (e107.org) * Copyright (C) 2008-2013 e107 Inc (e107.org)
* Released under the terms and conditions of the * Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
* *
@@ -31,11 +31,6 @@ TODO:
if (!defined('e107_INIT')) { exit; } if (!defined('e107_INIT')) { exit; }
if (!is_object(vartrue($euf)))
{
require_once(e_HANDLER.'user_extended_class.php');
$euf = new e107_user_extended;
}
define('AUTH_SUCCESS', -1); define('AUTH_SUCCESS', -1);
@@ -46,476 +41,469 @@ if (!is_object(vartrue($euf)))
define('AUTH_NOT_AVAILABLE', 5); define('AUTH_NOT_AVAILABLE', 5);
require_once(e_HANDLER.'user_extended_class.php');
require_once(e_PLUGIN.'alt_auth/alt_auth_login_class.php'); // Has base methods class
/**
* Get list of supported authentication methods
* Searches for files *_auth.php in the plugin directory class alt_auth_admin extends alt_auth_base
*
* @param boolean $incE107 - if TRUE, 'e107' is included as an authentication method.
*
* @return array of authentication methods in value fields
*/
function alt_auth_get_authlist($incE107 = TRUE)
{ {
$authlist = $incE107 ? array('e107') : array(); private $euf = FALSE;
$handle = opendir(e_PLUGIN.'alt_auth');
while ($file = readdir($handle)) public function __construct()
{ {
if(preg_match("/^(.*)_auth\.php/", $file, $match)) $this->euf = new e107_user_extended;
}
/**
* Get list of supported authentication methods
* Searches for files *_auth.php in the plugin directory
*
* @param boolean $incE107 - if TRUE, 'e107' is included as an authentication method.
*
* @return array of authentication methods in value fields
*/
public function alt_auth_get_authlist($incE107 = TRUE)
{
$authlist = $incE107 ? array('e107') : array();
$handle = opendir(e_PLUGIN.'alt_auth');
while ($file = readdir($handle))
{ {
$authlist[] = $match[1]; if(preg_match("/^(.+)_auth\.php/", $file, $match))
{
$authlist[] = $match[1];
}
} }
closedir($handle);
return $authlist;
} }
closedir($handle);
return $authlist;
}
/** /**
* Return HTML for selector for authentication method * Return HTML for selector for authentication method
* *
* @param string $name - the name of the selector * @param string $name - the name of the selector
* @param string $curval - current value (if any) * @param string $curval - current value (if any)
* @param string $optlist - comma-separated list of options to be included as choices * @param string $optlist - comma-separated list of options to be included as choices
*/ */
function alt_auth_get_dropdown($name, $curval = '', $options = '') public function alt_auth_get_dropdown($name, $curval = '', $options = '')
{
$optList = explode(',', $options);
$authList = array_merge($optList, alt_auth_get_authlist(FALSE));
$ret = "<select class='tbox' name='{$name}'>\n";
foreach ($authList as $v)
{ {
$sel = ($curval == $v ? " selected = 'selected' " : ''); $optList = explode(',', $options);
$ret .= "<option value='{$v}'{$sel} >{$v}</option>\n"; $authList = array_merge($optList, $this->alt_auth_get_authlist(FALSE));
} $ret = "<select class='tbox' name='{$name}'>\n";
$ret .= "</select>\n"; foreach ($authList as $v)
return $ret;
}
/**
* All user fields which might, just possibly, be transferred. The array key is the corresponding field in the E107 user database; code prefixes it
* with 'xf_' to get the parameter
* 'default' may be a single value to set the same for all connect methods, or an array to set different defaults.
*/
$alt_auth_user_fields = array(
'user_email' => array('prompt' => LAN_ALT_12, 'default' => 'user_email', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => 'mail'),
'user_hideemail' => array('prompt' => LAN_ALT_13, 'default' => 'user_hideemail', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => '', method => 'bool1'),
'user_name' => array('prompt' => LAN_ALT_14, 'default' => 'user_name', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => ''),
'user_login' => array('prompt' => LAN_ALT_15, 'default' => 'user_login', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => 'sn'),
'user_customtitle'=> array('prompt' => LAN_ALT_16, 'default' => 'user_customtitle', 'optional' => TRUE, 'otherdb' => FALSE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_signature' => array('prompt' => LAN_ALT_17, 'default' => 'user_signature', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_image' => array('prompt' => LAN_ALT_18, 'default' => 'user_image', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_sess' => array('prompt' => LAN_ALT_19, 'default' => 'user_sess', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_join' => array('prompt' => LAN_ALT_20, 'default' => 'user_join', 'optional' => TRUE, 'otherdb' => FALSE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => ''),
'user_ban' => array('prompt' => LAN_ALT_21, 'default' => 'user_ban', 'optional' => TRUE, 'otherdb' => FALSE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_class' => array('prompt' => LAN_ALT_22, 'default' => 'user_class', 'optional' => TRUE, 'otherdb' => FALSE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE)
);
/**
* Returns a block of table rows with user DB fields and either checkboxes or entry boxes
*
* @param string $tableType is the prefix used, without the following underscore
* @param $frm is the form object to use to create the text
* @param array $parm is the array of options for the current auth type as read from the DB
*/
function alt_auth_get_field_list($tableType, $frm, $parm, $asCheckboxes = FALSE)
{
global $alt_auth_user_fields;
$ret = '';
foreach ($alt_auth_user_fields as $f => $v)
{
if (varsettrue($v['showAll']) || varsettrue($v[$tableType]))
{ {
$ret .= "<tr><td$log>"; $sel = ($curval == $v ? " selected = 'selected' " : '');
if ($v['optional'] == FALSE) $ret .= '*&nbsp;'; $ret .= "<option value='{$v}'{$sel} >{$v}</option>\n";
$ret .= $v['prompt'].':'; }
if (isset($v['help'])) $ret .= "</select>\n";
return $ret;
}
/**
* All user fields which might, just possibly, be transferred. The array key is the corresponding field in the E107 user database; code prefixes it
* with 'xf_' to get the parameter
* 'default' may be a single value to set the same for all connect methods, or an array to set different defaults.
*/
private $alt_auth_user_fields = array(
'user_email' => array('prompt' => LAN_ALT_12, 'default' => 'user_email', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => 'mail'),
'user_hideemail' => array('prompt' => LAN_ALT_13, 'default' => 'user_hideemail', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => '', method => 'bool1'),
'user_name' => array('prompt' => LAN_ALT_14, 'default' => 'user_name', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => ''),
'user_login' => array('prompt' => LAN_ALT_15, 'default' => 'user_login', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => 'sn'),
'user_customtitle'=> array('prompt' => LAN_ALT_16, 'default' => 'user_customtitle', 'optional' => TRUE, 'otherdb' => FALSE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_signature' => array('prompt' => LAN_ALT_17, 'default' => 'user_signature', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_image' => array('prompt' => LAN_ALT_18, 'default' => 'user_image', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_sess' => array('prompt' => LAN_ALT_19, 'default' => 'user_sess', 'optional' => TRUE, 'otherdb' => TRUE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_join' => array('prompt' => LAN_ALT_20, 'default' => 'user_join', 'optional' => TRUE, 'otherdb' => FALSE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => TRUE, 'ldap_field' => ''),
'user_ban' => array('prompt' => LAN_ALT_21, 'default' => 'user_ban', 'optional' => TRUE, 'otherdb' => FALSE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE),
'user_class' => array('prompt' => LAN_ALT_22, 'default' => 'user_class', 'optional' => TRUE, 'otherdb' => FALSE, 'e107db' => TRUE, 'importdb' => FALSE, 'ldap' => FALSE)
);
/**
* Returns a block of table rows with user DB fields and either checkboxes or entry boxes
*
* @param string $tableType is the prefix used, without the following underscore
* @param $frm is the form object to use to create the text
* @param array $parm is the array of options for the current auth type as read from the DB
*/
public function alt_auth_get_field_list($tableType, $frm, $parm, $asCheckboxes = FALSE)
{
$ret = '';
foreach ($this->alt_auth_user_fields as $f => $v)
{
if (varsettrue($v['showAll']) || varsettrue($v[$tableType]))
{ {
$ret .= "<br /><span class='smalltext'>".$v['help']."</span>"; $ret .= "<tr><td$log>";
} if ($v['optional'] == FALSE) $ret .= '*&nbsp;';
$ret .= "</td><td$log>"; $ret .= $v['prompt'].':';
// $fieldname = $tableType.'_'.$v['optname']; if (isset($v['help']))
$fieldname = $tableType.'_xf_'.$f; // Name of the input box
$value = varset($v['default'],'');
if (is_array($value))
{
$value = varset($value[$tableType],'');
}
if (isset($v[$tableType.'_field'])) $value = $v[$tableType.'_field'];
if (isset($parm[$fieldname])) $value = $parm[$fieldname];
// echo "Field: {$fieldname} => {$value}<br />";
if ($asCheckboxes)
{
$ret .= $frm -> form_checkbox($fieldname, 1, $value);
}
else
{
$ret .= $frm -> form_text($fieldname, 35, $value, 120);
if (isset($v['method']) && $v['method'])
{ {
$fieldMethod = $tableType.'_pm_'.$f; // Processing method ID code $ret .= "<br /><span class='smalltext'>".$v['help']."</span>";
$method = varset($parm[$fieldMethod],''); }
$ret .= '&nbsp;&nbsp;'.alt_auth_processing($fieldMethod,$v['method'], $method); $ret .= "</td><td$log>";
// $fieldname = $tableType.'_'.$v['optname'];
$fieldname = $tableType.'_xf_'.$f; // Name of the input box
$value = varset($v['default'],'');
if (is_array($value))
{
$value = varset($value[$tableType],'');
}
if (isset($v[$tableType.'_field'])) $value = $v[$tableType.'_field'];
if (isset($parm[$fieldname])) $value = $parm[$fieldname];
// echo "Field: {$fieldname} => {$value}<br />";
if ($asCheckboxes)
{
$ret .= $frm -> form_checkbox($fieldname, 1, $value);
}
else
{
$ret .= $frm -> form_text($fieldname, 35, $value, 120);
if (isset($v['method']) && $v['method'])
{
$fieldMethod = $tableType.'_pm_'.$f; // Processing method ID code
$method = varset($parm[$fieldMethod],'');
$ret .= '&nbsp;&nbsp;'.$this->alt_auth_processing($fieldMethod,$v['method'], $method);
}
}
$ret .= "</td></tr>\n";
}
}
return $ret;
}
/**
* Returns a list of all the user-related fields allowed as an array, whhere the key is the field name
*
* @param string $tableType is the prefix used, without the following underscore
*
* @return array
*/
public function alt_auth_get_allowed_fields($tableType)
{
$ret = array();
foreach ($this->alt_auth_user_fields as $f => $v)
{
if (varsettrue($v['showAll']) || varsettrue($v[$tableType]))
{
// $fieldname = $tableType.'_'.$v['optname'];
$fieldname = $tableType.'_xf_'.$f; // Name of the input box
$ret[$fieldname] = '1';
}
}
return $ret;
}
/**
* Routine adds the extended user fields which may be involved into the table of field definitions, so that they're displayed
*/
public function add_extended_fields()
{
global $pref;
if (!isset($pref['auth_extended'])) return;
if (!$pref['auth_extended']) return;
static $fieldsAdded = FALSE;
if ($fieldsAdded) return;
$xFields = $this->euf->user_extended_get_fieldList('','user_extended_struct_name');
// print_a($xFields);
$fields = explode(',',$pref['auth_extended']);
foreach ($fields as $f)
{
if (isset($xFields[$f]))
{
$this->alt_auth_user_fields['x_'.$f] = array('prompt' => varset($xFields[$f]['user_extended_struct_text'],'').' ('.$f.')',
'default' => varset($xFields[$f]['default'],''),
'optional' => TRUE,
'showAll' => TRUE, // Show for all methods - in principle, its likely to be wanted for all
'method' => '*' // Specify all convert methods - have little idea what may be around
);
}
}
$fieldsAdded = TRUE;
}
/**
* List of the standard fields which may be displayed for any method.
*/
private $common_fields = array(
'server' => array('fieldname' => 'server', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_32, 'help' => ''),
'uname' => array('fieldname' => 'username', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_33, 'help' => ''),
'pwd' => array('fieldname' => 'password', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_34, 'help' => ''),
'db' => array('fieldname' => 'database', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_35, 'help' => ''),
'table' => array('fieldname' => 'table', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_36, 'help' => ''),
'prefix' => array('fieldname' => 'prefix', 'size' => 35, 'max_size' => 35, 'prompt' => LAN_ALT_39, 'help' => ''),
'ufield' => array('fieldname' => 'user_field','size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_37, 'help' => ''),
'pwfield'=> array('fieldname' => 'password_field','size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_38, 'help' => ''),
'salt' => array('fieldname' => 'password_salt','size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_24, 'help' => LAN_ALT_25),
'classfilt' => array('fieldname' => 'filter_class', 'size' => 10, 'max_size' => 8, 'prompt' => LAN_ALT_76, 'help' => LAN_ALT_77)
);
/**
* Return the HTML for all server-related fields required for configuration of a particular method.
* Each is a row of a table having two columns (no <table>...</table> etc added, so can be embedded in a larger table
*
* @param string $prefix is the prefix used, without the following underscore
* @param $frm is the form object to use
* @param array $parm is an array of the current values of each item
* @param string $fields is a list of the fields to display, separated by '|'. The names are the key values from $common_fields table
*
*/
public function alt_auth_get_db_fields($prefix, $frm, $parm, $fields = 'server|uname|pwd|db|table|ufield|pwfield')
{
$opts = explode('|',$fields);
$ret = '';
foreach ($this->common_fields as $fn => $cf)
{
if (in_array($fn,$opts))
{
$ret .= "<tr><td$log>".$cf['prompt'];
$ret .= "</td><td$log>";
$ret .= $frm -> form_text($prefix.'_'.$cf['fieldname'], $cf['size'], $parm[$prefix.'_'.$cf['fieldname']], $cf['max_size']);
if ($cf['help']) $ret .= "<br /><span class='field-help'>".$cf['help']."</span>";
$ret .= "</td></tr>\n";
}
}
return $ret;
}
/**
* Write all the options for a particular authentication type to the DB
*
* @var string $prefix - the prefix string representing the authentication type (currently importdb|e107db|otherdb|ldap|radius). Must NOT have a trailing underscore
*/
public function alt_auth_post_options($prefix)
{
$sql = e107::getDb();
$lprefix = $prefix.'_';
$user_fields = $this->alt_auth_get_allowed_fields($prefix); // Need this list in case checkboxes for parameters
foreach ($user_fields as $k => $v)
{
if (!isset($_POST[$k]))
{
$_POST[$k] = '0';
}
}
// Now we can post everything
foreach($_POST as $k => $v)
{
if (strpos($k,$lprefix) === 0)
{
$v = base64_encode(base64_encode($v));
if($sql -> db_Select('alt_auth', '*', "auth_type='{$prefix}' AND auth_parmname='{$k}' "))
{
$sql -> db_Update('alt_auth', "auth_parmval='{$v}' WHERE auth_type='{$prefix}' AND auth_parmname='{$k}' ");
}
else
{
$sql -> db_Insert('alt_auth', "'{$prefix}','{$k}','{$v}' ");
} }
} }
$ret .= "</td></tr>\n";
}
}
return $ret;
}
/**
* Returns a list of all the user-related fields allowed as an array, whhere the key is the field name
*
* @param string $tableType is the prefix used, without the following underscore
*
* @return array
*/
function alt_auth_get_allowed_fields($tableType)
{
global $alt_auth_user_fields;
$ret = array();
foreach ($alt_auth_user_fields as $f => $v)
{
if (varsettrue($v['showAll']) || varsettrue($v[$tableType]))
{
// $fieldname = $tableType.'_'.$v['optname'];
$fieldname = $tableType.'_xf_'.$f; // Name of the input box
$ret[$fieldname] = '1';
}
}
return $ret;
}
/**
* Routine adds the extended user fields which may be involved into the table of field definitions, so that they're displayed
*/
function add_extended_fields()
{
global $alt_auth_user_fields, $euf, $pref;
if (!isset($pref['auth_extended'])) return;
if (!$pref['auth_extended']) return;
static $fieldsAdded = FALSE;
if ($fieldsAdded) return;
$xFields = $euf->user_extended_get_fieldList('','user_extended_struct_name');
// print_a($xFields);
$fields = explode(',',$pref['auth_extended']);
foreach ($fields as $f)
{
if (isset($xFields[$f]))
{
$alt_auth_user_fields['x_'.$f] = array('prompt' => varset($xFields[$f]['user_extended_struct_text'],'').' ('.$f.')',
'default' => varset($xFields[$f]['default'],''),
'optional' => TRUE,
'showAll' => TRUE, // Show for all methods - in principle, its likely to be wanted for all
'method' => '*' // Specify all convert methods - have little idea what may be around
);
}
}
$fieldsAdded = TRUE;
}
/**
* List of the standard fields which may be displayed for any method.
*/
$common_fields = array(
'server' => array('fieldname' => 'server', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_32, 'help' => ''),
'uname' => array('fieldname' => 'username', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_33, 'help' => ''),
'pwd' => array('fieldname' => 'password', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_34, 'help' => ''),
'db' => array('fieldname' => 'database', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_35, 'help' => ''),
'table' => array('fieldname' => 'table', 'size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_36, 'help' => ''),
'prefix' => array('fieldname' => 'prefix', 'size' => 35, 'max_size' => 35, 'prompt' => LAN_ALT_39, 'help' => ''),
'ufield' => array('fieldname' => 'user_field','size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_37, 'help' => ''),
'pwfield'=> array('fieldname' => 'password_field','size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_38, 'help' => ''),
'salt' => array('fieldname' => 'password_salt','size' => 35, 'max_size' => 120, 'prompt' => LAN_ALT_24, 'help' => LAN_ALT_25),
'classfilt' => array('fieldname' => 'filter_class', 'size' => 10, 'max_size' => 8, 'prompt' => LAN_ALT_76, 'help' => LAN_ALT_77)
);
/**
* Return the HTML for all server-related fields required for configuration of a particular method.
* Each is a row of a table having two columns (no <table>...</table> etc added, so can be embedded in a larger table
*
* @param string $prefix is the prefix used, without the following underscore
* @param $frm is the form object to use
* @param array $parm is an array of the current values of each item
* @param string $fields is a list of the fields to display, separated by '|'. The names are the key values from $common_fields table
*
*/
function alt_auth_get_db_fields($prefix, $frm, $parm, $fields = 'server|uname|pwd|db|table|ufield|pwfield')
{
global $common_fields;
$opts = explode('|',$fields);
$ret = '';
foreach ($common_fields as $fn => $cf)
{
if (in_array($fn,$opts))
{
$ret .= "<tr><td$log>".$cf['prompt'];
$ret .= "</td><td$log>";
$ret .= $frm -> form_text($prefix.'_'.$cf['fieldname'], $cf['size'], $parm[$prefix.'_'.$cf['fieldname']], $cf['max_size']);
if ($cf['help']) $ret .= "<br /><span class='field-help'>".$cf['help']."</span>";
$ret .= "</td></tr>\n";
}
}
return $ret;
}
/**
* Write all the options for a particular authentication type to the DB
*
* @var string $prefix - the prefix string representing the authentication type (currently importdb|e107db|otherdb|ldap|radius). Must NOT have a trailing underscore
*/
function alt_auth_post_options($prefix)
{
global $common_fields, $sql, $admin_log;
$lprefix = $prefix.'_';
$user_fields = alt_auth_get_allowed_fields($prefix); // Need this list in case checkboxes for parameters
foreach ($user_fields as $k => $v)
{
if (!isset($_POST[$k]))
{
$_POST[$k] = '0';
} }
e107::getAdminLog()->log_event('AUTH_03',$prefix,E_LOG_INFORMATIVE,'');
return LAN_ALT_UPDATED;
} }
// Now we can post everything
foreach($_POST as $k => $v) /**
* Get the HTML for a password type selector.
*
* @param string $name - name to be used for selector
* @param $frm - form object to use
* @param string $currentSelection - current value (if any)
* @param boolean $getExtended - return all supported password types if TRUE, 'core' password types if FALSE
*/
public function altAuthGetPasswordSelector($name, $frm, $currentSelection = '', $getExtended = FALSE)
{ {
if (strpos($k,$lprefix) === 0) $password_methods = ExtendedPasswordHandler::GetPasswordTypes($getExtended);
$text = "";
$text .= $frm->form_select_open($name);
foreach($password_methods as $k => $v)
{ {
$v = base64_encode(base64_encode($v)); $sel = ($currentSelection == $k) ? " Selected='selected'" : '';
if($sql -> db_Select('alt_auth', '*', "auth_type='{$prefix}' AND auth_parmname='{$k}' ")) $text .= $frm -> form_option($v, $sel, $k);
{ }
$sql -> db_Update('alt_auth', "auth_parmval='{$v}' WHERE auth_type='{$prefix}' AND auth_parmname='{$k}' "); $text .= $frm->form_select_close();
return $text;
}
/**
* Return the HTML needed to display the test form.
*
* @param string $prefix - the type of connection being tested
* @param $frm - the form object to use
*
* if $_POST['testauth'] is set, attempts to validate the connection, and displays any returned values
*/
public function alt_auth_test_form($prefix, $frm)
{
$text = $frm -> form_open('post', e_SELF, 'testform');
$text .= "<table class='table adminform'>
<tr><td colspan='2' class='forumheader2' style='text-align:center;'>".LAN_ALT_42."</td></tr>";
if (isset($_POST['testauth']))
{
// Try and connect to DB/server, and maybe validate user name
require_once(e_PLUGIN.'alt_auth/'.$prefix.'_auth.php');
$_login = new auth_login;
$log_result = AUTH_UNKNOWN;
$pass_vars = array();
$val_name = trim(varset($_POST['nametovalidate'],''));
if(isset($_login->Available) && ($_login->Available === FALSE))
{ // Relevant auth method not available (e.g. PHP extension not loaded)
$log_result = AUTH_NOT_AVAILABLE;
} }
else else
{ {
$sql -> db_Insert('alt_auth', "'{$prefix}','{$k}','{$v}' "); $log_result = $_login->login($val_name, $_POST['passtovalidate'], $pass_vars, ($val_name == ''));
} }
$text .= "<tr><td$log>".LAN_ALT_48;
if ($val_name)
{
$text .= "<br />".LAN_ALT_49.$val_name.'<br />'.LAN_ALT_50;
if (varset($_POST['passtovalidate'],'')) $text .= str_repeat('*',strlen($_POST['passtovalidate'])); else $text .= LAN_ALT_51;
}
$text .= "</td><td $log>";
switch ($log_result)
{
case AUTH_SUCCESS :
$text .= LAN_ALT_58;
if (count($pass_vars))
{
$text .= '<br />'.LAN_ALT_59;
foreach ($pass_vars as $k => $v)
{
$text .= '<br />&nbsp;&nbsp;'.$k.'=>'.$v;
}
}
break;
case AUTH_NOUSER :
$text .= LAN_ALT_52.LAN_ALT_55;
break;
case AUTH_BADPASSWORD :
$text .= LAN_ALT_52.LAN_ALT_56;
break;
case AUTH_NOCONNECT :
$text .= LAN_ALT_52.LAN_ALT_54;
break;
case AUTH_UNKNOWN :
$text .= LAN_ALT_52.LAN_ALT_53;
break;
case AUTH_NOT_AVAILABLE :
$text .= LAN_ALT_52.LAN_ALT_57;
break;
default :
$text .= "Coding error";
}
if (isset($_login ->ErrorText)) $text .= '<br />'.$_login ->ErrorText;
$text .= "</td></tr>";
} }
$text .= "<tr><td $log>".LAN_ALT_33."</td><td $log>";
$text .= $frm->form_text('nametovalidate', 35, '', 120);
$text .= "</td></tr>";
$text .= "<tr><td $log>".LAN_ALT_34."</td><td $log>";
$text .= $frm->form_password('passtovalidate', 35, '', 120);
$text .= "</td></tr>";
$text .= "<tr><td class='forumheader' colspan='2' style='text-align:center;'>";
// $text .= $frm->form_button("submit", 'testauth', LAN_ALT_47);
$text .= e107::getForm()->admin_button('testauth', LAN_ALT_47,'other');
$text .= "</td></tr>";
$text .= "</table>";
$text .= $frm->form_close();
return $text;
} }
$admin_log->log_event('AUTH_03',$prefix,E_LOG_INFORMATIVE,'');
return LAN_ALT_UPDATED;
}
/** //-----------------------------------------------
* Get the HTML for a password type selector. // VALUE COPY METHOD SELECTION
* //-----------------------------------------------
* @param string $name - name to be used for selector
* @param $frm - form object to use private $procListOpts = array(
* @param string $currentSelection - current value (if any) 'none' => LAN_ALT_70,
* @param boolean $getExtended - return all supported password types if TRUE, 'core' password types if FALSE 'bool1' => LAN_ALT_71,
*/ 'ucase' => LAN_ALT_72,
function altAuthGetPasswordSelector($name, $frm, $currentSelection = '', $getExtended = FALSE) 'lcase' => LAN_ALT_73,
{ 'ucfirst' => LAN_ALT_74,
$password_methods = ExtendedPasswordHandler::GetPasswordTypes($getExtended); 'ucwords' => LAN_ALT_75
$text = ""; );
$text .= $frm->form_select_open($name);
foreach($password_methods as $k => $v) /**
* Return a 'select' box for available processing methods
*/
public function alt_auth_processing($selName, $allowed='*', $curVal='')
{ {
$sel = ($currentSelection == $k) ? " Selected='selected'" : ''; if (($allowed == 'none') || ($allowed == '')) return '';
$text .= $frm -> form_option($v, $sel, $k); if ($allowed == '*')
} {
$text .= $frm->form_select_close(); $valid = $this->procListOpts; // We just want all the array keys to exist!
return $text;
}
/**
* Get configuration parameters for an authentication method
*
* @param string $prefix - the method
*
* @return array
*/
function altAuthGetParams($prefix)
{
$sql = e107::getDB();
$sql->db_Select('alt_auth', '*', "auth_type = '".$prefix."' ");
$parm = array();
while($row = $sql->db_Fetch())
{
$parm[$row['auth_parmname']] = base64_decode(base64_decode($row['auth_parmval']));
}
return $parm;
}
/**
* Return the HTML needed to display the test form.
*
* @param string $prefix - the type of connection being tested
* @param $frm - the form object to use
*
* if $_POST['testauth'] is set, attempts to validate the connection, and displays any returned values
*/
function alt_auth_test_form($prefix, $frm)
{
$text = $frm -> form_open('post', e_SELF, 'testform');
$text .= "<table class='table adminform'>
<tr><td colspan='2' class='forumheader2' style='text-align:center;'>".LAN_ALT_42."</td></tr>";
if (isset($_POST['testauth']))
{
// Try and connect to DB/server, and maybe validate user name
require_once(e_PLUGIN.'alt_auth/'.$prefix.'_auth.php');
$_login = new auth_login;
$log_result = AUTH_UNKNOWN;
$pass_vars = array();
$val_name = trim(varset($_POST['nametovalidate'],''));
if(isset($_login->Available) && ($_login->Available === FALSE))
{ // Relevant auth method not available (e.g. PHP extension not loaded)
$log_result = AUTH_NOT_AVAILABLE;
} }
else else
{ {
$log_result = $_login->login($val_name, $_POST['passtovalidate'], $pass_vars, ($val_name == '')); $valid = array_flip(explode(',', $allowed));
$valid['none'] = '1'; // Make sure this key exists - value doesn't matter
} }
$ret = "<select class='tbox' name='{$selName}' id='{$selName}'>\n";
$text .= "<tr><td$log>".LAN_ALT_48; foreach ($this->procListOpts as $k => $v)
if ($val_name)
{ {
$text .= "<br />".LAN_ALT_49.$val_name.'<br />'.LAN_ALT_50; if (isset($valid[$k]))
if (varset($_POST['passtovalidate'],'')) $text .= str_repeat('*',strlen($_POST['passtovalidate'])); else $text .= LAN_ALT_51; {
$s = ($curVal == $k) ? " selected='selected'" : '';
$ret .= "<option value='{$k}'{$s}>{$v}</option>\n";
}
} }
$text .= "</td><td $log>"; $ret .= "</select>\n";
switch ($log_result) // $ret .= $selName.':'.$curVal;
{ return $ret;
case AUTH_SUCCESS :
$text .= LAN_ALT_58;
if (count($pass_vars))
{
$text .= '<br />'.LAN_ALT_59;
foreach ($pass_vars as $k => $v)
{
$text .= '<br />&nbsp;&nbsp;'.$k.'=>'.$v;
}
}
break;
case AUTH_NOUSER :
$text .= LAN_ALT_52.LAN_ALT_55;
break;
case AUTH_BADPASSWORD :
$text .= LAN_ALT_52.LAN_ALT_56;
break;
case AUTH_NOCONNECT :
$text .= LAN_ALT_52.LAN_ALT_54;
break;
case AUTH_UNKNOWN :
$text .= LAN_ALT_52.LAN_ALT_53;
break;
case AUTH_NOT_AVAILABLE :
$text .= LAN_ALT_52.LAN_ALT_57;
break;
default :
$text .= "Coding error";
}
if (isset($_login ->ErrorText)) $text .= '<br />'.$_login ->ErrorText;
$text .= "</td></tr>";
} }
$text .= "<tr><td $log>".LAN_ALT_33."</td><td $log>";
$text .= $frm->form_text('nametovalidate', 35, '', 120);
$text .= "</td></tr>";
$text .= "<tr><td $log>".LAN_ALT_34."</td><td $log>";
$text .= $frm->form_password('passtovalidate', 35, '', 120);
$text .= "</td></tr>";
$text .= "<tr><td class='forumheader' colspan='2' style='text-align:center;'>";
// $text .= $frm->form_button("submit", 'testauth', LAN_ALT_47);
$text .= e107::getForm()->admin_button('testauth', LAN_ALT_47,'other');
$text .= "</td></tr>";
$text .= "</table>";
$text .= $frm->form_close();
return $text;
}
//-----------------------------------------------
// VALUE COPY METHOD SELECTION
//-----------------------------------------------
$procListOpts = array(
'none' => LAN_ALT_70,
'bool1' => LAN_ALT_71,
'ucase' => LAN_ALT_72,
'lcase' => LAN_ALT_73,
'ucfirst' => LAN_ALT_74,
'ucwords' => LAN_ALT_75
);
// Return a 'select' box for available processing methods
function alt_auth_processing($selName, $allowed='*', $curVal='')
{
global $procListOpts;
if (($allowed == 'none') || ($allowed == '')) return '';
if ($allowed == '*')
{
$valid = $procListOpts; // We just want all the array keys to exist!
}
else
{
$valid = array_flip(explode(',',$allowed));
$valid['none'] = '1'; // Make sure this key exists - value doesn't matter
}
$ret = "<select class='tbox' name='{$selName}' id='{$selName}'>\n";
foreach ($procListOpts as $k => $v)
{
if (isset($valid[$k]))
{
$s = ($curVal == $k) ? " selected='selected'" : '';
$ret .= "<option value='{$k}'{$s}>{$v}</option>\n";
}
}
$ret .= "</select>\n";
// $ret .= $selName.':'.$curVal;
return $ret;
} }
function alt_auth_adminmenu() function alt_auth_adminmenu()
{ {
global $authlist; echo ' ';
echo " ";
if(!is_array($authlist)) if(!is_array($authlist))
{ {
$authlist = alt_auth_get_authlist(); $authlist = alt_auth_admin::alt_auth_get_authlist();
} }
define("ALT_AUTH_ACTION", "main"); define('ALT_AUTH_ACTION', 'main');
$var['main']['text'] = LAN_ALT_31; $var['main']['text'] = LAN_ALT_31;
$var['main']['link'] = e_PLUGIN."alt_auth/alt_auth_conf.php"; $var['main']['link'] = e_PLUGIN.'alt_auth/alt_auth_conf.php';
show_admin_menu("alt auth", ALT_AUTH_ACTION, $var); show_admin_menu('alt auth', ALT_AUTH_ACTION, $var);
$var = array(); $var = array();
foreach($authlist as $a) foreach($authlist as $a)
{ {

View File

@@ -1,226 +1,232 @@
<?php <?php
/* /*
* e107 website system * e107 website system
* *
* Copyright (C) 2008-2011 e107 Inc (e107.org) * Copyright (C) 2008-2011 e107 Inc (e107.org)
* Released under the terms and conditions of the * Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
* *
* Alt_auth plugin - general configuration * Alt_auth plugin - general configuration
* *
* $URL$ * $URL$
* $Id$ * $Id$
* *
*/ */
/** /**
* e107 Alternate authorisation plugin * e107 Alternate authorisation plugin
* *
* @package e107_plugins * @package e107_plugins
* @subpackage alt_auth * @subpackage alt_auth
* @version $Id$; * @version $Id$;
*/ */
/* /*
@todo: @todo:
1. Change prefs handling 1. Change prefs handling
2. Change admin log references 2. Change admin log references
*/ */
$eplug_admin = true; $eplug_admin = true;
require_once('../../class2.php'); require_once('../../class2.php');
if(!getperms('P') || !e107::isInstalled('alt_auth')) if(!getperms('P') || !e107::isInstalled('alt_auth'))
{ {
header('location:'.e_BASE.'index.php'); header('location:'.e_BASE.'index.php');
exit(); exit();
} }
require_once(e_HANDLER.'form_handler.php'); require_once(e_HANDLER.'form_handler.php');
$frm = e107::getForm(); $frm = e107::getForm();
require_once(e_ADMIN.'auth.php'); require_once(e_ADMIN.'auth.php');
include_lan(e_PLUGIN.'alt_auth/languages/'.e_LANGUAGE.'/admin_alt_auth.php'); include_lan(e_PLUGIN.'alt_auth/languages/'.e_LANGUAGE.'/admin_alt_auth.php');
define('ALT_AUTH_ACTION', 'main'); define('ALT_AUTH_ACTION', 'main');
require_once(e_PLUGIN.'alt_auth/alt_auth_adminmenu.php'); require_once(e_PLUGIN.'alt_auth/alt_auth_adminmenu.php');
require_once(e_HANDLER.'user_extended_class.php'); require_once(e_HANDLER.'user_extended_class.php');
$euf = new e107_user_extended; $euf = new e107_user_extended;
if(isset($_POST['updateprefs'])) $pref = e107::pref('core');
{
unset($temp); if(isset($_POST['updateprefs']))
$temp['auth_method'] = $tp->toDB($_POST['auth_method']); {
$temp['auth_noconn'] = intval($_POST['auth_noconn']); unset($temp);
$temp['auth_method2'] = $tp->toDB($_POST['auth_method2']); $temp['auth_method'] = $tp->toDB($_POST['auth_method']);
$temp['auth_badpassword'] = intval($_POST['auth_badpassword']); $temp['auth_noconn'] = intval($_POST['auth_noconn']);
if ($admin_log->logArrayDiffs($temp, $pref, 'AUTH_01')) $temp['auth_method2'] = $tp->toDB($_POST['auth_method2']);
{ $temp['auth_badpassword'] = intval($_POST['auth_badpassword']);
save_prefs(); // Only save if changes if ($admin_log->logArrayDiffs($temp, $pref, 'AUTH_01'))
header('location:'.e_SELF); {
exit; save_prefs(); // Only save if changes @TODO:
} header('location:'.e_SELF);
} exit;
}
}
if(isset($_POST['updateeufs']))
{
$authExtended = array(); if(isset($_POST['updateeufs']))
foreach ($_POST['auth_euf_include'] as $au) {
{ $authExtended = array();
$authExtended[] = trim($tp->toDB($au)); foreach ($_POST['auth_euf_include'] as $au)
} {
$au = implode(',',$authExtended); $authExtended[] = trim($tp->toDB($au));
if ($au != $pref['auth_extended']) }
{ $au = implode(',',$authExtended);
$pref['auth_extended'] = $au; if ($au != $pref['auth_extended'])
save_prefs(); {
$admin_log->log_event('AUTH_02',$au,''); $pref['auth_extended'] = $au; // @TODO:
} save_prefs();
} $admin_log->log_event('AUTH_02',$au,'');
}
// Avoid need for lots of checks later }
if (!isset($pref['auth_badpassword'])) $pref['auth_badpassword'] = 0;
if (!isset($pref['auth_noconn'])) $pref['auth_noconn'] = 0; // Avoid need for lots of checks later
if (!isset($pref['auth_badpassword'])) $pref['auth_badpassword'] = 0;
// Convert prefs if (!isset($pref['auth_noconn'])) $pref['auth_noconn'] = 0;
if (isset($pref['auth_nouser']))
{ // Convert prefs
$pref['auth_method2'] = 'none'; // Default to no fallback if (isset($pref['auth_nouser']))
if ($pref['auth_nouser']) {
{ $pref['auth_method2'] = 'none'; // Default to no fallback
$pref['auth_method2'] = 'e107'; if ($pref['auth_nouser'])
} {
unset($pref['auth_nouser']); $pref['auth_method2'] = 'e107';
if (!isset($pref['auth_badpassword'])) $pref['auth_badpassword'] = 0; }
save_prefs(); unset($pref['auth_nouser']);
} if (!isset($pref['auth_badpassword'])) $pref['auth_badpassword'] = 0;
save_prefs(); // @TODO
}
$authlist = alt_auth_get_authlist();
if (isset($pref['auth_extended']))
{ $authlist = alt_auth_admin::alt_auth_get_authlist();
$authExtended = explode(',',$pref['auth_extended']); if (isset($pref['auth_extended']))
} {
else $authExtended = explode(',',$pref['auth_extended']);
{ }
$pref['auth_extended'] = ''; else
$authExtended = array(); {
} $pref['auth_extended'] = '';
$authExtended = array();
}
if(isset($message))
{
e107::getRender()->tablerender('', "<div style='text-align:center'><b>".$message."</b></div>"); if(isset($message))
} {
e107::getRender()->tablerender('', "<div style='text-align:center'><b>".$message."</b></div>");
$text = " }
<div>
<form method='post' action='".e_SELF."'>
<table class='table adminform'> $altAuthAdmin = new alt_auth_admin();
<colgroup span='2'>
<col class='col-label' />
<col class='col-control' /> $text = "
</colgroup> <div>
<tr> <form method='post' action='".e_SELF."'>
<td>".LAN_ALT_1.": </td> <table class='table adminform'>
<td>". <colgroup span='2'>
alt_auth_get_dropdown('auth_method', $pref['auth_method'], 'e107')." <col class='col-label' />
</td> <col class='col-control' />
</tr> </colgroup>
<tr>
<tr> <td>".LAN_ALT_1.": </td>
<td>".LAN_ALT_78.":<br /></td> <td>".
<td> $altAuthAdmin->alt_auth_get_dropdown('auth_method', $pref['auth_method'], 'e107')."
<select class='tbox' name='auth_badpassword'>"; </td>
$sel = (!$pref['auth_badpassword'] ? "" : " selected = 'selected' "); </tr>
$text .= "<option value='0' {$sel} >".LAN_ALT_FAIL."</option>";
$sel = ($pref['auth_badpassword'] ? " selected = 'selected' " : ""); <tr>
$text .= "<option value='1' {$sel} >".LAN_ALT_FALLBACK."</option> <td>".LAN_ALT_78.":<br /></td>
</select><div class='smalltext field-help'>".LAN_ALT_79."</div> <td>
</td> <select class='tbox' name='auth_badpassword'>";
</tr> $sel = (!$pref['auth_badpassword'] ? "" : " selected = 'selected' ");
$text .= "<option value='0' {$sel} >".LAN_ALT_FAIL."</option>";
<tr> $sel = ($pref['auth_badpassword'] ? " selected = 'selected' " : "");
<td>".LAN_ALT_6.":<br /></td> $text .= "<option value='1' {$sel} >".LAN_ALT_FALLBACK."</option>
<td> </select><div class='smalltext field-help'>".LAN_ALT_79."</div>
<select class='tbox' name='auth_noconn'>"; </td>
$sel = (!$pref['auth_noconn'] ? '' : " selected = 'selected' "); </tr>
$text .= "<option value='0' {$sel} >".LAN_ALT_FAIL."</option>";
$sel = ($pref['auth_noconn'] ? " selected = 'selected' " : ''); <tr>
$text .= "<option value='1' {$sel} >".LAN_ALT_FALLBACK."</option> <td>".LAN_ALT_6.":<br /></td>
</select><div class='smalltext field-help'>".LAN_ALT_7."</div> <td>
</td> <select class='tbox' name='auth_noconn'>";
</tr> $sel = (!$pref['auth_noconn'] ? '' : " selected = 'selected' ");
$text .= "<option value='0' {$sel} >".LAN_ALT_FAIL."</option>";
<tr> $sel = ($pref['auth_noconn'] ? " selected = 'selected' " : '');
<td>".LAN_ALT_8.":<br /> $text .= "<option value='1' {$sel} >".LAN_ALT_FALLBACK."</option>
</select><div class='smalltext field-help'>".LAN_ALT_7."</div>
</td> </td>
<td>".alt_auth_get_dropdown('auth_method2', $pref['auth_method2'], 'none')." </tr>
<div class='smalltext field-help'>".LAN_ALT_9."</div>
</td> <tr>
</tr> <td>".LAN_ALT_8.":<br />
</table>
</td>
<div class='buttons-bar center'>". <td>".$altAuthAdmin->alt_auth_get_dropdown('auth_method2', $pref['auth_method2'], 'none')."
$frm->admin_button('updateprefs',LAN_UPDATE,'update')." <div class='smalltext field-help'>".LAN_ALT_9."</div>
</div> </td>
</form> </tr>
</div>"; </table>
$ns = e107::getRender();
<div class='buttons-bar center'>".
$ns->tablerender(LAN_ALT_3, $text); $frm->admin_button('updateprefs',LAN_UPDATE,'update')."
</div>
</form>
if ($euf->userCount) </div>";
{ $ns = e107::getRender();
include_lan(e_LANGUAGEDIR.e_LANGUAGE.'/lan_user_extended.php');
$fl = &$euf->fieldDefinitions; $ns->tablerender(LAN_ALT_3, $text);
$text = "<div>
<form method='post' action='".e_SELF."'>
<table class='table adminlist'> if ($euf->userCount)
<colgroup> {
<col style='width:10%' /> include_lan(e_LANGUAGEDIR.e_LANGUAGE.'/lan_user_extended.php');
<col style='width:30%' /> $fl = &$euf->fieldDefinitions;
<col style='width:40%' /> $text = "<div>
<col style='width:20%' /> <form method='post' action='".e_SELF."'>
</colgroup>\n"; <table class='table adminlist'>
<colgroup>
$text .= "<thead><tr> <col style='width:10%' />
<th class='center'>".LAN_ALT_61."</th> <col style='width:30%' />
<th>".LAN_ALT_62."</th> <col style='width:40%' />
<th>".LAN_ALT_63."</th> <col style='width:20%' />
<th>".LAN_ALT_64."</th> </colgroup>\n";
</tr>
</thead> $text .= "<thead><tr>
<tbody>"; <th class='center'>".LAN_ALT_61."</th>
foreach ($fl as $f) <th>".LAN_ALT_62."</th>
{ <th>".LAN_ALT_63."</th>
$checked = (in_array($f['user_extended_struct_name'], $authExtended) ? " checked='checked'" : ''); <th>".LAN_ALT_64."</th>
$text .= "<tr> </tr>
<td class='center'><input type='checkbox' name='auth_euf_include[]' value='{$f['user_extended_struct_name']}'{$checked} /></td> </thead>
<td>{$f['user_extended_struct_name']}</td> <tbody>";
<td>".$tp->toHTML($f['user_extended_struct_text'],FALSE,'TITLE')."</td> foreach ($fl as $f)
<td>{$euf->user_extended_types[$f['user_extended_struct_type']]}</td></tr>\n"; {
} $checked = (in_array($f['user_extended_struct_name'], $authExtended) ? " checked='checked'" : '');
$text .= "</tbody> $text .= "<tr>
</table><div class='buttons-bar center'> <td class='center'><input type='checkbox' name='auth_euf_include[]' value='{$f['user_extended_struct_name']}'{$checked} /></td>
".$frm->admin_button('updateeufs',LAN_UPDATE,'update')." <td>{$f['user_extended_struct_name']}</td>
<td>".$tp->toHTML($f['user_extended_struct_text'],FALSE,'TITLE')."</td>
</div> <td>{$euf->user_extended_types[$f['user_extended_struct_type']]}</td></tr>\n";
}
</form> $text .= "</tbody>
</div>"; </table><div class='buttons-bar center'>
e107::getRender()->tablerender(LAN_ALT_60, $text); ".$frm->admin_button('updateeufs',LAN_UPDATE,'update')."
</div>
}
</form>
</div>";
require_once(e_ADMIN.'footer.php'); e107::getRender()->tablerender(LAN_ALT_60, $text);
function alt_auth_conf_adminmenu()
{ }
alt_auth_adminmenu();
}
require_once(e_ADMIN.'footer.php');
function alt_auth_conf_adminmenu()
{
alt_auth_adminmenu();
}
?> ?>

View File

@@ -1,258 +1,293 @@
<?php <?php
/* /*
* e107 website system * e107 website system
* *
* Copyright (C) 2008-2011 e107 Inc (e107.org) * Copyright (C) 2008-2011 e107 Inc (e107.org)
* Released under the terms and conditions of the * Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
* *
* Alternate login * Alternate login
* *
* $URL$ * $URL$
* $Id$ * $Id$
* *
*/ */
/** /**
* e107 Alternate authorisation plugin * e107 Alternate authorisation plugin
* *
* @package e107_plugins * @package e107_plugins
* @subpackage alt_auth * @subpackage alt_auth
* @version $Id$; * @version $Id$;
*/ */
define('AA_DEBUG',FALSE); define('AA_DEBUG',FALSE);
define('AA_DEBUG1',FALSE); define('AA_DEBUG1',FALSE);
//TODO convert to class constants (but may be more useful as globals, perhaps within a general login manager scheme) //TODO convert to class constants (but may be more useful as globals, perhaps within a general login manager scheme)
define('AUTH_SUCCESS', -1); define('AUTH_SUCCESS', -1);
define('AUTH_NOUSER', 1); define('AUTH_NOUSER', 1);
define('AUTH_BADPASSWORD', 2); define('AUTH_BADPASSWORD', 2);
define('AUTH_NOCONNECT', 3); define('AUTH_NOCONNECT', 3);
define('AUTH_UNKNOWN', 4); define('AUTH_UNKNOWN', 4);
define('AUTH_NOT_AVAILABLE', 5); define('AUTH_NOT_AVAILABLE', 5);
define('AUTH_NORESOURCE', 6); // Used to indicate, for example, that a required PHP module isn't loaded define('AUTH_NORESOURCE', 6); // Used to indicate, for example, that a required PHP module isn't loaded
class alt_login
{ /**
protected $e107; * Methods used by a number of alt_auth classes.
public $loginResult = false; * The login authorisation classes are descendants of this one.
* Admin functions also use it - a little extra overhead by including this file, but less of a problem for admin
public function __construct($method, &$username, &$userpass) */
{ class alt_auth_base
$this->e107 = e107::getInstance(); {
$newvals=array(); public function __construct()
{
if ($method == 'none') }
{
$this->loginResult = AUTH_NOCONNECT;
return; /**
} * Get configuration parameters for an authentication method
*
require_once(e_PLUGIN.'alt_auth/'.$method.'_auth.php'); * @param string $prefix - the method
$_login = new auth_login; *
* @return array
if(isset($_login->Available) && ($_login->Available === FALSE)) */
{ // Relevant auth method not available (e.g. PHP extension not loaded) public function altAuthGetParams($prefix)
$this->loginResult = AUTH_NOT_AVAILABLE; {
return; $sql = e107::getDb();
}
$sql->db_Select('alt_auth', '*', "auth_type = '".$prefix."' ");
$login_result = $_login->login($username, $userpass, $newvals, FALSE); $parm = array();
while($row = $sql->db_Fetch())
if($login_result === AUTH_SUCCESS ) {
{ $parm[$row['auth_parmname']] = base64_decode(base64_decode($row['auth_parmval']));
require_once (e_HANDLER.'user_handler.php'); }
require_once(e_HANDLER.'validator_class.php'); return $parm;
}
if (MAGIC_QUOTES_GPC == FALSE) }
{
$username = mysql_real_escape_string($username);
} class alt_login
$username = preg_replace("/\sOR\s|\=|\#/", "", $username); {
$username = substr($username, 0, e107::getPref('loginname_maxlength')); protected $e107;
public $loginResult = false;
$aa_sql = e107::getDb('aa');
$userMethods = new UserHandler; public function __construct($method, &$username, &$userpass)
$db_vals = array('user_password' => $aa_sql->escape($userMethods->HashPassword($userpass,$username))); {
$xFields = array(); // Possible extended user fields $this->e107 = e107::getInstance();
$newvals=array();
// See if any of the fields need processing before save
if (isset($_login->copyMethods) && count($_login->copyMethods)) if ($method == 'none')
{ {
foreach ($newvals as $k => $v) $this->loginResult = AUTH_NOCONNECT;
{ return;
if (isset($_login->copyMethods[$k])) }
{
$newvals[$k] = $this->translate($_login->copyMethods[$k], $v); require_once(e_PLUGIN.'alt_auth/'.$method.'_auth.php');
if (AA_DEBUG1) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth convert",$k.': '.$v.'=>'.$newvals[$k],FALSE,LOG_TO_ROLLING); $_login = new auth_login;
}
} if(isset($_login->Available) && ($_login->Available === FALSE))
} { // Relevant auth method not available (e.g. PHP extension not loaded)
foreach ($newvals as $k => $v) $this->loginResult = AUTH_NOT_AVAILABLE;
{ return;
if (strpos($k,'x_') === 0) }
{ // Extended field
$k = substr($k,2); $login_result = $_login->login($username, $userpass, $newvals, FALSE);
$xFields['user_'.$k] = $v;
} if($login_result === AUTH_SUCCESS )
else {
{ // Normal user table require_once (e_HANDLER.'user_handler.php');
if (strpos($k,'user_' !== 0)) $k = 'user_'.$k; // translate the field names (but latest handlers don't need translation) require_once(e_HANDLER.'validator_class.php');
$db_vals[$k] = $v;
} if (MAGIC_QUOTES_GPC == FALSE)
} {
$ulogin = new userlogin(); $username = mysql_real_escape_string($username);
if (count($xFields)) }
{ // We're going to have to do something with extended fields as well - make sure there's an object $username = preg_replace("/\sOR\s|\=|\#/", "", $username);
require_once (e_HANDLER.'user_extended_class.php'); $username = substr($username, 0, e107::getPref('loginname_maxlength'));
$ue = new e107_user_extended;
$q = $aa_sql = e107::getDb('aa');
$qry = "SELECT u.user_id,u.".implode(',u.',array_keys($db_vals)).", ue.user_extended_id, ue.".implode(',ue.',array_keys($xFields))." FROM `#user` AS u $userMethods = new UserHandler;
LEFT JOIN `#user_extended` AS ue ON ue.user_extended_id = u.user_id $db_vals = array('user_password' => $aa_sql->escape($userMethods->HashPassword($userpass,$username)));
WHERE ".$ulogin->getLookupQuery($username, FALSE, 'u.'); $xFields = array(); // Possible extended user fields
if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","Query: {$qry}[!br!]".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING);
} // See if any of the fields need processing before save
else if (isset($_login->copyMethods) && count($_login->copyMethods))
{ {
$qry = "SELECT * FROM `#user` WHERE ".$ulogin->getLookupQuery($username, FALSE); foreach ($newvals as $k => $v)
} {
if($aa_sql -> db_Select_gen($qry)) if (isset($_login->copyMethods[$k]))
{ // Existing user - get current data, see if any changes {
$row = $aa_sql->db_Fetch(MYSQL_ASSOC); $newvals[$k] = $this->translate($_login->copyMethods[$k], $v);
foreach ($db_vals as $k => $v) if (AA_DEBUG1) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth convert",$k.': '.$v.'=>'.$newvals[$k],FALSE,LOG_TO_ROLLING);
{ }
if ($row[$k] == $v) unset($db_vals[$k]); }
} }
if (count($db_vals)) foreach ($newvals as $k => $v)
{ {
$newUser = array(); if (strpos($k,'x_') === 0)
$newUser['data'] = $db_vals; { // Extended field
validatorClass::addFieldTypes($userMethods->userVettingInfo,$newUser); $k = substr($k,2);
$newUser['WHERE'] = '`user_id`='.$row['user_id']; $xFields['user_'.$k] = $v;
$aa_sql->db_Update('user',$newUser); }
if (AA_DEBUG1) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","User data update: ".print_r($newUser,TRUE),FALSE,LOG_TO_ROLLING); else
} { // Normal user table
foreach ($xFields as $k => $v) if (strpos($k,'user_' !== 0)) $k = 'user_'.$k; // translate the field names (but latest handlers don't need translation)
{ $db_vals[$k] = $v;
if ($row[$k] == $v) unset($xFields[$k]); }
} }
if (AA_DEBUG1) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","User data read: ".print_r($row,TRUE)."[!br!]".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING); $ulogin = new userlogin();
if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","User xtnd read: ".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING); if (count($xFields))
if (count($xFields)) { // We're going to have to do something with extended fields as well - make sure there's an object
{ require_once (e_HANDLER.'user_extended_class.php');
$xArray = array(); $ue = new e107_user_extended;
$xArray['data'] = $xFields; $q =
if ($row['user_extended_id']) $qry = "SELECT u.user_id,u.".implode(',u.',array_keys($db_vals)).", ue.user_extended_id, ue.".implode(',ue.',array_keys($xFields))." FROM `#user` AS u
{ LEFT JOIN `#user_extended` AS ue ON ue.user_extended_id = u.user_id
$ue->addFieldTypes($xArray); // Add in the data types for storage WHERE ".$ulogin->getLookupQuery($username, FALSE, 'u.');
$xArray['WHERE'] = '`user_extended_id`='.intval($row['user_id']); if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","Query: {$qry}[!br!]".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING);
if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","User xtnd update: ".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING); }
$aa_sql->db_Update('user_extended',$xArray ); else
} {
else $qry = "SELECT * FROM `#user` WHERE ".$ulogin->getLookupQuery($username, FALSE);
{ // Never been an extended user fields record for this user }
$xArray['data']['user_extended_id'] = $row['user_id']; if($aa_sql -> db_Select_gen($qry))
$ue->addDefaultFields($xArray); // Add in the data types for storage, plus any default values { // Existing user - get current data, see if any changes
if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","Write new extended record".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING); $row = $aa_sql->db_Fetch(MYSQL_ASSOC);
$aa_sql->db_Insert('user_extended',$xArray); foreach ($db_vals as $k => $v)
} {
} if ($row[$k] == $v) unset($db_vals[$k]);
} }
else if (count($db_vals))
{ // Just add a new user {
$newUser = array();
if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","Add new user: ".print_r($db_vals,TRUE)."[!br!]".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING); $newUser['data'] = $db_vals;
if (!isset($db_vals['user_name'])) $db_vals['user_name'] = $username; validatorClass::addFieldTypes($userMethods->userVettingInfo,$newUser);
if (!isset($db_vals['user_loginname'])) $db_vals['user_loginname'] = $username; $newUser['WHERE'] = '`user_id`='.$row['user_id'];
if (!isset($db_vals['user_join'])) $db_vals['user_join'] = time(); $aa_sql->db_Update('user',$newUser);
$db_vals['user_class'] = e107::getPref('initial_user_classes'); if (AA_DEBUG1) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","User data update: ".print_r($newUser,TRUE),FALSE,LOG_TO_ROLLING);
if (!isset($db_vals['user_signature'])) $db_vals['user_signature'] = ''; }
if (!isset($db_vals['user_prefs'])) $db_vals['user_prefs'] = ''; foreach ($xFields as $k => $v)
if (!isset($db_vals['user_perms'])) $db_vals['user_perms'] = ''; {
$userMethods->userClassUpdate($db_vals, 'userall'); if ($row[$k] == $v) unset($xFields[$k]);
$newUser = array(); }
$newUser['data'] = $db_vals; if (AA_DEBUG1) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","User data read: ".print_r($row,TRUE)."[!br!]".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING);
$userMethods->addNonDefaulted($newUser); if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","User xtnd read: ".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING);
validatorClass::addFieldTypes($userMethods->userVettingInfo,$newUser); if (count($xFields))
$newID = $aa_sql->db_Insert('user',$newUser); {
if ($newID !== FALSE) $xArray = array();
{ $xArray['data'] = $xFields;
if (count($xFields)) if ($row['user_extended_id'])
{ {
$xFields['user_extended_id'] = $newID; $ue->addFieldTypes($xArray); // Add in the data types for storage
$xArray = array(); $xArray['WHERE'] = '`user_extended_id`='.intval($row['user_id']);
$xArray['data'] = $xFields; if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","User xtnd update: ".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING);
$ue->addDefaultFields($xArray); // Add in the data types for storage, plus any default values $aa_sql->db_Update('user_extended',$xArray );
$result = $aa_sql->db_Insert('user_extended',$xArray); }
if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),'DEBUG','Alt auth login',"Add extended: UID={$newID} result={$result}",FALSE,LOG_TO_ROLLING); else
} { // Never been an extended user fields record for this user
} $xArray['data']['user_extended_id'] = $row['user_id'];
else $ue->addDefaultFields($xArray); // Add in the data types for storage, plus any default values
{ // Error adding user to database - possibly a conflict on unique fields if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","Write new extended record".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING);
$this->e107->admin_log->e_log_event(10,__FILE__.'|'.__FUNCTION__.'@'.__LINE__,'ALT_AUTH','Alt auth login','Add user fail: DB Error '.$aa_sql->getLastErrorText()."[!br!]".print_r($db_vals,TRUE),FALSE,LOG_TO_ROLLING); $aa_sql->db_Insert('user_extended',$xArray);
$this->loginResult = LOGIN_DB_ERROR; }
return; }
} }
} else
$this->loginResult = LOGIN_CONTINUE; { // Just add a new user
return;
} if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),"DEBUG","Alt auth login","Add new user: ".print_r($db_vals,TRUE)."[!br!]".print_r($xFields,TRUE),FALSE,LOG_TO_ROLLING);
else if (!isset($db_vals['user_name'])) $db_vals['user_name'] = $username;
{ // Failure modes if (!isset($db_vals['user_loginname'])) $db_vals['user_loginname'] = $username;
switch($login_result) if (!isset($db_vals['user_join'])) $db_vals['user_join'] = time();
{ $db_vals['user_class'] = e107::getPref('initial_user_classes');
case AUTH_NOCONNECT: if (!isset($db_vals['user_signature'])) $db_vals['user_signature'] = '';
if(varset(e107::getPref('auth_noconn'), TRUE)) if (!isset($db_vals['user_prefs'])) $db_vals['user_prefs'] = '';
{ if (!isset($db_vals['user_perms'])) $db_vals['user_perms'] = '';
$this->loginResult = LOGIN_TRY_OTHER; $userMethods->userClassUpdate($db_vals, 'userall');
return; $newUser = array();
} $newUser['data'] = $db_vals;
$username=md5('xx_noconn_xx'); $userMethods->addNonDefaulted($newUser);
$this->loginResult = LOGIN_ABORT; validatorClass::addFieldTypes($userMethods->userVettingInfo,$newUser);
return; $newID = $aa_sql->db_Insert('user',$newUser);
case AUTH_BADPASSWORD: if ($newID !== FALSE)
if(varset(e107::getPref('auth_badpassword'), TRUE)) {
{ if (count($xFields))
$this->loginResult = LOGIN_TRY_OTHER; {
return; $xFields['user_extended_id'] = $newID;
} $xArray = array();
$userpass=md5('xx_badpassword_xx'); $xArray['data'] = $xFields;
$this->loginResult = LOGIN_ABORT; // Not going to magically be able to log in! $ue->addDefaultFields($xArray); // Add in the data types for storage, plus any default values
return; $result = $aa_sql->db_Insert('user_extended',$xArray);
} if (AA_DEBUG) $this->e107->admin_log->e_log_event(10,debug_backtrace(),'DEBUG','Alt auth login',"Add extended: UID={$newID} result={$result}",FALSE,LOG_TO_ROLLING);
} }
$this->loginResult = LOGIN_ABORT; // catch-all just in case }
return; else
} { // Error adding user to database - possibly a conflict on unique fields
$this->e107->admin_log->e_log_event(10,__FILE__.'|'.__FUNCTION__.'@'.__LINE__,'ALT_AUTH','Alt auth login','Add user fail: DB Error '.$aa_sql->getLastErrorText()."[!br!]".print_r($db_vals,TRUE),FALSE,LOG_TO_ROLLING);
$this->loginResult = LOGIN_DB_ERROR;
// Function to implement copy methods return;
public function translate($method, $word) }
{ }
$tp = e107::getParser(); $this->loginResult = LOGIN_CONTINUE;
switch ($method) return;
{ }
case 'bool1' : else
switch ($tp->ustrtoupper($word)) { // Failure modes
{ switch($login_result)
case 'TRUE' : return TRUE; {
case 'FALSE' : return FALSE; case AUTH_NOCONNECT:
} if(varset(e107::getPref('auth_noconn'), TRUE))
return $word; {
case 'ucase' : $this->loginResult = LOGIN_TRY_OTHER;
return $tp->ustrtoupper($word); return;
case 'lcase' : }
return $tp->ustrtolower($word); $username=md5('xx_noconn_xx');
case 'ucfirst' : $this->loginResult = LOGIN_ABORT;
return ucfirst($word); // TODO: Needs changing to utf-8 function return;
case 'ucwords' : case AUTH_BADPASSWORD:
return ucwords($word); // TODO: Needs changing to utf-8 function if(varset(e107::getPref('auth_badpassword'), TRUE))
case 'none' : {
return $word; $this->loginResult = LOGIN_TRY_OTHER;
} return;
} }
$userpass=md5('xx_badpassword_xx');
} $this->loginResult = LOGIN_ABORT; // Not going to magically be able to log in!
return;
}
}
$this->loginResult = LOGIN_ABORT; // catch-all just in case
return;
}
// Function to implement copy methods
public function translate($method, $word)
{
$tp = e107::getParser();
switch ($method)
{
case 'bool1' :
switch ($tp->ustrtoupper($word))
{
case 'TRUE' : return TRUE;
case 'FALSE' : return FALSE;
}
return $word;
case 'ucase' :
return $tp->ustrtoupper($word);
case 'lcase' :
return $tp->ustrtolower($word);
case 'ucfirst' :
return ucfirst($word); // TODO: Needs changing to utf-8 function
case 'ucwords' :
return ucwords($word); // TODO: Needs changing to utf-8 function
case 'none' :
return $word;
}
}
}
?> ?>

View File

@@ -1,181 +1,181 @@
<?php <?php
/* /*
* e107 website system * e107 website system
* *
* Copyright (C) 2008-2012 e107 Inc (e107.org) * Copyright (C) 2008-2012 e107 Inc (e107.org)
* Released under the terms and conditions of the * Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
* *
* e107 DB authorisation for alt_auth plugin * e107 DB authorisation for alt_auth plugin
* *
* $URL$ * $URL$
* $Id$ * $Id$
*/ */
/** /**
* e107 Alternate authorisation plugin * e107 Alternate authorisation plugin
* *
* @package e107_plugins * @package e107_plugins
* @subpackage alt_auth * @subpackage alt_auth
* @version $Id$; * @version $Id$;
* *
* This connects to a 'foreign' e107 user database to validate the user * This connects to a 'foreign' e107 user database to validate the user
*/ */
/* /*
return values return values
AUTH_NOCONNECT = unable to connect to db AUTH_NOCONNECT = unable to connect to db
AUTH_NOUSER = user not found AUTH_NOUSER = user not found
AUTH_BADPASSWORD = supplied password incorrect AUTH_BADPASSWORD = supplied password incorrect
AUTH_SUCCESS = valid login AUTH_SUCCESS = valid login
*/ */
class auth_login class auth_login extends alt_auth_base
{ {
public $Available = FALSE; // Flag indicates whether DB connection available public $Available = FALSE; // Flag indicates whether DB connection available
public $ErrorText; // e107 error string on exit public $ErrorText; // e107 error string on exit
private $conf; // Configuration parameters private $conf; // Configuration parameters
/** /**
* Read configuration, initialise connection to remote e107 database * Read configuration, initialise connection to remote e107 database
* *
* @return AUTH_xxxx result code * @return AUTH_xxxx result code
*/ */
public function __construct() public function __construct()
{ {
$this->ErrorText = ''; $this->ErrorText = '';
$this->conf = altAuthGetParams('e107db'); $this->conf = $this->altAuthGetParams('e107db');
$this->Available = TRUE; $this->Available = TRUE;
} }
/** /**
* Retrieve and construct error strings * Retrieve and construct error strings
* *
* @todo - test whether reconnect to DB is required (shouldn't be) * @todo - test whether reconnect to DB is required (shouldn't be)
*/ */
private function makeErrorText($extra = '') private function makeErrorText($extra = '')
{ {
$this->ErrorText = $extra; $this->ErrorText = $extra;
//global $mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb, $sql; //global $mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb, $sql;
//$sql->db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb); //$sql->db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb);
} }
/** /**
* Validate login credentials * Validate login credentials
* *
* @param string $uname - The user name requesting access * @param string $uname - The user name requesting access
* @param string $pass - Password to use (usually plain text) * @param string $pass - Password to use (usually plain text)
* @param pointer &$newvals - pointer to array to accept other data read from database * @param pointer &$newvals - pointer to array to accept other data read from database
* @param boolean $connect_only - TRUE to simply connect to the database * @param boolean $connect_only - TRUE to simply connect to the database
* *
* @return integer result (AUTH_xxxx) * @return integer result (AUTH_xxxx)
* *
* On a successful login, &$newvals array is filled with the requested data from the server * On a successful login, &$newvals array is filled with the requested data from the server
*/ */
public function login($uname, $pword, &$newvals, $connect_only = FALSE) public function login($uname, $pword, &$newvals, $connect_only = FALSE)
{ {
//Attempt to open connection to sql database //Attempt to open connection to sql database
if(!$res = mysql_connect($this->conf['e107db_server'], $this->conf['e107db_username'], $this->conf['e107db_password'])) if(!$res = mysql_connect($this->conf['e107db_server'], $this->conf['e107db_username'], $this->conf['e107db_password']))
{ {
$this->makeErrorText('Cannot connect to remote server'); $this->makeErrorText('Cannot connect to remote server');
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
//Select correct db //Select correct db
if(!mysql_select_db($this->conf['e107db_database'], $res)) if(!mysql_select_db($this->conf['e107db_database'], $res))
{ {
mysql_close($res); mysql_close($res);
$this->makeErrorText('Cannot connect to remote DB'); $this->makeErrorText('Cannot connect to remote DB');
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
if ($connect_only) return AUTH_SUCCESS; // Test mode may just want to connect to the DB if ($connect_only) return AUTH_SUCCESS; // Test mode may just want to connect to the DB
$sel_fields = array(); $sel_fields = array();
// Make an array of the fields we want from the source DB // Make an array of the fields we want from the source DB
foreach($this->conf as $k => $v) foreach($this->conf as $k => $v)
{ {
if ($v && (strpos($k,'e107db_xf_') === 0)) if ($v && (strpos($k,'e107db_xf_') === 0))
{ {
$sel_fields[] = substr($k,strlen('e107db_xf_')); $sel_fields[] = substr($k,strlen('e107db_xf_'));
} }
} }
$filterClass = intval(varset($this->conf['e107db_filter_class'], e_UC_PUBLIC)); $filterClass = intval(varset($this->conf['e107db_filter_class'], e_UC_PUBLIC));
if (($filterClass != e_UC_PUBLIC) && (!in_array('user_class',$sel_fields))) if (($filterClass != e_UC_PUBLIC) && (!in_array('user_class',$sel_fields)))
{ {
$sel_fields[] = 'user_class'; $sel_fields[] = 'user_class';
} }
$sel_fields[] = 'user_password'; $sel_fields[] = 'user_password';
$user_field = 'user_loginname'; $user_field = 'user_loginname';
//Get record containing supplied login name //Get record containing supplied login name
$qry = 'SELECT '.implode(',',$sel_fields)." FROM ".$this->conf['e107db_prefix']."user WHERE {$user_field} = '{$uname}' AND `user_ban` = 0"; $qry = 'SELECT '.implode(',',$sel_fields)." FROM ".$this->conf['e107db_prefix']."user WHERE {$user_field} = '{$uname}' AND `user_ban` = 0";
// echo "Query: {$qry}<br />"; // echo "Query: {$qry}<br />";
if(!$r1 = mysql_query($qry)) if(!$r1 = mysql_query($qry))
{ {
mysql_close($res); mysql_close($res);
$this->makeErrorText('Lookup query failed'); $this->makeErrorText('Lookup query failed');
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
if (!$row = mysql_fetch_array($r1)) if (!$row = mysql_fetch_array($r1))
{ {
mysql_close($res); mysql_close($res);
$this->makeErrorText('User not found'); $this->makeErrorText('User not found');
return AUTH_NOUSER; return AUTH_NOUSER;
} }
mysql_close($res); // Finished with 'foreign' DB now mysql_close($res); // Finished with 'foreign' DB now
// Got something from the DB - see whether password valid // Got something from the DB - see whether password valid
require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); // This auto-loads the 'standard' password handler as well require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); // This auto-loads the 'standard' password handler as well
$pass_check = new ExtendedPasswordHandler(); $pass_check = new ExtendedPasswordHandler();
$passMethod = $pass_check->passwordMapping($this->conf['e107db_password_method']); $passMethod = $pass_check->passwordMapping($this->conf['e107db_password_method']);
if ($passMethod === FALSE) if ($passMethod === FALSE)
{ {
$this->makeErrorText('Password error - invalid method'); $this->makeErrorText('Password error - invalid method');
return AUTH_BADPASSWORD; return AUTH_BADPASSWORD;
} }
$pwFromDB = $row['user_password']; // Password stored in DB $pwFromDB = $row['user_password']; // Password stored in DB
if ($pass_check->checkPassword($pword, $uname, $pwFromDB, $passMethod) !== PASSWORD_VALID) if ($pass_check->checkPassword($pword, $uname, $pwFromDB, $passMethod) !== PASSWORD_VALID)
{ {
$this->makeErrorText('Password incorrect'); $this->makeErrorText('Password incorrect');
return AUTH_BADPASSWORD; return AUTH_BADPASSWORD;
} }
// Valid user - check he's in an appropriate class // Valid user - check he's in an appropriate class
if ($filterClass != e_UC_PUBLIC) if ($filterClass != e_UC_PUBLIC)
{ {
$tmp = explode(',', $row['user_class']); $tmp = explode(',', $row['user_class']);
if (!in_array($filterClass, $tmp)) if (!in_array($filterClass, $tmp))
{ {
$this->makeErrorText('Userc not found'); $this->makeErrorText('Userc not found');
return AUTH_NOUSER; // Treat as non-existent user return AUTH_NOUSER; // Treat as non-existent user
} }
unset($tmp); unset($tmp);
} }
// Now copy across any values we have selected // Now copy across any values we have selected
foreach($this->conf as $k => $v) foreach($this->conf as $k => $v)
{ {
if ($v && (strpos($k,'e107db_xf_') === 0)) if ($v && (strpos($k,'e107db_xf_') === 0))
{ {
$f = substr($k,strlen('e107db_xf_')); $f = substr($k,strlen('e107db_xf_'));
if (isset($row[$f])) $newvals[$f] = $row[$f]; if (isset($row[$f])) $newvals[$f] = $row[$f];
} }
} }
$this->makeErrorText(''); // Success - just reconnect to E107 DB if needed $this->makeErrorText(''); // Success - just reconnect to E107 DB if needed
return AUTH_SUCCESS; return AUTH_SUCCESS;
} }
} }
?> ?>

View File

@@ -30,9 +30,64 @@ require_once(e_PLUGIN.'alt_auth/alt_auth_adminmenu.php');
require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); require_once(e_PLUGIN.'alt_auth/extended_password_handler.php');
class alt_auth_e107db extends alt_auth_admin
{
public function __construct()
{
}
public function showForm()
{
$ns = e107::getRender();
$parm = $this->altAuthGetParams('e107db');
$frm = new form;
$text = $frm -> form_open('post', e_SELF);
$text .= "<table class='table adminform'>
<colgroup span='2'>
<col class='col-label' />
<col class='col-control' />
</colgroup>";
$text .= "<tr><td>".LAN_ALT_26."</td><td>";
$text .= E107DB_LAN_1;
$text .= "</td></tr>";
$text .= $this->alt_auth_get_db_fields('e107db', $frm, $parm, 'server|uname|pwd|db|prefix|classfilt');
$text .= "<tr><td>".E107DB_LAN_9."</td><td>";
$text .= $this->altAuthGetPasswordSelector('e107db_password_method', $frm, $parm['e107db_password_method'], FALSE);
$text .= "</td></tr>";
$text .= "<tr><td colspan='2'><br />".E107DB_LAN_11."</td></tr>";
$text .= $this->alt_auth_get_field_list('e107db',$frm, $parm, TRUE);
$text .= "</table><div class='buttons-bar center'>";
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
// $text .= $frm -> form_button("submit", "update", LAN_ALT_UPDATESET);
$text .= '</div>';
$text .= $frm -> form_close();
$ns->tablerender(E107DB_LAN_10, $text);
$ns->tablerender(LAN_ALT_40.LAN_ALT_41,$this->alt_auth_test_form('e107db',$frm));
}
}
$e107dbAdmin = new alt_auth_e107db();
if(vartrue($_POST['update'])) if(vartrue($_POST['update']))
{ {
$message = alt_auth_post_options('e107db'); $message = $e107dbAdmin->alt_auth_post_options('e107db');
} }
@@ -41,51 +96,9 @@ if(vartrue($message))
e107::getRender()->tablerender('',"<div style='text-align:center;'>".$message.'</div>'); e107::getRender()->tablerender('',"<div style='text-align:center;'>".$message.'</div>');
} }
$e107dbAdmin->showForm();
show_e107db_form();
function show_e107db_form()
{
$ns = e107::getRender();
$parm = altAuthGetParams('e107db');
$frm = new form;
$text = $frm -> form_open('post', e_SELF);
$text .= "<table class='table adminform'>
<colgroup span='2'>
<col class='col-label' />
<col class='col-control' />
</colgroup>";
$text .= "<tr><td>".LAN_ALT_26."</td><td>";
$text .= E107DB_LAN_1;
$text .= "</td></tr>";
$text .= alt_auth_get_db_fields('e107db', $frm, $parm, 'server|uname|pwd|db|prefix|classfilt');
$text .= "<tr><td>".E107DB_LAN_9."</td><td>";
$text .= altAuthGetPasswordSelector('e107db_password_method', $frm, $parm['e107db_password_method'], FALSE);
$text .= "</td></tr>";
$text .= "<tr><td colspan='2'><br />".E107DB_LAN_11."</td></tr>";
$text .= alt_auth_get_field_list('e107db',$frm, $parm, TRUE);
$text .= "</table><div class='buttons-bar center'>";
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
// $text .= $frm -> form_button("submit", "update", LAN_ALT_UPDATESET);
$text .= '</div>';
$text .= $frm -> form_close();
$ns->tablerender(E107DB_LAN_10, $text);
$ns->tablerender(LAN_ALT_40.LAN_ALT_41,alt_auth_test_form('e107db',$frm));
}
require_once(e_ADMIN.'footer.php'); require_once(e_ADMIN.'footer.php');

View File

@@ -1,332 +1,332 @@
<?php <?php
/* /*
* e107 website system * e107 website system
* *
* Copyright (C) 2008-2012 e107 Inc (e107.org) * Copyright (C) 2008-2013 e107 Inc (e107.org)
* Released under the terms and conditions of the * Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
* *
* Extended password handler for alt_auth plugin * Extended password handler for alt_auth plugin
* *
* $URL$ * $URL$
* $Id$ * $Id$
*/ */
/** /**
* e107 Alternate authorisation plugin * e107 Alternate authorisation plugin
* *
* @package e107_plugins * @package e107_plugins
* @subpackage alt_auth * @subpackage alt_auth
* @version $Id$; * @version $Id$;
*/ */
/** /**
EXTENDED PASSWORD HANDLER CLASS EXTENDED PASSWORD HANDLER CLASS
- supports many password formats used on other systems - supports many password formats used on other systems
- implements checking of existing passwords only - implements checking of existing passwords only
To use: To use:
Instantiate ExtendedPasswordHandler Instantiate ExtendedPasswordHandler
call CheckPassword(plaintext_password,login_name, stored_value) call CheckPassword(plaintext_password,login_name, stored_value)
or, optionally: or, optionally:
call CheckPassword(plaintext_password,login_name, stored_value, password_type) call CheckPassword(plaintext_password,login_name, stored_value, password_type)
@todo: @todo:
1. Check that public/private declarations of functions are correct 1. Check that public/private declarations of functions are correct
*/ */
if (!defined('e107_INIT')) { exit; } if (!defined('e107_INIT')) { exit; }
require_once(e_HANDLER.'user_handler.php'); require_once(e_HANDLER.'user_handler.php');
// @todo make these class constants // @todo make these class constants
define('PASSWORD_PHPBB_SALT',2); define('PASSWORD_PHPBB_SALT',2);
define('PASSWORD_MAMBO_SALT',3); define('PASSWORD_MAMBO_SALT',3);
define('PASSWORD_JOOMLA_SALT',4); define('PASSWORD_JOOMLA_SALT',4);
define('PASSWORD_GENERAL_MD5',5); define('PASSWORD_GENERAL_MD5',5);
define('PASSWORD_PLAINTEXT',6); define('PASSWORD_PLAINTEXT',6);
define('PASSWORD_GENERAL_SHA1',7); define('PASSWORD_GENERAL_SHA1',7);
define('PASSWORD_WORDPRESS_SALT', 8); define('PASSWORD_WORDPRESS_SALT', 8);
define('PASSWORD_MAGENTO_SALT', 9); define('PASSWORD_MAGENTO_SALT', 9);
// Supported formats: // Supported formats:
define('PASSWORD_PHPBB_ID', '$H$'); // PHPBB salted define('PASSWORD_PHPBB_ID', '$H$'); // PHPBB salted
define('PASSWORD_ORIG_ID', '$P$'); // 'Original' code define('PASSWORD_ORIG_ID', '$P$'); // 'Original' code
define('PASSWORD_WORDPRESS_ID', '$P$'); // WordPress 2.8 define('PASSWORD_WORDPRESS_ID', '$P$'); // WordPress 2.8
class ExtendedPasswordHandler extends UserHandler class ExtendedPasswordHandler extends UserHandler
{ {
private $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; // Holds a string of 64 characters for base64 conversion private $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; // Holds a string of 64 characters for base64 conversion
var $random_state = ''; // A (hopefully) random number var $random_state = ''; // A (hopefully) random number
/** /**
* Constructor - just call parent * Constructor - just call parent
*/ */
function __construct() function __construct()
{ {
// Ancestor constructor // Ancestor constructor
parent::__construct(); parent::__construct();
} }
/** /**
* Return a number of random bytes as specified by $count * Return a number of random bytes as specified by $count
*/ */
private function get_random_bytes($count) private function get_random_bytes($count)
{ {
$this->random_state = md5($this->random_state.microtime().mt_rand(0,10000)); // This will 'auto seed' $this->random_state = md5($this->random_state.microtime().mt_rand(0,10000)); // This will 'auto seed'
$output = ''; $output = '';
for ($i = 0; $i < $count; $i += 16) for ($i = 0; $i < $count; $i += 16)
{ // Only do this loop once unless we need more than 16 bytes { // Only do this loop once unless we need more than 16 bytes
$this->random_state = md5(microtime() . $this->random_state); $this->random_state = md5(microtime() . $this->random_state);
$output .= pack('H*', md5($this->random_state)); // Becomes an array of 16 bytes $output .= pack('H*', md5($this->random_state)); // Becomes an array of 16 bytes
} }
$output = substr($output, 0, $count); $output = substr($output, 0, $count);
return $output; return $output;
} }
/** /**
* Encode to base64 (each block of three 8-bit chars becomes 4 printable chars) * Encode to base64 (each block of three 8-bit chars becomes 4 printable chars)
* Use first $count characters of $input string * Use first $count characters of $input string
*/ */
private function encode64($input, $count) private function encode64($input, $count)
{ {
return base64_encode(substr($input, 0, $count)); // @todo - check this works OK return base64_encode(substr($input, 0, $count)); // @todo - check this works OK
/* /*
$output = ''; $output = '';
$i = 0; $i = 0;
do do
{ {
$value = ord($input[$i++]); $value = ord($input[$i++]);
$output .= $this->itoa64[$value & 0x3f]; $output .= $this->itoa64[$value & 0x3f];
if ($i < $count) $value |= ord($input[$i]) << 8; if ($i < $count) $value |= ord($input[$i]) << 8;
$output .= $this->itoa64[($value >> 6) & 0x3f]; $output .= $this->itoa64[($value >> 6) & 0x3f];
if ($i++ >= $count) break; if ($i++ >= $count) break;
if ($i < $count) $value |= ord($input[$i]) << 16; if ($i < $count) $value |= ord($input[$i]) << 16;
$output .= $this->itoa64[($value >> 12) & 0x3f]; $output .= $this->itoa64[($value >> 12) & 0x3f];
if ($i++ >= $count) break; if ($i++ >= $count) break;
$output .= $this->itoa64[($value >> 18) & 0x3f]; $output .= $this->itoa64[($value >> 18) & 0x3f];
} while ($i < $count); } while ($i < $count);
return $output; return $output;
*/ */
} }
/** /**
* Method for PHPBB3-style salted passwords, which begin '$H$', and WordPress-style salted passwords, which begin '$P$' * Method for PHPBB3-style salted passwords, which begin '$H$', and WordPress-style salted passwords, which begin '$P$'
* Given a plaintext password and the complete password/hash function (which includes any salt), calculate hash * Given a plaintext password and the complete password/hash function (which includes any salt), calculate hash
* Returns FALSE on error * Returns FALSE on error
*/ */
private function crypt_private($password, $stored_password, $password_type = PASSWORD_PHPBB_SALT) private function crypt_private($password, $stored_password, $password_type = PASSWORD_PHPBB_SALT)
{ {
$output = '*0'; $output = '*0';
if (substr($stored_password, 0, 2) == $output) if (substr($stored_password, 0, 2) == $output)
{ {
$output = '*1'; $output = '*1';
} }
$prefix = ''; $prefix = '';
switch ($password_type) switch ($password_type)
{ {
case PASSWORD_PHPBB_SALT : case PASSWORD_PHPBB_SALT :
$prefix = PASSWORD_PHPBB_ID; $prefix = PASSWORD_PHPBB_ID;
break; break;
case PASSWORD_WORDPRESS_SALT : case PASSWORD_WORDPRESS_SALT :
$prefix = PASSWORD_WORDPRESS_ID; $prefix = PASSWORD_WORDPRESS_ID;
break; break;
default : default :
$prefix = ''; $prefix = '';
} }
if ($prefix != substr($stored_password, 0, 3)) if ($prefix != substr($stored_password, 0, 3))
{ {
return $output; return $output;
} }
$count_log2 = strpos($this->itoa64, $stored_password[3]); // 4th character indicates hash depth count $count_log2 = strpos($this->itoa64, $stored_password[3]); // 4th character indicates hash depth count
if ($count_log2 < 7 || $count_log2 > 30) if ($count_log2 < 7 || $count_log2 > 30)
{ {
return $output; return $output;
} }
$count = 1 << $count_log2; $count = 1 << $count_log2;
$salt = substr($stored_password, 4, 8); // Salt is characters 5..12 $salt = substr($stored_password, 4, 8); // Salt is characters 5..12
if (strlen($salt) != 8) if (strlen($salt) != 8)
{ {
return $output; return $output;
} }
# We're kind of forced to use MD5 here since it's the only # We're kind of forced to use MD5 here since it's the only
# cryptographic primitive available in all versions of PHP # cryptographic primitive available in all versions of PHP
# currently in use. To implement our own low-level crypto # currently in use. To implement our own low-level crypto
# in PHP would result in much worse performance and # in PHP would result in much worse performance and
# consequently in lower iteration counts and hashes that are # consequently in lower iteration counts and hashes that are
# quicker to crack (by non-PHP code). # quicker to crack (by non-PHP code).
// Get raw binary output (always 16 bytes) - we assume PHP5 here // Get raw binary output (always 16 bytes) - we assume PHP5 here
$hash = md5($salt.$password, TRUE); $hash = md5($salt.$password, TRUE);
do do
{ {
$hash = md5($hash.$password, TRUE); $hash = md5($hash.$password, TRUE);
} while (--$count); } while (--$count);
$output = substr($setting, 0, 12); // Identifier, shift count and salt - total 12 chars $output = substr($setting, 0, 12); // Identifier, shift count and salt - total 12 chars
$output .= $this->encode64($hash, 16); // Returns 22-character string $output .= $this->encode64($hash, 16); // Returns 22-character string
return $output; return $output;
} }
/** /**
* Return array of supported password types - key is used internally, text is displayed * Return array of supported password types - key is used internally, text is displayed
*/ */
public function getPasswordTypes($includeExtended = TRUE) public function getPasswordTypes($includeExtended = TRUE)
{ {
$vals = array(); $vals = array();
$vals = array('md5' => IMPORTDB_LAN_7,'e107_salt' => IMPORTDB_LAN_8); // Methods supported in core $vals = array('md5' => IMPORTDB_LAN_7,'e107_salt' => IMPORTDB_LAN_8); // Methods supported in core
if ($includeExtended) if ($includeExtended)
{ {
$vals = array_merge($vals,array( $vals = array_merge($vals,array(
'plaintext' => IMPORTDB_LAN_2, 'plaintext' => IMPORTDB_LAN_2,
'joomla_salt' => IMPORTDB_LAN_3, 'joomla_salt' => IMPORTDB_LAN_3,
'mambo_salt' => IMPORTDB_LAN_4, 'mambo_salt' => IMPORTDB_LAN_4,
'smf_sha1' => IMPORTDB_LAN_5, 'smf_sha1' => IMPORTDB_LAN_5,
'sha1' => IMPORTDB_LAN_6, 'sha1' => IMPORTDB_LAN_6,
'phpbb3_salt' => IMPORTDB_LAN_12, 'phpbb3_salt' => IMPORTDB_LAN_12,
'wordpress_salt' => IMPORTDB_LAN_13, 'wordpress_salt' => IMPORTDB_LAN_13,
'magento_salt' => IMPORTDB_LAN_14, 'magento_salt' => IMPORTDB_LAN_14,
)); ));
} }
return $vals; return $vals;
} }
/** /**
* Return password type which relates to a specific foreign system * Return password type which relates to a specific foreign system
*/ */
public function passwordMapping($ptype) public function passwordMapping($ptype)
{ {
$maps = array( $maps = array(
'plaintext' => PASSWORD_PLAINTEXT, 'plaintext' => PASSWORD_PLAINTEXT,
'joomla_salt' => PASSWORD_JOOMLA_SALT, 'joomla_salt' => PASSWORD_JOOMLA_SALT,
'mambo_salt' => PASSWORD_MAMBO_SALT, 'mambo_salt' => PASSWORD_MAMBO_SALT,
'smf_sha1' => PASSWORD_GENERAL_SHA1, 'smf_sha1' => PASSWORD_GENERAL_SHA1,
'sha1' => PASSWORD_GENERAL_SHA1, 'sha1' => PASSWORD_GENERAL_SHA1,
'mambo' => PASSWORD_GENERAL_MD5, 'mambo' => PASSWORD_GENERAL_MD5,
'phpbb2' => PASSWORD_GENERAL_MD5, 'phpbb2' => PASSWORD_GENERAL_MD5,
'e107' => PASSWORD_GENERAL_MD5, 'e107' => PASSWORD_GENERAL_MD5,
'md5' => PASSWORD_GENERAL_MD5, 'md5' => PASSWORD_GENERAL_MD5,
'e107_salt' => PASSWORD_E107_SALT, 'e107_salt' => PASSWORD_E107_SALT,
'phpbb2_salt' => PASSWORD_PHPBB_SALT, 'phpbb2_salt' => PASSWORD_PHPBB_SALT,
'phpbb3_salt' => PASSWORD_PHPBB_SALT, 'phpbb3_salt' => PASSWORD_PHPBB_SALT,
'wordpress_salt' => PASSWORD_WORDPRESS_SALT, 'wordpress_salt' => PASSWORD_WORDPRESS_SALT,
'magento_salt' => PASSWORD_MAGENTO_SALT, 'magento_salt' => PASSWORD_MAGENTO_SALT,
); );
if (isset($maps[$ptype])) return $maps[$ptype]; if (isset($maps[$ptype])) return $maps[$ptype];
return FALSE; return FALSE;
} }
/** /**
* Extension of password validation to handle more types * Extension of password validation to handle more types
* *
* @param string $pword - plaintext password as entered by user * @param string $pword - plaintext password as entered by user
* @param string $login_name - string used to log in (could actually be email address) * @param string $login_name - string used to log in (could actually be email address)
* @param string $stored_hash - required value for password to match * @param string $stored_hash - required value for password to match
* @param integer $password_type - constant specifying the type of password to check against * @param integer $password_type - constant specifying the type of password to check against
* *
* @return PASSWORD_INVALID|PASSWORD_VALID|string * @return PASSWORD_INVALID|PASSWORD_VALID|string
* PASSWORD_INVALID if no match * PASSWORD_INVALID if no match
* PASSWORD_VALID if valid password * PASSWORD_VALID if valid password
* Return a new hash to store if valid password but non-preferred encoding * Return a new hash to store if valid password but non-preferred encoding
*/ */
public function CheckPassword($pword, $login_name, $stored_hash, $password_type = PASSWORD_DEFAULT_TYPE) public function CheckPassword($pword, $login_name, $stored_hash, $password_type = PASSWORD_DEFAULT_TYPE)
{ {
switch ($password_type) switch ($password_type)
{ {
case PASSWORD_GENERAL_MD5 : case PASSWORD_GENERAL_MD5 :
case PASSWORD_E107_MD5 : case PASSWORD_E107_MD5 :
$pwHash = md5($pword); $pwHash = md5($pword);
break; break;
case PASSWORD_GENERAL_SHA1 : case PASSWORD_GENERAL_SHA1 :
if (strlen($stored_hash) != 40) return PASSWORD_INVALID; if (strlen($stored_hash) != 40) return PASSWORD_INVALID;
$pwHash = sha1($pword); $pwHash = sha1($pword);
break; break;
case PASSWORD_JOOMLA_SALT : case PASSWORD_JOOMLA_SALT :
case PASSWORD_MAMBO_SALT : case PASSWORD_MAMBO_SALT :
if ((strpos($stored_hash, ':') === false) || (strlen($stored_hash) < 40)) if ((strpos($stored_hash, ':') === false) || (strlen($stored_hash) < 40))
{ {
return PASSWORD_INVALID; return PASSWORD_INVALID;
} }
// Mambo/Joomla salted hash - should be 32-character md5 hash, ':', 16-character salt (but could be 8-char salt, maybe) // Mambo/Joomla salted hash - should be 32-character md5 hash, ':', 16-character salt (but could be 8-char salt, maybe)
list($hash, $salt) = explode(':', $stored_hash); list($hash, $salt) = explode(':', $stored_hash);
$pwHash = md5($pword.$salt); $pwHash = md5($pword.$salt);
$stored_hash = $hash; $stored_hash = $hash;
break; break;
case PASSWORD_MAGENTO_SALT : case PASSWORD_MAGENTO_SALT :
$hash = $salt = ''; $hash = $salt = '';
if ((strpos($stored_hash, ':') !== false)) if ((strpos($stored_hash, ':') !== false))
{ {
list($hash, $salt) = explode(':', $stored_hash); list($hash, $salt) = explode(':', $stored_hash);
} }
// Magento salted hash - should be 32-character md5 hash, ':', 2-character salt, but could be also only md5 hash // Magento salted hash - should be 32-character md5 hash, ':', 2-character salt, but could be also only md5 hash
else else
{ {
$hash = $stored_hash; $hash = $stored_hash;
} }
if(strlen($hash) !== 32) if(strlen($hash) !== 32)
{ {
//return PASSWORD_INVALID; //return PASSWORD_INVALID;
} }
$pwHash = $salt ? md5($salt.$pword) : md5($pword); $pwHash = $salt ? md5($salt.$pword) : md5($pword);
$stored_hash = $hash; $stored_hash = $hash;
break; break;
case PASSWORD_E107_SALT : case PASSWORD_E107_SALT :
//return e107::getUserSession()->CheckPassword($password, $login_name, $stored_hash); //return e107::getUserSession()->CheckPassword($password, $login_name, $stored_hash);
return parent::CheckPassword($password, $login_name, $stored_hash); return parent::CheckPassword($password, $login_name, $stored_hash);
break; break;
case PASSWORD_PHPBB_SALT : case PASSWORD_PHPBB_SALT :
case PASSWORD_WORDPRESS_SALT : case PASSWORD_WORDPRESS_SALT :
if (strlen($stored_hash) != 34) return PASSWORD_INVALID; if (strlen($stored_hash) != 34) return PASSWORD_INVALID;
$pwHash = $this->crypt_private($pword, $stored_hash, $password_type); $pwHash = $this->crypt_private($pword, $stored_hash, $password_type);
if ($pwHash[0] == '*') if ($pwHash[0] == '*')
{ {
return PASSWORD_INVALID; return PASSWORD_INVALID;
} }
$stored_hash = substr($stored_hash,12); $stored_hash = substr($stored_hash,12);
break; break;
case PASSWORD_PLAINTEXT : case PASSWORD_PLAINTEXT :
$pwHash = $pword; $pwHash = $pword;
break; break;
default : default :
return PASSWORD_INVALID; return PASSWORD_INVALID;
} }
if ($stored_hash != $pwHash) return PASSWORD_INVALID; if ($stored_hash != $pwHash) return PASSWORD_INVALID;
return PASSWORD_VALID; return PASSWORD_VALID;
} }
} }
?> ?>

View File

@@ -1,113 +1,113 @@
<?php <?php
/* /*
* e107 website system * e107 website system
* *
* Copyright (C) 2008-2012 e107 Inc (e107.org) * Copyright (C) 2008-2012 e107 Inc (e107.org)
* Released under the terms and conditions of the * Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
* *
* imported DB authorisation for alt_auth plugin * imported DB authorisation for alt_auth plugin
* *
* $URL$ * $URL$
* $Id$ * $Id$
*/ */
/** /**
* e107 Alternate authorisation plugin * e107 Alternate authorisation plugin
* *
* @package e107_plugins * @package e107_plugins
* @subpackage alt_auth * @subpackage alt_auth
* @version $Id$; * @version $Id$;
*/ */
/* /*
return values return values
AUTH_NOCONNECT = unable to connect to db AUTH_NOCONNECT = unable to connect to db
AUTH_NOUSER = user not found AUTH_NOUSER = user not found
AUTH_BADPASSWORD = supplied password incorrect AUTH_BADPASSWORD = supplied password incorrect
AUTH_SUCCESS = valid login AUTH_SUCCESS = valid login
*/ */
class auth_login class auth_login extends alt_auth_base
{ {
public $Available = FALSE; // Flag indicates whether DB connection available public $Available = FALSE; // Flag indicates whether DB connection available
public $ErrorText; // e107 error string on exit public $ErrorText; // e107 error string on exit
private $conf; // Configuration parameters private $conf; // Configuration parameters
/** /**
* Read configuration * Read configuration
* *
* @return AUTH_xxxx result code * @return AUTH_xxxx result code
*/ */
public function __construct() public function __construct()
{ {
$this->ErrorText = ''; $this->ErrorText = '';
$this->conf = altAuthGetParams('importdb'); $this->conf = $this->altAuthGetParams('importdb');
$this->Available = TRUE; $this->Available = TRUE;
} }
private function makeErrorText($extra = '') private function makeErrorText($extra = '')
{ {
$this->ErrorText = $extra; $this->ErrorText = $extra;
} }
/** /**
* Validate login credentials * Validate login credentials
* *
* @param string $uname - The user name requesting access * @param string $uname - The user name requesting access
* @param string $pass - Password to use (usually plain text) * @param string $pass - Password to use (usually plain text)
* @param pointer &$newvals - pointer to array to accept other data read from database * @param pointer &$newvals - pointer to array to accept other data read from database
* @param boolean $connect_only - TRUE to simply connect to the database * @param boolean $connect_only - TRUE to simply connect to the database
* *
* @return integer result (AUTH_xxxx) * @return integer result (AUTH_xxxx)
* *
* On a successful login, &$newvals array is filled with the requested data from the server * On a successful login, &$newvals array is filled with the requested data from the server
*/ */
public function login($uname, $pword, &$newvals, $connect_only = FALSE) public function login($uname, $pword, &$newvals, $connect_only = FALSE)
{ {
if ($connect_only) return AUTH_SUCCESS; // Big problem if can't connect to our own DB! if ($connect_only) return AUTH_SUCCESS; // Big problem if can't connect to our own DB!
// See if the user's in the E107 database - otherwise they can go away // See if the user's in the E107 database - otherwise they can go away
global $sql, $tp; global $sql, $tp;
if (!$sql->db_Select('user', 'user_loginname, user_password', "user_loginname = '".$tp -> toDB($uname)."'")) if (!$sql->db_Select('user', 'user_loginname, user_password', "user_loginname = '".$tp -> toDB($uname)."'"))
{ // Invalid user { // Invalid user
$this->makeErrorText('User not found'); $this->makeErrorText('User not found');
return AUTH_NOUSER; return AUTH_NOUSER;
} }
// Now look at their password - we always need to verify it, even if its a core E107 format. // Now look at their password - we always need to verify it, even if its a core E107 format.
// Higher levels will always convert an authorised password to E107 format and save it for us. // Higher levels will always convert an authorised password to E107 format and save it for us.
if (!$row = $sql->db_Fetch()) if (!$row = $sql->db_Fetch())
{ {
$this->makeErrorText('Error reading DB'); $this->makeErrorText('Error reading DB');
return AUTH_NOCONNECT; // Debateable return code - really a DB error. But consistent with other handler return AUTH_NOCONNECT; // Debateable return code - really a DB error. But consistent with other handler
} }
require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); // This auto-loads the 'standard' password handler as well require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); // This auto-loads the 'standard' password handler as well
$pass_check = new ExtendedPasswordHandler(); $pass_check = new ExtendedPasswordHandler();
$passMethod = $pass_check->passwordMapping($this->conf['importdb_password_method']); $passMethod = $pass_check->passwordMapping($this->conf['importdb_password_method']);
if ($passMethod === FALSE) if ($passMethod === FALSE)
{ {
$this->makeErrorText('Password error - invalid method'); $this->makeErrorText('Password error - invalid method');
return AUTH_BADPASSWORD; return AUTH_BADPASSWORD;
} }
$pwFromDB = $row['user_password']; // Password stored in DB $pwFromDB = $row['user_password']; // Password stored in DB
if ($pass_check->checkPassword($pword, $uname, $pwFromDB, $passMethod) !== PASSWORD_VALID) if ($pass_check->checkPassword($pword, $uname, $pwFromDB, $passMethod) !== PASSWORD_VALID)
{ {
$this->makeErrorText('Password incorrect'); $this->makeErrorText('Password incorrect');
return LOGIN_CONTINUE; // Could have already changed password to E107 format return LOGIN_CONTINUE; // Could have already changed password to E107 format
} }
$this->makeErrorText(''); $this->makeErrorText('');
return AUTH_SUCCESS; return AUTH_SUCCESS;
} }
} }
?> ?>

View File

@@ -32,10 +32,57 @@ require_once(e_PLUGIN.'alt_auth/alt_auth_adminmenu.php');
require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); require_once(e_PLUGIN.'alt_auth/extended_password_handler.php');
class alt_auth_otherdb extends alt_auth_admin
{
public function __construct()
{
}
public function showForm()
{
$ns = e107::getRender();
$parm = $this->altAuthGetParams('importdb');
$frm = new form;
$text = $frm -> form_open('post', e_SELF);
$text .= "<table class='table adminform'>
<colgroup span='2'>
<col class='col-label' />
<col class='col-control' />
</colgroup>";
$text .= "<tr><td colspan='2'>".IMPORTDB_LAN_11."</td></tr>";
$text .= "<tr><td>".IMPORTDB_LAN_9."</td><td>";
$text .= $this->altAuthGetPasswordSelector('importdb_password_method', $frm, $parm['importdb_password_method'], TRUE);
$text .= "</td></tr>";
$text .= "</table><div class='buttons-bar center'>";
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
$text .= "</div>";
$text .= $frm -> form_close();
$ns -> tablerender(IMPORTDB_LAN_10, $text);
$ns->tablerender(LAN_ALT_40.LAN_ALT_41, $this->alt_auth_test_form('importdb',$frm));
}
}
$otherDbAdmin = new alt_auth_otherdb();
if(vartrue($_POST['update'])) if(vartrue($_POST['update']))
{ {
// $message = update_importdb_prefs(); // $message = update_importdb_prefs();
$message = alt_auth_post_options('importdb'); $message = $otherDbAdmin->alt_auth_post_options('importdb');
} }
if(vartrue($message)) if(vartrue($message))
@@ -44,41 +91,8 @@ if(vartrue($message))
} }
show_importdb_form(); $otherDbAdmin->showForm();
function show_importdb_form()
{
$ns = e107::getRender();
$parm = altAuthGetParams('importdb');
$frm = new form;
$text = $frm -> form_open('post', e_SELF);
$text .= "<table class='table adminform'>
<colgroup span='2'>
<col class='col-label' />
<col class='col-control' />
</colgroup>";
$text .= "<tr><td colspan='2'>".IMPORTDB_LAN_11."</td></tr>";
$text .= "<tr><td>".IMPORTDB_LAN_9."</td><td>";
$text .= altAuthGetPasswordSelector('importdb_password_method', $frm, $parm['importdb_password_method'], TRUE);
$text .= "</td></tr>";
$text .= "</table><div class='buttons-bar center'>";
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
$text .= "</div>";
$text .= $frm -> form_close();
$ns -> tablerender(IMPORTDB_LAN_10, $text);
$ns->tablerender(LAN_ALT_40.LAN_ALT_41,alt_auth_test_form('importdb',$frm));
}
require_once(e_ADMIN.'footer.php'); require_once(e_ADMIN.'footer.php');

View File

@@ -1,311 +1,309 @@
<?php <?php
/* /*
* e107 website system * e107 website system
* *
* Copyright (C) 2008-2012 e107 Inc (e107.org) * Copyright (C) 2008-2012 e107 Inc (e107.org)
* Released under the terms and conditions of the * Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
* *
* LDAP authorisation for alt_auth plugin * LDAP authorisation for alt_auth plugin
* *
* $URL$ * $URL$
* $Id$ * $Id$
*/ */
/** /**
* e107 Alternate authorisation plugin * e107 Alternate authorisation plugin
* *
* @package e107_plugins * @package e107_plugins
* @subpackage alt_auth * @subpackage alt_auth
* @version $Id$; * @version $Id$;
*/ */
class auth_login class auth_login extends alt_auth_base
{ {
private $server; // The LDAP server (array of possible servers) private $server; // The LDAP server (array of possible servers)
private $dn; // LDAP domain private $dn; // LDAP domain
private $ou; // LDAP OU private $ou; // LDAP OU
private $usr; // User name to log on to server private $usr; // User name to log on to server
private $pwd; // Password to log on to server private $pwd; // Password to log on to server
private $serverType; // Server type = LDAP/AD/eDirectory private $serverType; // Server type = LDAP/AD/eDirectory
public $ldapErrorCode; // LDAP error code on exit public $ldapErrorCode; // LDAP error code on exit
public $ldapErrorText; // LDAP error string on exit public $ldapErrorText; // LDAP error string on exit
public $ErrorText; // e107 error string on exit public $ErrorText; // e107 error string on exit
private $connection; // LDAP resource for connection private $connection; // LDAP resource for connection
private $ldapVersion; // Version of LDAP to use private $ldapVersion; // Version of LDAP to use
public $Available = FALSE; // Flag indicates whether DB connection available public $Available = FALSE; // Flag indicates whether DB connection available
private $filter; // Filter for eDirectory search private $filter; // Filter for eDirectory search
private $copyAttribs; // Any attributes which are to be copied on successful login private $copyAttribs; // Any attributes which are to be copied on successful login
private $copyMethods; // Methods which are to be used to copy attributes private $copyMethods; // Methods which are to be used to copy attributes
/** /**
* Read configuration, initialise connection to LDAP database * Read configuration, initialise connection to LDAP database
* *
* @return AUTH_xxxx result code * @return AUTH_xxxx result code
*/ */
public function auth_login() public function auth_login()
{ {
$this->copyAttribs = array(); $this->copyAttribs = array();
$this->copyMethods = array(); $this->copyMethods = array();
$sql = e107::getDB('altAuth'); $ldap = $this->altAuthGetParams('ldap');
$sql->db_Select('alt_auth', '*', "auth_type = 'ldap' ");
while ($row = $sql->db_Fetch()) foreach ($ldap as $row)
{ {
$ldap[$row['auth_parmname']] = base64_decode(base64_decode($row['auth_parmval'])); if ((strpos($row['auth_parmname'], 'ldap_xf_') === 0) && $ldap[$row['auth_parmname']]) // Attribute to copy on successful login
if ((strpos($row['auth_parmname'], 'ldap_xf_') === 0) && $ldap[$row['auth_parmname']]) // Attribute to copy on successful login {
{ $this->copyAttribs[substr($row['auth_parmname'], strlen('ldap_xf_'))] = $ldap[$row['auth_parmname']]; // Key = LDAP attribute. Value = e107 field name
$this->copyAttribs[substr($row['auth_parmname'], strlen('ldap_xf_'))] = $ldap[$row['auth_parmname']]; // Key = LDAP attribute. Value = e107 field name }
} elseif ((strpos($row['auth_parmname'], 'ldap_pm_') === 0) && $ldap[$row['auth_parmname']] && ($ldap[$row['auth_parmname']] != 'none')) // Method to use to copy parameter
elseif ((strpos($row['auth_parmname'], 'ldap_pm_') === 0) && $ldap[$row['auth_parmname']] && ($ldap[$row['auth_parmname']] != 'none')) // Method to use to copy parameter { // Any fields with non-null 'copy' methods
{ // Any fields with non-null 'copy' methods $this->copyMethods[substr($row['auth_parmname'], strlen('ldap_pm_'))] = $ldap[$row['auth_parmname']]; // Key = e107 field name. Value = copy method
$this->copyMethods[substr($row['auth_parmname'], strlen('ldap_pm_'))] = $ldap[$row['auth_parmname']]; // Key = e107 field name. Value = copy method }
} }
unset($row['auth_parmname']); $this->server = explode(',', $ldap['ldap_server']);
} $this->serverType = $ldap['ldap_servertype'];
$this->server = explode(',', $ldap['ldap_server']); $this->dn = $ldap['ldap_basedn'];
$this->serverType = $ldap['ldap_servertype']; $this->ou = $ldap['ldap_ou'];
$this->dn = $ldap['ldap_basedn']; $this->usr = $ldap['ldap_user'];
$this->ou = $ldap['ldap_ou']; $this->pwd = $ldap['ldap_passwd'];
$this->usr = $ldap['ldap_user']; $this->ldapVersion = $ldap['ldap_version'];
$this->pwd = $ldap['ldap_passwd']; $this->filter = (isset($ldap['ldap_edirfilter']) ? $ldap['ldap_edirfilter'] : "");
$this->ldapVersion = $ldap['ldap_version'];
$this->filter = (isset($ldap['ldap_edirfilter']) ? $ldap['ldap_edirfilter'] : ""); if (!function_exists('ldap_connect'))
{
if (!function_exists('ldap_connect')) return AUTH_NORESOURCE;
{ }
return AUTH_NORESOURCE;
} if (!$this->connect())
{
if (!$this->connect()) return AUTH_NOCONNECT;
{ }
return AUTH_NOCONNECT; $this->Available = TRUE;
} return AUTH_SUCCESS;
$this->Available = TRUE; }
return AUTH_SUCCESS;
}
/**
* Retrieve and construct error strings
/** */
* Retrieve and construct error strings private function makeErrorText($extra = '')
*/ {
private function makeErrorText($extra = '') $this->ldapErrorCode = ldap_errno($this->connection);
{ $this->ldapErrorText = ldap_error($this->connection);
$this->ldapErrorCode = ldap_errno($this->connection); $this->ErrorText = $extra . ' ' . $this->ldapErrorCode . ': ' . $this->ldapErrorText;
$this->ldapErrorText = ldap_error($this->connection); }
$this->ErrorText = $extra . ' ' . $this->ldapErrorCode . ': ' . $this->ldapErrorText;
}
/**
* Connect to the LDAP server
/** *
* Connect to the LDAP server * @return boolean TRUE for success, FALSE for failure
* */
* @return boolean TRUE for success, FALSE for failure public function connect()
*/ {
public function connect() foreach ($this->server as $key => $host)
{ {
foreach ($this->server as $key => $host) $this->connection = ldap_connect($host);
{ if ($this->connection)
$this->connection = ldap_connect($host); {
if ($this->connection) if ($this->ldapVersion == 3 || $this->serverType == "ActiveDirectory")
{ {
if ($this->ldapVersion == 3 || $this->serverType == "ActiveDirectory") @ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
{ }
@ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3); return true;
} }
return true; }
}
} $this->ldapErrorCode = -1;
$this->ldapErrorText = "Unable to connect to any server";
$this->ldapErrorCode = -1; $this->ErrorText = $this->ldapErrorCode . ': ' . $this->ldapErrorText;
$this->ldapErrorText = "Unable to connect to any server"; return false;
$this->ErrorText = $this->ldapErrorCode . ': ' . $this->ldapErrorText; }
return false;
}
/**
* Close the connection to the LDAP server
/** */
* Close the connection to the LDAP server public function close()
*/ {
public function close() if (!@ldap_close($this->connection))
{ {
if (!@ldap_close($this->connection)) $this->makeErrorText(); // Read the error code and explanatory string
{ return false;
$this->makeErrorText(); // Read the error code and explanatory string }
return false; else
} {
else return true;
{ }
return true; }
}
}
/**
* Validate login credentials
/** *
* Validate login credentials * @param string $uname - The user name requesting access
* * @param string $pass - Password to use (usually plain text)
* @param string $uname - The user name requesting access * @param pointer &$newvals - pointer to array to accept other data read from database
* @param string $pass - Password to use (usually plain text) * @param boolean $connect_only - TRUE to simply connect to the server
* @param pointer &$newvals - pointer to array to accept other data read from database *
* @param boolean $connect_only - TRUE to simply connect to the server * @return integer result (AUTH_xxxx)
* *
* @return integer result (AUTH_xxxx) * On a successful login, &$newvals array is filled with the requested data from the server
* */
* On a successful login, &$newvals array is filled with the requested data from the server function login($uname, $pass, &$newvals, $connect_only = false)
*/ {
function login($uname, $pass, &$newvals, $connect_only = false) /* Construct the full DN, eg:-
{ ** "uid=username, ou=People, dc=orgname,dc=com"
/* Construct the full DN, eg:- */
** "uid=username, ou=People, dc=orgname,dc=com" // echo "Login to server type: {$this->serverType}<br />";
*/ $current_filter = "";
// echo "Login to server type: {$this->serverType}<br />"; if ($this->serverType == "ActiveDirectory")
$current_filter = ""; {
if ($this->serverType == "ActiveDirectory") $checkDn = $uname . '@' . $this->dn;
{ // added by Father Barry Keal
$checkDn = $uname . '@' . $this->dn; // $current_filter = "(sAMAccountName={$uname})"; for pre windows 2000
// added by Father Barry Keal $current_filter = "(userprincipalname={$uname}@{$this->dn})"; // for 2000 +
// $current_filter = "(sAMAccountName={$uname})"; for pre windows 2000 // end add by Father Barry Keal
$current_filter = "(userprincipalname={$uname}@{$this->dn})"; // for 2000 + }
// end add by Father Barry Keal else
} {
else if ($this->usr != '' && $this->pwd != '')
{ {
if ($this->usr != '' && $this->pwd != '') $this->result = ldap_bind($this->connection, $this->usr, $this->pwd);
{ }
$this->result = ldap_bind($this->connection, $this->usr, $this->pwd); else
} {
else $this->result = ldap_bind($this->connection);
{ }
$this->result = ldap_bind($this->connection); if ($this->result === false)
} {
if ($this->result === false) // echo "LDAP bind failed<br />";
{ $this->makeErrorText(); // Read the error code and explanatory string
// echo "LDAP bind failed<br />"; return AUTH_NOCONNECT;
$this->makeErrorText(); // Read the error code and explanatory string }
return AUTH_NOCONNECT; // In ldap_auth.php, should look like this instead for eDirectory
} // $query = ldap_search($this -> connection, $this -> dn, "cn=".$uname);
// In ldap_auth.php, should look like this instead for eDirectory if ($this->serverType == "eDirectory")
// $query = ldap_search($this -> connection, $this -> dn, "cn=".$uname); {
if ($this->serverType == "eDirectory") $current_filter = "(&(cn={$uname})" . $this->filter . ")";
{ }
$current_filter = "(&(cn={$uname})" . $this->filter . ")"; else
} {
else $current_filter = "uid=" . $uname;
{ }
$current_filter = "uid=" . $uname; // echo "LDAP search: {$this->dn}, {$current_filter}<br />";
} $query = ldap_search($this->connection, $this->dn, $current_filter);
// echo "LDAP search: {$this->dn}, {$current_filter}<br />";
$query = ldap_search($this->connection, $this->dn, $current_filter); if ($query === false)
{
if ($query === false) // Could not perform query to LDAP directory
{ echo "LDAP - search for user failed<br />";
// Could not perform query to LDAP directory $this->makeErrorText(); // Read the error code and explanatory string
echo "LDAP - search for user failed<br />"; return AUTH_NOCONNECT;
$this->makeErrorText(); // Read the error code and explanatory string }
return AUTH_NOCONNECT; else
} {
else $query_result = ldap_get_entries($this->connection, $query);
{
$query_result = ldap_get_entries($this->connection, $query); if ($query_result["count"] != 1)
{
if ($query_result["count"] != 1) if ($connect_only) return AUTH_SUCCESS;
{ else return AUTH_NOUSER;
if ($connect_only) return AUTH_SUCCESS; }
else return AUTH_NOUSER; else
} {
else $checkDn = $query_result[0]["dn"];
{ $this->close();
$checkDn = $query_result[0]["dn"]; $this->connect();
$this->close(); }
$this->connect(); }
} }
} // Try and connect...
} $this->result = ldap_bind($this->connection, $checkDn, $pass);
// Try and connect... if ($this->result)
$this->result = ldap_bind($this->connection, $checkDn, $pass); {
if ($this->result) // Connected OK - login credentials are fine!
{ // But bind can return success even if no password! Does reject an invalid password, however
// Connected OK - login credentials are fine! if ($connect_only) return AUTH_SUCCESS;
// But bind can return success even if no password! Does reject an invalid password, however if (trim($pass) == '') return AUTH_BADPASSWORD; // Pick up a blank password
if ($connect_only) return AUTH_SUCCESS; if (count($this->copyAttribs) == 0) return AUTH_SUCCESS; // No attributes required - we're done
if (trim($pass) == '') return AUTH_BADPASSWORD; // Pick up a blank password $ldap_attributes = array_values(array_unique($this->copyAttribs));
if (count($this->copyAttribs) == 0) return AUTH_SUCCESS; // No attributes required - we're done if ($this->serverType == "ActiveDirectory")
$ldap_attributes = array_values(array_unique($this->copyAttribs)); { // If we are using AD then build up the full string from the fqdn
if ($this->serverType == "ActiveDirectory") $altauth_tmp = explode('.', $this->dn);
{ // If we are using AD then build up the full string from the fqdn $checkDn='';
$altauth_tmp = explode('.', $this->dn); foreach($altauth_tmp as $$altauth_dc)
$checkDn=''; {
foreach($altauth_tmp as $$altauth_dc) $checkDn .= ",DC={$altauth_dc}";
{ }
$checkDn .= ",DC={$altauth_dc}"; // prefix with the OU
} $checkDn = $this->ou . $checkDn;
// prefix with the OU }
$checkDn = $this->ou . $checkDn; $this->result = ldap_search($this->connection, $checkDn, $current_filter, $ldap_attributes);
} if ($this->result)
$this->result = ldap_search($this->connection, $checkDn, $current_filter, $ldap_attributes); {
if ($this->result) $entries = ldap_get_entries($this->connection, $this->result);
{ if (count($entries) == 2) // All OK
$entries = ldap_get_entries($this->connection, $this->result); {
if (count($entries) == 2) // All OK for ($j = 0; $j < $entries[0]['count']; $j++)
{ {
for ($j = 0; $j < $entries[0]['count']; $j++) $k = $entries[0][$j]; // LDAP attribute name
{ $tlv = $entries[0][$k]; // Array of LDAP data
$k = $entries[0][$j]; // LDAP attribute name if (is_array($tlv) && count($tempKeys = array_keys($this->copyAttribs,$k))) // This bit executed if we've successfully got some data. Key is the attribute name, then array of data
$tlv = $entries[0][$k]; // Array of LDAP data {
if (is_array($tlv) && count($tempKeys = array_keys($this->copyAttribs,$k))) // This bit executed if we've successfully got some data. Key is the attribute name, then array of data foreach ($tempKeys as $tk) // Single LDAP attribute may be mapped to several fields
{ {
foreach ($tempKeys as $tk) // Single LDAP attribute may be mapped to several fields // $newvals[$tk] = $this->translate($tlv[0]); // Just grab the first value
{ $newvals[$tk] = $tlv[0]; // Just grab the first value
// $newvals[$tk] = $this->translate($tlv[0]); // Just grab the first value }
$newvals[$tk] = $tlv[0]; // Just grab the first value }
} else
} {
else // echo " Unexpected non-array value - Key: {$k} Value: {$tlv}<br />";
{ $this->makeErrorText(); // Read the error code and explanatory string
// echo " Unexpected non-array value - Key: {$k} Value: {$tlv}<br />"; return AUTH_NOCONNECT; // Not really a suitable return code for this - its an error
$this->makeErrorText(); // Read the error code and explanatory string }
return AUTH_NOCONNECT; // Not really a suitable return code for this - its an error }
} }
} else
} {
else // echo "Got wrong number of entries<br />";
{ $this->makeErrorText(); // Read the error code and explanatory string
// echo "Got wrong number of entries<br />"; return AUTH_NOUSER; // Bit debateable what to return if this happens
$this->makeErrorText(); // Read the error code and explanatory string }
return AUTH_NOUSER; // Bit debateable what to return if this happens }
} else // Probably a bit strange if we don't get any info back - but possible
} {
else // Probably a bit strange if we don't get any info back - but possible // echo "No results!<br />";
{ }
// echo "No results!<br />";
} return AUTH_SUCCESS;
}
return AUTH_SUCCESS; else
} {
else /* Login failed. Return error code.
{ ** The common error codes and reasons are listed below :
/* Login failed. Return error code. ** (for iPlanet, other servers may differ)
** The common error codes and reasons are listed below : ** 19 - Account locked out (too many invalid login attempts)
** (for iPlanet, other servers may differ) ** 32 - User does not exist
** 19 - Account locked out (too many invalid login attempts) ** 49 - Wrong password
** 32 - User does not exist ** 53 - Account inactive (manually locked out by administrator)
** 49 - Wrong password */
** 53 - Account inactive (manually locked out by administrator) $this->makeErrorText(); // Read the error code and explanatory string
*/
$this->makeErrorText(); // Read the error code and explanatory string switch ($this->ldapErrorCode)
{
switch ($this->ldapErrorCode) case 32 :
{ return AUTH_NOUSER;
case 32 : case 49 :
return AUTH_NOUSER; return AUTH_BADPASSWORD;
case 49 : }
return AUTH_BADPASSWORD; // return error code as if it never connected, maybe change that in the future
} return AUTH_NOCONNECT;
// return error code as if it never connected, maybe change that in the future }
return AUTH_NOCONNECT; }
} }
}
} ?>
?>

View File

@@ -31,17 +31,104 @@ require_once(e_PLUGIN.'alt_auth/alt_auth_adminmenu.php');
$mes = e107::getMessage(); $mes = e107::getMessage();
$server_types[1] = 'LDAP';
$server_types[2] = 'ActiveDirectory';
$server_types[3] = 'eDirectory';
$ldap_ver[1]='2'; class alt_auth_ldap extends alt_auth_admin
$ldap_ver[2]='3'; {
public function __construct()
{
}
public function showForm($mes)
{
$server_types[1] = 'LDAP';
$server_types[2] = 'ActiveDirectory';
$server_types[3] = 'eDirectory';
$ldap_ver[1]='2';
$ldap_ver[2]='3';
$ldap = $this->altAuthGetParams('ldap');
if (!isset($ldap['ldap_edirfilter'])) $ldap['ldap_edirfilter'] == '';
//print_a($ldap);
$current_filter = "(&(cn=[USERNAME]){$ldap['ldap_edirfilter']})";
$frm = new form;
$text = $frm -> form_open('post',e_SELF);
$text .= "<table class='table adminform'>";
$text .= "<tr><td>".LDAPLAN_12."</td><td>";
$text .= $frm -> form_select_open("ldap_servertype");
foreach($server_types as $v)
{
$sel = (vartrue($ldap['ldap_servertype']) == $v) ? " Selected='selected'" : '';
$text .= $frm -> form_option($v, $sel, $v);
}
$text .= $frm -> form_select_close();
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_1."</td><td>";
$text .= $frm -> form_text("ldap_server", 35, vartrue($ldap['ldap_server']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_2."</td><td>";
$text .= $frm -> form_text("ldap_basedn", 35, vartrue($ldap['ldap_basedn']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_14."</td><td>";
$text .= $frm -> form_text("ldap_ou", 35, vartrue($ldap['ldap_ou']), 60);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_3."</td><td>";
$text .= $frm -> form_text("ldap_user", 35, vartrue($ldap['ldap_user']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_4."</td><td>";
$text .= $frm -> form_text("ldap_passwd", 35, vartrue($ldap['ldap_passwd']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_5."</td><td>";
$text .= $frm -> form_select_open("ldap_version");
foreach($ldap_ver as $v)
{
$sel = ($ldap['ldap_version'] == $v) ? " Selected='selected'" : "";
$text .= $frm -> form_option($v, $sel, $v);
}
$text .= $frm -> form_select_close();
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_7."<br /><span class='smalltext'>".LDAPLAN_8."</span></td><td>";
$text .= $frm -> form_text('ldap_edirfilter', 35, $ldap['ldap_edirfilter'], 120);
$text .= "<br /><span class='smalltext'>".LDAPLAN_9."<br />".htmlentities($current_filter)."</span></td></tr>";
$text .= "<tr><td class='forumheader2' colspan='2'>".LAN_ALT_27."</td></tr>";
$this->add_extended_fields();
$text .= $this->alt_auth_get_field_list('ldap',$frm, $ldap, FALSE);
$text .= "<tr><td class='forumheader' colspan='2' style='text-align:center;'>";
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
//$text .= $frm -> form_button('submit', 'update', LDAPLAN_13);
$text .= "</td></tr>";
$text .= "</table>\n";
$text .= $frm -> form_close();
e107::getRender()->tablerender(LDAPLAN_6, $mes->render(). $text);
e107::getRender()->tablerender(LAN_ALT_40.LAN_ALT_41, $this->alt_auth_test_form('ldap',$frm));
}
}
$ldapAdmin = new alt_auth_ldap();
$message = ''; $message = '';
if(vartrue($_POST['update'])) if(vartrue($_POST['update']))
{ {
$message .= alt_auth_post_options('ldap'); $message .= $ldapAdmin->alt_auth_post_options('ldap');
} }
@@ -57,76 +144,8 @@ if($message)
e107::getRender()->tablerender('',"<div style='text-align:center;'>".$message.'</div>'); e107::getRender()->tablerender('',"<div style='text-align:center;'>".$message.'</div>');
} }
$ldapAdmin->showForm($mes);
$ldap = altAuthGetParams('ldap');
if (!isset($ldap['ldap_edirfilter'])) $ldap['ldap_edirfilter'] == '';
//print_a($ldap);
$current_filter = "(&(cn=[USERNAME]){$ldap['ldap_edirfilter']})";
$frm = new form;
$text = $frm -> form_open('post',e_SELF);
$text .= "<table class='table adminform'>";
$text .= "<tr><td>".LDAPLAN_12."</td><td>";
$text .= $frm -> form_select_open("ldap_servertype");
foreach($server_types as $v)
{
$sel = (vartrue($ldap['ldap_servertype']) == $v) ? " Selected='selected'" : '';
$text .= $frm -> form_option($v, $sel, $v);
}
$text .= $frm -> form_select_close();
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_1."</td><td>";
$text .= $frm -> form_text("ldap_server", 35, vartrue($ldap['ldap_server']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_2."</td><td>";
$text .= $frm -> form_text("ldap_basedn", 35, vartrue($ldap['ldap_basedn']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_14."</td><td>";
$text .= $frm -> form_text("ldap_ou", 35, vartrue($ldap['ldap_ou']), 60);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_3."</td><td>";
$text .= $frm -> form_text("ldap_user", 35, vartrue($ldap['ldap_user']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_4."</td><td>";
$text .= $frm -> form_text("ldap_passwd", 35, vartrue($ldap['ldap_passwd']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_5."</td><td>";
$text .= $frm -> form_select_open("ldap_version");
foreach($ldap_ver as $v)
{
$sel = ($ldap['ldap_version'] == $v) ? " Selected='selected'" : "";
$text .= $frm -> form_option($v, $sel, $v);
}
$text .= $frm -> form_select_close();
$text .= "</td></tr>";
$text .= "<tr><td>".LDAPLAN_7."<br /><span class='smalltext'>".LDAPLAN_8."</span></td><td>";
$text .= $frm -> form_text('ldap_edirfilter', 35, $ldap['ldap_edirfilter'], 120);
$text .= "<br /><span class='smalltext'>".LDAPLAN_9."<br />".htmlentities($current_filter)."</span></td></tr>";
$text .= "<tr><td class='forumheader2' colspan='2'>".LAN_ALT_27."</td></tr>";
add_extended_fields();
$text .= alt_auth_get_field_list('ldap',$frm, $ldap, FALSE);
$text .= "<tr><td class='forumheader' colspan='2' style='text-align:center;'>";
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
//$text .= $frm -> form_button('submit', 'update', LDAPLAN_13);
$text .= "</td></tr>";
$text .= "</table>\n";
$text .= $frm -> form_close();
e107::getRender()->tablerender(LDAPLAN_6, $mes->render(). $text);
e107::getRender()->tablerender(LAN_ALT_40.LAN_ALT_41,alt_auth_test_form('ldap',$frm));
require_once(e_ADMIN.'footer.php'); require_once(e_ADMIN.'footer.php');

View File

@@ -1,166 +1,166 @@
<?php <?php
/* /*
* e107 website system * e107 website system
* *
* Copyright (C) 2008-2012 e107 Inc (e107.org) * Copyright (C) 2008-2012 e107 Inc (e107.org)
* Released under the terms and conditions of the * Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
* *
* Alt_auth plugin - 'otherdb' authorisation handler * Alt_auth plugin - 'otherdb' authorisation handler
* *
* $URL$ * $URL$
* $Id$ * $Id$
* *
*/ */
/** /**
* e107 Alternate authorisation plugin * e107 Alternate authorisation plugin
* *
* @package e107_plugins * @package e107_plugins
* @subpackage alt_auth * @subpackage alt_auth
* @version $Id$; * @version $Id$;
*/ */
/* /*
return values return values
AUTH_NOCONNECT = unable to connect to db AUTH_NOCONNECT = unable to connect to db
AUTH_NOUSER = user not found AUTH_NOUSER = user not found
AUTH_BADPASSWORD = supplied password incorrect AUTH_BADPASSWORD = supplied password incorrect
AUTH_SUCCESS = valid login AUTH_SUCCESS = valid login
*/ */
class auth_login class auth_login extends alt_auth_base
{ {
public $Available = FALSE; // Flag indicates whether DB connection available public $Available = FALSE; // Flag indicates whether DB connection available
public $ErrorText; // e107 error string on exit public $ErrorText; // e107 error string on exit
private $conf; // Configuration parameters private $conf; // Configuration parameters
/** /**
* Read configuration * Read configuration
* *
* @return AUTH_xxxx result code * @return AUTH_xxxx result code
*/ */
public function __construct() public function __construct()
{ {
$this->ErrorText = ''; $this->ErrorText = '';
$this->conf = altAuthGetParams('otherdb'); $this->conf = $this->altAuthGetParams('otherdb');
$this->Available = TRUE; $this->Available = TRUE;
} }
/** /**
* Retrieve and construct error strings * Retrieve and construct error strings
* *
* @todo - test whether reconnect to DB is required (shouldn't be) * @todo - test whether reconnect to DB is required (shouldn't be)
*/ */
private function makeErrorText($extra = '') private function makeErrorText($extra = '')
{ {
$this->ErrorText = $extra; $this->ErrorText = $extra;
//global $mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb, $sql; //global $mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb, $sql;
//$sql->db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb); //$sql->db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb);
} }
/** /**
* Validate login credentials * Validate login credentials
* *
* @param string $uname - The user name requesting access * @param string $uname - The user name requesting access
* @param string $pass - Password to use (usually plain text) * @param string $pass - Password to use (usually plain text)
* @param pointer &$newvals - pointer to array to accept other data read from database * @param pointer &$newvals - pointer to array to accept other data read from database
* @param boolean $connect_only - TRUE to simply connect to the database * @param boolean $connect_only - TRUE to simply connect to the database
* *
* @return integer result (AUTH_xxxx) * @return integer result (AUTH_xxxx)
* *
* On a successful login, &$newvals array is filled with the requested data from the server * On a successful login, &$newvals array is filled with the requested data from the server
*/ */
public function login($uname, $pword, &$newvals, $connect_only = FALSE) public function login($uname, $pword, &$newvals, $connect_only = FALSE)
{ {
//Attempt to open connection to sql database //Attempt to open connection to sql database
if(!$res = mysql_connect($this->conf['otherdb_server'], $this->conf['otherdb_username'], $this->conf['otherdb_password'])) if(!$res = mysql_connect($this->conf['otherdb_server'], $this->conf['otherdb_username'], $this->conf['otherdb_password']))
{ {
$this->makeErrorText('Cannot connect to remote server'); $this->makeErrorText('Cannot connect to remote server');
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
//Select correct db //Select correct db
if(!mysql_select_db($this->conf['otherdb_database'], $res)) if(!mysql_select_db($this->conf['otherdb_database'], $res))
{ {
mysql_close($res); mysql_close($res);
$this->makeErrorText('Cannot connect to remote DB'); $this->makeErrorText('Cannot connect to remote DB');
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
if ($connect_only) return AUTH_SUCCESS; // Test mode may just want to connect to the DB if ($connect_only) return AUTH_SUCCESS; // Test mode may just want to connect to the DB
$sel_fields = array(); $sel_fields = array();
// Make an array of the fields we want from the source DB // Make an array of the fields we want from the source DB
foreach($this->conf as $k => $v) foreach($this->conf as $k => $v)
{ {
if ($v && (strpos($k,'otherdb_xf_') === 0)) if ($v && (strpos($k,'otherdb_xf_') === 0))
{ {
$sel_fields[] = $v; $sel_fields[] = $v;
} }
} }
$sel_fields[] = $this->conf['otherdb_password_field']; $sel_fields[] = $this->conf['otherdb_password_field'];
$user_field = $this->conf['otherdb_user_field']; $user_field = $this->conf['otherdb_user_field'];
if (isset($this->conf['otherdb_salt_field'])) if (isset($this->conf['otherdb_salt_field']))
{ {
$sel_fields[] = $this->conf['otherdb_salt_field']; $sel_fields[] = $this->conf['otherdb_salt_field'];
} }
//Get record containing supplied login name //Get record containing supplied login name
$qry = "SELECT ".implode(',',$sel_fields)." FROM {$this->conf['otherdb_table']} WHERE {$user_field} = '{$uname}'"; $qry = "SELECT ".implode(',',$sel_fields)." FROM {$this->conf['otherdb_table']} WHERE {$user_field} = '{$uname}'";
// echo "Query: {$qry}<br />"; // echo "Query: {$qry}<br />";
if(!$r1 = mysql_query($qry)) if(!$r1 = mysql_query($qry))
{ {
mysql_close($res); mysql_close($res);
$this->makeErrorText('Lookup query failed'); $this->makeErrorText('Lookup query failed');
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
if(!$row = mysql_fetch_array($r1)) if(!$row = mysql_fetch_array($r1))
{ {
mysql_close($res); mysql_close($res);
$this->makeErrorText('User not found'); $this->makeErrorText('User not found');
return AUTH_NOUSER; return AUTH_NOUSER;
} }
mysql_close($res); // Finished with 'foreign' DB now mysql_close($res); // Finished with 'foreign' DB now
// Got something from the DB - see whether password valid // Got something from the DB - see whether password valid
require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); // This auto-loads the 'standard' password handler as well require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); // This auto-loads the 'standard' password handler as well
$pass_check = new ExtendedPasswordHandler(); $pass_check = new ExtendedPasswordHandler();
$passMethod = $pass_check->passwordMapping($this->conf['otherdb_password_method']); $passMethod = $pass_check->passwordMapping($this->conf['otherdb_password_method']);
if ($passMethod === FALSE) if ($passMethod === FALSE)
{ {
$this->makeErrorText('Password error - invalid method'); $this->makeErrorText('Password error - invalid method');
return AUTH_BADPASSWORD; return AUTH_BADPASSWORD;
} }
$pwFromDB = $row[$this->conf['otherdb_password_field']]; // Password stored in DB $pwFromDB = $row[$this->conf['otherdb_password_field']]; // Password stored in DB
if ($salt_field) $pwFromDB .= ':'.$row[$salt_field]; if ($salt_field) $pwFromDB .= ':'.$row[$salt_field];
if ($pass_check->checkPassword($pword, $uname, $pwFromDB, $passMethod) !== PASSWORD_VALID) if ($pass_check->checkPassword($pword, $uname, $pwFromDB, $passMethod) !== PASSWORD_VALID)
{ {
$this->makeErrorText('Password incorrect'); $this->makeErrorText('Password incorrect');
return AUTH_BADPASSWORD; return AUTH_BADPASSWORD;
} }
// Now copy across any values we have selected // Now copy across any values we have selected
foreach($this->conf as $k => $v) foreach($this->conf as $k => $v)
{ {
if ($v && (strpos($k,'otherdb_xf_') === 0) && isset($row[$v])) if ($v && (strpos($k,'otherdb_xf_') === 0) && isset($row[$v]))
{ {
$newvals[substr($k,strlen('otherdb_xf_'))] = $row[$v]; $newvals[substr($k,strlen('otherdb_xf_'))] = $row[$v];
} }
} }
$this->makeErrorText(''); // Success - just reconnect to E107 DB if needed $this->makeErrorText(''); // Success - just reconnect to E107 DB if needed
return AUTH_SUCCESS; return AUTH_SUCCESS;
} }
} }
?> ?>

View File

@@ -31,9 +31,62 @@ require_once(e_PLUGIN.'alt_auth/alt_auth_adminmenu.php');
require_once(e_PLUGIN.'alt_auth/extended_password_handler.php'); require_once(e_PLUGIN.'alt_auth/extended_password_handler.php');
class alt_auth_otherdb extends alt_auth_admin
{
public function __construct()
{
}
public function showForm()
{
$ns = e107::getRender();
$parm = $this->altAuthGetParams('otherdb');
$frm = new form;
$text = $frm -> form_open("post", e_SELF);
$text .= "<table class='table adminform'>";
$text .= "<tr><td>".LAN_ALT_26."</td><td>";
$text .= OTHERDB_LAN_15;
$text .= "</td></tr>";
$text .= $this->alt_auth_get_db_fields('otherdb', $frm, $parm, 'server|uname|pwd|db|table|ufield|pwfield|salt');
$text .= "<tr><td>".OTHERDB_LAN_9."</td><td>";
$text .= $this->altAuthGetPasswordSelector('otherdb_password_method', $frm, $parm['otherdb_password_method'], TRUE);
$text .= "</td></tr>";
$text .= "<tr><td class='forumheader2' colspan='2'>".LAN_ALT_27."</td></tr>";
$text .= $this->alt_auth_get_field_list('otherdb',$frm, $parm, FALSE);
$text .= "<tr><td class='forumheader' colspan='2' style='text-align:center;'>";
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
$text .= '</td></tr>';
$text .= '</table>';
$text .= $frm -> form_close();
$ns -> tablerender(OTHERDB_LAN_10, $text);
$ns->tablerender(LAN_ALT_40.LAN_ALT_41, $this->alt_auth_test_form('otherdb',$frm));
}
}
$otherdbAdmin = new alt_auth_otherdb();
if(vartrue($_POST['update'])) if(vartrue($_POST['update']))
{ {
$message = alt_auth_post_options('otherdb'); $message = $otherdbAdmin->alt_auth_post_options('otherdb');
} }
@@ -43,45 +96,8 @@ if(vartrue($message))
} }
$otherdbAdmin->showForm($mes);
show_otherdb_form();
function show_otherdb_form()
{
$ns = e107::getRender();
$parm = altAuthGetParams('otherdb');
$frm = new form;
$text = $frm -> form_open("post", e_SELF);
$text .= "<table class='table adminform'>";
$text .= "<tr><td>".LAN_ALT_26."</td><td>";
$text .= OTHERDB_LAN_15;
$text .= "</td></tr>";
$text .= alt_auth_get_db_fields('otherdb', $frm, $parm, 'server|uname|pwd|db|table|ufield|pwfield|salt');
$text .= "<tr><td>".OTHERDB_LAN_9."</td><td>";
$text .= altAuthGetPasswordSelector('otherdb_password_method', $frm, $parm['otherdb_password_method'], TRUE);
$text .= "</td></tr>";
$text .= "<tr><td class='forumheader2' colspan='2'>".LAN_ALT_27."</td></tr>";
$text .= alt_auth_get_field_list('otherdb',$frm, $parm, FALSE);
$text .= "<tr><td class='forumheader' colspan='2' style='text-align:center;'>";
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
$text .= '</td></tr>';
$text .= '</table>';
$text .= $frm -> form_close();
$ns -> tablerender(OTHERDB_LAN_10, $text);
$ns->tablerender(LAN_ALT_40.LAN_ALT_41,alt_auth_test_form('otherdb',$frm));
}
require_once(e_ADMIN.'footer.php'); require_once(e_ADMIN.'footer.php');

View File

@@ -1,250 +1,250 @@
<?php <?php
/* /*
+ ----------------------------------------------------------------------------+ + ----------------------------------------------------------------------------+
| e107 website system | e107 website system
| |
| Copyright (C) 2008-2009 e107 Inc (e107.org) | Copyright (C) 2008-2009 e107 Inc (e107.org)
| http://e107.org | http://e107.org
| |
| |
| Released under the terms and conditions of the | Released under the terms and conditions of the
| GNU General Public License (http://gnu.org). | GNU General Public License (http://gnu.org).
| |
| $Source: /cvs_backup/e107_0.8/e107_plugins/alt_auth/radius_auth.php,v $ | $Source: /cvs_backup/e107_0.8/e107_plugins/alt_auth/radius_auth.php,v $
| $Revision$ | $Revision$
| $Date$ | $Date$
| $Author$ | $Author$
+----------------------------------------------------------------------------+ +----------------------------------------------------------------------------+
RFC2865 is the main RADIUS standard - http://www.faqs.org/rfcs/rfc2865 RFC2865 is the main RADIUS standard - http://www.faqs.org/rfcs/rfc2865
Potential enhancements: Potential enhancements:
- Multiple servers (done, but not tested) - Multiple servers (done, but not tested)
- Configurable port (probably not necessary) - Configurable port (probably not necessary)
- Configurable timeout - Configurable timeout
- Configurable retries - Configurable retries
Error recfrom: 10054 - winsock error for 'connection reset' Error recfrom: 10054 - winsock error for 'connection reset'
*/ */
define('RADIUS_DEBUG',TRUE); define('RADIUS_DEBUG',FALSE);
class auth_login
{ class auth_login extends alt_auth_base
{
private $server; private $server;
private $secret; private $secret;
private $port; private $port;
private $usr; private $usr;
private $pwd; private $pwd;
private $connection; // Handle to use on successful creation private $connection; // Handle to use on successful creation
public $Available = FALSE; // Flag indicates whether DB connection available public $Available = FALSE; // Flag indicates whether DB connection available
public $ErrorText; // e107 error string on exit public $ErrorText; // e107 error string on exit
/** /**
* Read configuration, initialise connection to LDAP database * Read configuration, initialise connection to LDAP database
* *
* @return AUTH_xxxx result code * @return AUTH_xxxx result code
*/ */
function __construct() function __construct()
{ {
$this->copyAttribs = array(); $this->copyAttribs = array();
$radius = altAuthGetParams('radius'); $radius = $this->altAuthGetParams('radius');
$this->server = explode(',',$radius['radius_server']); $this->server = explode(',',$radius['radius_server']);
$this->port = 1812; // Assume fixed port number for now - 1812 (UDP) is listed for servers, 1645 for authentification. (1646, 1813 for accounting) $this->port = 1812; // Assume fixed port number for now - 1812 (UDP) is listed for servers, 1645 for authentification. (1646, 1813 for accounting)
// (A Microsoft app note says 1812 is the RFC2026-compliant port number. (http://support.microsoft.com/kb/230786) // (A Microsoft app note says 1812 is the RFC2026-compliant port number. (http://support.microsoft.com/kb/230786)
// $this->port = 1645; // $this->port = 1645;
$this->secret = explode(',',$radius['radius_secret']); $this->secret = explode(',',$radius['radius_secret']);
if ((count($this->server) > 1) && (count($this->secret) == 1)) if ((count($this->server) > 1) && (count($this->secret) == 1))
{ {
$this->secret = array(); $this->secret = array();
foreach ($this->server as $k => $v) foreach ($this->server as $k => $v)
{ {
$this->secret[$k] = $radius['radius_secret']; // Same secret for all servers, if only one entered $this->secret[$k] = $radius['radius_secret']; // Same secret for all servers, if only one entered
} }
} }
$this->ErrorText = ''; $this->ErrorText = '';
if(!function_exists('radius_auth_open')) if(!function_exists('radius_auth_open'))
{ {
return AUTH_NORESOURCE; return AUTH_NORESOURCE;
} }
if(!$this -> connect()) if(!$this -> connect())
{ {
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
$this->Available = TRUE; $this->Available = TRUE;
return AUTH_SUCCESS; return AUTH_SUCCESS;
} }
/** /**
* Retrieve and construct error strings * Retrieve and construct error strings
*/ */
function makeErrorText($extra = '') function makeErrorText($extra = '')
{ {
$this->ErrorText = $extra.radius_strerror($this->connection) ; $this->ErrorText = $extra.radius_strerror($this->connection) ;
if (!RADIUS_DEBUG) return; if (!RADIUS_DEBUG) return;
$text = "<br />Server: {$this->server} Stored secret: ".radius_server_secret($this->connection)." Port: {$this->port}"; $text = "<br />Server: {$this->server} Stored secret: ".radius_server_secret($this->connection)." Port: {$this->port}";
$this->ErrorText .= $text; $this->ErrorText .= $text;
} }
/** /**
* Try to connect to a radius server * Try to connect to a radius server
* *
* @return boolean TRUE for success, FALSE for failure * @return boolean TRUE for success, FALSE for failure
*/ */
function connect() function connect()
{ {
if (!($this->connection = radius_auth_open())) if (!($this->connection = radius_auth_open()))
{ {
$this->makeErrorText('RADIUS open failed: ') ; $this->makeErrorText('RADIUS open failed: ') ;
return FALSE; return FALSE;
} }
foreach ($this->server as $k => $s) foreach ($this->server as $k => $s)
{ {
if (!radius_add_server($this->connection, $s, $this->port, $this->secret[$k], 15, 1)) // fixed 15 second timeout, one try ATM if (!radius_add_server($this->connection, $s, $this->port, $this->secret[$k], 15, 1)) // fixed 15 second timeout, one try ATM
{ {
$this->makeErrorText('RADIUS add server failed: ') ; $this->makeErrorText('RADIUS add server failed: ') ;
return FALSE; return FALSE;
} }
} }
return TRUE; return TRUE;
} }
/** /**
* Close the connection to the Radius server * Close the connection to the Radius server
*/ */
function close() function close()
{ {
if ( !radius_close( $this->connection)) // (Not strictly necessary, but tidy) if ( !radius_close( $this->connection)) // (Not strictly necessary, but tidy)
{ {
$this->makeErrorText('RADIUS close error: ') ; $this->makeErrorText('RADIUS close error: ') ;
return false; return false;
} }
else else
{ {
return true; return true;
} }
} }
/** /**
* Validate login credentials * Validate login credentials
* *
* @param string $uname - The user name requesting access * @param string $uname - The user name requesting access
* @param string $pass - Password to use (usually plain text) * @param string $pass - Password to use (usually plain text)
* @param pointer &$newvals - pointer to array to accept other data read from database * @param pointer &$newvals - pointer to array to accept other data read from database
* @param boolean $connect_only - TRUE to simply connect to the server * @param boolean $connect_only - TRUE to simply connect to the server
* *
* @return integer result (AUTH_xxxx) * @return integer result (AUTH_xxxx)
* *
* On a successful login, &$newvals array is filled with the requested data from the server * On a successful login, &$newvals array is filled with the requested data from the server
*/ */
function login($uname, $pass, &$newvals, $connect_only = FALSE) function login($uname, $pass, &$newvals, $connect_only = FALSE)
{ {
// Create authentification request // Create authentification request
if (!radius_create_request($this->connection,RADIUS_ACCESS_REQUEST)) if (!radius_create_request($this->connection,RADIUS_ACCESS_REQUEST))
{ {
$this->makeErrorText('RADIUS failed authentification request: ') ; $this->makeErrorText('RADIUS failed authentification request: ') ;
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
if (trim($pass) == '') return AUTH_BADPASSWORD; // Pick up a blank password - always expect one if (trim($pass) == '') return AUTH_BADPASSWORD; // Pick up a blank password - always expect one
// Attach username and password // Attach username and password
if (!radius_put_attr($this->connection,RADIUS_USER_NAME,$uname) if (!radius_put_attr($this->connection,RADIUS_USER_NAME,$uname)
|| !radius_put_attr($this->connection,RADIUS_USER_PASSWORD,$pass)) || !radius_put_attr($this->connection,RADIUS_USER_PASSWORD,$pass))
{ {
$this->makeErrorText('RADIUS could not attach username/password: ') ; $this->makeErrorText('RADIUS could not attach username/password: ') ;
return AUTH_NOCONNECT; return AUTH_NOCONNECT;
} }
// Finally, send request to server // Finally, send request to server
switch (radius_send_request($this->connection)) switch (radius_send_request($this->connection))
{ {
case RADIUS_ACCESS_ACCEPT : // Valid username/password case RADIUS_ACCESS_ACCEPT : // Valid username/password
break; break;
case RADIUS_ACCESS_CHALLENGE : // CHAP response required - not currently implemented case RADIUS_ACCESS_CHALLENGE : // CHAP response required - not currently implemented
$this->makeErrorText('CHAP not supported'); $this->makeErrorText('CHAP not supported');
return AUTH_NOUSER; return AUTH_NOUSER;
case RADIUS_ACCESS_REJECT : // Specifically rejected case RADIUS_ACCESS_REJECT : // Specifically rejected
default: // Catch-all default: // Catch-all
$this->makeErrorText('RADIUS validation error: ') ; $this->makeErrorText('RADIUS validation error: ') ;
return AUTH_NOUSER; return AUTH_NOUSER;
} }
// User accepted here. // User accepted here.
if ($connect_only) return AUTH_SUCCESS; if ($connect_only) return AUTH_SUCCESS;
return AUTH_SUCCESS; // Not interested in any attributes returned ATM, so done. return AUTH_SUCCESS; // Not interested in any attributes returned ATM, so done.
// See if we get any attributes - not really any use to us unless we implement CHAP, so disabled ATM // See if we get any attributes - not really any use to us unless we implement CHAP, so disabled ATM
$attribs = array(); $attribs = array();
while ($resa = radius_get_attr($this->connection)) while ($resa = radius_get_attr($this->connection))
{ {
if (!is_array($resa)) if (!is_array($resa))
{ {
$this->makeErrorText("Error getting attribute: "); $this->makeErrorText("Error getting attribute: ");
exit; exit;
} }
// Decode attribute according to type (this isn't an exhaustive list) // Decode attribute according to type (this isn't an exhaustive list)
// Codes: 2, 3, 4, 5, 30, 31, 32, 60, 61 should never be received by us // Codes: 2, 3, 4, 5, 30, 31, 32, 60, 61 should never be received by us
// Codes 17, 21 not assigned // Codes 17, 21 not assigned
switch ($resa['attr']) switch ($resa['attr'])
{ {
case 8 : // IP address to be set (255.255.255.254 indicates 'allocate your own address') case 8 : // IP address to be set (255.255.255.254 indicates 'allocate your own address')
case 9 : // Subnet mask case 9 : // Subnet mask
case 14 : // Login-IP host case 14 : // Login-IP host
$attribs[$resa['attr']] = radius_cvt_addr($resa['data']); $attribs[$resa['attr']] = radius_cvt_addr($resa['data']);
break; break;
case 6 : // Service type (integer bitmap) case 6 : // Service type (integer bitmap)
case 7 : // Protocol (integer bitmap) case 7 : // Protocol (integer bitmap)
case 10 : // Routing method (integer) case 10 : // Routing method (integer)
case 12 : // Framed MTU case 12 : // Framed MTU
case 13 : // Compression method case 13 : // Compression method
case 15 : // Login service (bitmap) case 15 : // Login service (bitmap)
case 16 : // Login TCP port case 16 : // Login TCP port
case 23 : // Framed IPX network (0xFFFFFFFE indicates 'allocate your own') case 23 : // Framed IPX network (0xFFFFFFFE indicates 'allocate your own')
case 27 : // Session timeout - maximum connection/login time in seconds case 27 : // Session timeout - maximum connection/login time in seconds
case 28 : // Idle timeout in seconds case 28 : // Idle timeout in seconds
case 29 : // Termination action case 29 : // Termination action
case 37 : // AppleTalk link number case 37 : // AppleTalk link number
case 38 : // AppleTalk network case 38 : // AppleTalk network
case 62 : // Max ports case 62 : // Max ports
case 63 : // Login LAT port case 63 : // Login LAT port
$attribs[$resa['attr']] = radius_cvt_int($resa['data']); $attribs[$resa['attr']] = radius_cvt_int($resa['data']);
break; break;
case 1 : // User name case 1 : // User name
case 11 : // Filter ID - could get several of these case 11 : // Filter ID - could get several of these
case 18 : // Reply message (text, various purposes) case 18 : // Reply message (text, various purposes)
case 19 : // Callback number case 19 : // Callback number
case 20 : // Callback ID case 20 : // Callback ID
case 22 : // Framed route - could get several of these case 22 : // Framed route - could get several of these
case 24 : // State - used in CHAP case 24 : // State - used in CHAP
case 25 : // Class case 25 : // Class
case 26 : // Vendor-specific case 26 : // Vendor-specific
case 33 : // Proxy State case 33 : // Proxy State
case 34 : // Login LAT service case 34 : // Login LAT service
case 35 : // Login LAT node case 35 : // Login LAT node
case 36 : // Login LAT group case 36 : // Login LAT group
case 39 : // AppleTalk zone case 39 : // AppleTalk zone
default : default :
$attribs[$resa['attr']] = radius_cvt_string($resa['data']); // Default to string type $attribs[$resa['attr']] = radius_cvt_string($resa['data']); // Default to string type
} }
printf("Got Attr: %d => %d Bytes %s\n", $resa['attr'], strlen($attribs[$resa['attr']]), $attribs[$resa['attr']]); printf("Got Attr: %d => %d Bytes %s\n", $resa['attr'], strlen($attribs[$resa['attr']]), $attribs[$resa['attr']]);
} }
return AUTH_SUCCESS; return AUTH_SUCCESS;
} }
} }
?> ?>

View File

@@ -3,7 +3,7 @@
+ ----------------------------------------------------------------------------+ + ----------------------------------------------------------------------------+
| e107 website system | e107 website system
| |
| Copyright (C) 2008-2009 e107 Inc (e107.org) | Copyright (C) 2008-2013 e107 Inc (e107.org)
| http://e107.org | http://e107.org
| |
| |
@@ -26,11 +26,64 @@ define("ALT_AUTH_ACTION", "radius");
require_once(e_PLUGIN."alt_auth/alt_auth_adminmenu.php"); require_once(e_PLUGIN."alt_auth/alt_auth_adminmenu.php");
$mes = e107::getMessage(); $mes = e107::getMessage();
class alt_auth_radius extends alt_auth_admin
{
private $radius;
public function __construct()
{
}
public function readOptions()
{
$this->radius = $this->altAuthGetParams('radius');
}
public function showForm($mes)
{
$ns = e107::getRender();
$frm = new form;
$text = $frm->form_open('post',e_SELF);
$text .= "<table class='table adminform'>";
$text .= "<tr><td>".LAN_RADIUS_01."</td><td>";
$text .= $frm->form_text('radius_server', 35, vartrue($this->radius['radius_server']), 120);
$text .= "</td></tr>\n";
$text .= "<tr><td>".LAN_RADIUS_02."</td><td>";
$text .= $frm->form_text('radius_secret', 35, vartrue($this->radius['radius_secret']), 200);
$text .= "</td></tr>\n";
$tmp = $this->alt_auth_get_field_list('radius', $frm, $this->radius, FALSE);
if ($tmp)
{
$text .= "<tr><td class='forumheader2' colspan='2'>".LAN_ALT_27."</td></tr>\n".$tmp;
unset($tmp);
}
$text .= "<tr><td class='forumheader' colspan='2' style='text-align:center;'>";
// $text .= $frm -> form_button("submit", "update", LAN_ALT_2);
$text .= e107::getForm()->admin_button('update', LAN_UPDATE,'update');
$text .= "</td></tr>\n";
$text .= "</table>\n";
$text .= $frm->form_close();
$ns->tablerender(LAN_RADIUS_06, $mes->render().$text);
$ns->tablerender(LAN_ALT_40.LAN_ALT_41, $this->alt_auth_test_form('radius',$frm));
}
}
$message = ''; $message = '';
$radiusAdmin = new alt_auth_radius();
if(vartrue($_POST['update'])) if(vartrue($_POST['update']))
{ {
// $message .= alt_auth_post_options('radius'); // $message .= alt_auth_post_options('radius');
$mes->addSuccess(alt_auth_post_options('radius')); $mes->addSuccess($radiusAdmin->alt_auth_post_options('radius'));
} }
@@ -43,47 +96,15 @@ if (!extension_loaded('radius'))
if($message) if($message)
{ {
$ns->tablerender("","<div style='text-align:center;'>".$message."</div>"); $ns->tablerender('',"<div style='text-align:center;'>".$message."</div>");
} }
$radiusAdmin->readOptions();
$sql -> db_Select("alt_auth", "*", "auth_type = 'radius' "); $radiusAdmin->showForm($mes);
while($row = $sql->db_Fetch())
{
$radius[$row['auth_parmname']] = base64_decode(base64_decode($row['auth_parmval'])); // Encoding is new for 0.8
}
$frm = new form;
$text = $frm -> form_open("post",e_SELF);
$text .= "<table class='table adminform'>";
$text .= "<tr><td>".LAN_RADIUS_01."</td><td>";
$text .= $frm -> form_text("radius_server", 35, vartrue($radius['radius_server']), 120);
$text .= "</td></tr>";
$text .= "<tr><td>".LAN_RADIUS_02."</td><td>"; require_once(e_ADMIN.'footer.php');
$text .= $frm -> form_text('radius_secret', 35, vartrue($radius['radius_secret']), 200);
$text .= "</td></tr>";
$tmp = alt_auth_get_field_list('radius',$frm, vartrue($ldap), FALSE);
if ($tmp)
{
$text .= "<tr><td class='forumheader2' colspan='2'>".LAN_ALT_27."</td></tr>".$tmp;
unset($tmp);
}
$text .= "<tr><td class='forumheader' colspan='2' style='text-align:center;'>";
// $text .= $frm -> form_button("submit", "update", LAN_ALT_2);
$text .= e107::getForm()->admin_button("update", LAN_UPDATE,'update');
$text .= "</td></tr>";
$text .= "</table>";
$text .= $frm -> form_close();
$ns -> tablerender(LAN_RADIUS_06, $mes->render() . $text);
$ns->tablerender(LAN_ALT_40.LAN_ALT_41,alt_auth_test_form('radius',$frm));
require_once(e_ADMIN."footer.php");
function radius_conf_adminmenu() function radius_conf_adminmenu()