From bcad40a05ab2dc2a341a3227e30b96668bce4500 Mon Sep 17 00:00:00 2001 From: Karl 'vollmerk' Vollmer Date: Thu, 9 Jun 2005 16:34:40 +0000 Subject: New Import --- libglue/README | 393 ++++++++++++++++++++++++++++++++++++++++++++++++ libglue/auth.php | 399 ++++++++++++++++++++++++++++++++++++++++++++++++ libglue/config.php | 173 +++++++++++++++++++++ libglue/dbh.php | 53 +++++++ libglue/libdb.php | 95 ++++++++++++ libglue/session.php | 417 +++++++++++++++++++++++++++++++++++++++++++++++++++ libglue/session2.php | 346 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 1876 insertions(+) create mode 100644 libglue/README create mode 100644 libglue/auth.php create mode 100644 libglue/config.php create mode 100644 libglue/dbh.php create mode 100644 libglue/libdb.php create mode 100644 libglue/session.php create mode 100644 libglue/session2.php (limited to 'libglue') diff --git a/libglue/README b/libglue/README new file mode 100644 index 00000000..b847586b --- /dev/null +++ b/libglue/README @@ -0,0 +1,393 @@ +libglue - 8/17/03 + +libglue provides a set of libraries for use with applications +developed here at Oregon State University. + +This set of libraries includes: +- mysql session handling, +- MySQL/LDAP/'shared' authentication methods +- a database handler + +Contents: +1 Authentication Methods + 1.1 LDAP Authentication + 1.2 MySQL Authentication + 1.3 Shared Authentication +2 Database schemas + 2.1 For Session management + 2.2 For LDAP Authentication + 2.3 For MySQL Authentication + 2.4 For Shared Authentication +3 The Config file + 3.1 Formatting + 3.2 Subsections + 3.3 Arrays + 3.3 Retrieving options +4 Session management +5 Libglue in action + +6 Help, FAQs + + +1 Authentication Methods +-------------------------------------------------------------------------------- + Libglue currently supports 3 authentication methods: LDAP, MySQL, and + 'Shared.' It can support any combination of these concurrently, by falling + through in the order you specify (see Section 3.3). + + 1.1 LDAP Authentication + ------------------------------------------------------------------------------ + To use LDAP authentication, you must have LDAP support for PHP. + See http://php.net/manual/en/ref.ldap.php for how to configure php with LDAP. + + You must provide credentials for your LDAP server in the config file. + Anonymous LDAP authentication is possible, but not with libglue today. + + libglue has two functions for ldap authentication, both in 'LIBGLUE/auth.php': + + mixed get_ldap_user($username [,$fields]) + + object auth_ldap($username,$password) + + 'auth_ldap' is intended for internal use, while 'get_ldap_user' is a utility + for app developers to use. Both have similar layouts: + + - connect to ldap service + - bind to ldap with credential from config file + - search for '$username' in the space specified in the config file + - attempt to bind with supplied user credentials (auth_ldap only) + + 'get_ldap_user' returns an array of fields on success (if '$fields' is + not specified, it will return all the information for the specified user), + and an error string on failure. + + 'auth_ldap' returns an 'auth_response' object, with success indicated by + the value of auth_response->success. (This class is defined in 'auth.php'). + + 'auth_ldap' is typically only going to be called from a login script. + 'get_ldap_user' could be used when granting access to a new user. + + Config Options: + ldap_host + ldap_auth_dn + ldap_user_dn + ldap_filter + ldap_pass + ldap_fields + ldap_version + + + 1.2 MySQL Authentication + ------------------------------------------------------------------------------ + MySQL Authentication (like all of libglue) requires MySQL support in PHP. + It defaults to using the MySQL PASSWORD() function to check passwords, but + can also use PHP crypt() for compatability with other applications + (pam_mysql for example). + + MySQL Authentication assumes the local database specified in the config file + is being used. It is possible to support a different database, but that + begins to duplicate functionality from Share Authentication (Section 1.3). + + Config Options: + mysql_host + mysql_db + mysql_username + mysql_passwd + mysql_table + mysql_usercol + mysql_passcol + mysql_other + mysql_fields + + 'mysql_other' is an optional clause appended to the query. + Ex: mysql_other = "access = 'admin'" + + 'mysql_fields' is a comma separated list of the fields to return from + 'mysql_table' + Ex: mysql_fields = 'id,username,email,homedir' + + 1.3 Shared Authentication + ------------------------------------------------------------------------------ + Because libglue uses a mysql database to store session info, it is possible + to share session information between applications, creating a "Single Sign + On" (SSO) framework for web applications. libglue supports this out of + the box, with the following assumptions: + 1) The initial authentication is being handled elsewhere + 2) "SSO" session data is stored in a mysql database. + 3) The SSO database uses the schema described in Section 2.3. + + libglue keeps track of the 'type' of authentication each session uses, so + can still use LDAP or MySQL authentication when also using SSO. + + Config options: + sso_host + sso_db + sso_username + sso_pass + sso_table + sso_sid + sso_usercol + sso_expirecol + sso_length + sso_dbh_name + + +2 Database schemas +-------------------------------------------------------------------------------- + + Below are sample schemas for use with libglue. Mandatory fields are + indicated with a '*'. Unless stated otherwise, field NAMES can be set in + the config file. + + 2.1 For Session Management + ------------------------------------------------------------------------------ + CREATE TABLE session_data ( + * id varchar(32) NOT NULL default '', + * username varchar(16) NOT NULL default '', + * expire int(10) unsigned NOT NULL default '0', + * type enum('sso','mysql','ldap') NOT NULL default 'sso', + * data text, + PRIMARY KEY (id)) + + This session table should work for any type of authentication you do. + 'id' is an md5sum by default (as generated by php) but you can make + something else up if you've got the spare entropy. 'Type' obviously + only applies if you're using more than 1 type of authentication, + but the code assumes that it's present. + + 'data' is the field where serialized php data (from $_SESSION) is stored. + If you overflow this field, weird things may happen. + + + 2.2 For LDAP Authentication + ------------------------------------------------------------------------------ + + Basic LDAP authentication with libglue doesn't require a mysql database, + only session management. However, you will most likely need to store + some user information locally, in which case the table definition in + Section 2.3 is a good starting point. + + 2.3 For MySQL Authentication + ------------------------------------------------------------------------------ + + CREATE TABLE user ( + * id int(11) NOT NULL default '0', + * username varchar(255) NOT NULL default '', + * password varchar(255) default NULL, + fullname varchar(255) NOT NULL default '', + email varchar(255) default NULL, + status enum('disabled','enabled','dev') NOT NULL default 'enabled', + expire date default NULL, + phone varchar(255) NOT NULL default '', + PRIMARY KEY (id), + UNIQUE KEY username (username), + UNIQUE KEY id (id) + } + + Feel free to add columns to this table and then specify them in + 'mysql_fields' to make them part of your session data. + + 2.3 For Shared Authentication + ------------------------------------------------------------------------------ + + If you need to store user data locally, see the definition in Section 2.3. + + +3 The Config file +-------------------------------------------------------------------------------- + + 3.1 Formatting + ------------------------------------------------------------------------------ + The libglue config file is a lot like the smb.cnf file if you've ever used + samba (it's really easy to parse). Options are specified like + + option = value + + 'option' is a letter followed by any number of letters or numbers. + The spaces between 'option' and 'value' are optional. + 'value' may be single quoted, double quoted, or not quoted at all. + semicolons at the end of the line are ignored. + '#' is the single-line comment character. + + 3.2 Subsections + ------------------------------------------------------------------------------ + The config file parser can generate subsections in the config: + + > [libglue] + > option1 = value; + > option2 = 'value'; + > option3 = "value" + > [conf] + > option1 = value; + > otheroption = othervalue; + > [other] + > foo = "bar"; + + The parser then returns: + array( + 'libglue' => ('option1' => 'value', + 'option2' => 'value', + 'option3' => 'value'), + 'conf' => ('option1' => 'value', + 'otheroption' => 'othervalue'), + 'other' => ('foo' => 'bar') + ); + + 3.3 Arrays + ------------------------------------------------------------------------------ + You can create arrays of values in the config file by declaring an option + multiple times: + + [libglue] + ldap_fields = 'cn' + ldap_fields = 'homedirectory' + ldap_fields = 'uidnumber' + ldap_fields = 'uid' + ldap_fields = 'osuuid' + + would return the following: + array( + 'libglue' => ('ldap_fields' => ( + 0 => 'cn', + 1 => 'homedirectory', + 2 => 'uidnumber', + 3 => 'uid', + 4 => 'osuuid') + ) + ) + + + 3.3 Retrieving options + ------------------------------------------------------------------------------ + LIBGLUE/config.php defines two functions, conf() and libglue_param() for + retrieving values from the config file. See "Libglue in action" below. + + +4 Session Data and Management +-------------------------------------------------------------------------------- + + Libglue should relieve some of the burden of session management from your app + once a user is authenticated. The config file has the following parameters, + + user_data_name - Name of the array to store authentication session data in. + Ex: + user_data_name = 'user' + + Libglue then puts all the account information it retrieves + into $_SESSION['user'] + + user_id - fieldname for userid, + stored in $_SESSION[user_data_name][user_id] + user_username - fieldname for username, + stored in $_SESSION[user_data_name][user_username] + + Then for each of your authentication methods: + + ldap_uidfield = 'uidnumber' + ldap_usernamefield = 'uid' + mysql_uidfield = 'id' + mysql_usernamefield = 'username' + + Note that in this case, 'sso' isn't really an authentication method + (the info has to be looked up either in ldap or mysql). + + What this lets you do is ignore account type in your application, since + every session will have the same field names. + + +5 Libglue in action +-------------------------------------------------------------------------------- + + Libglue assumes there are three basic types of files in your application: + 1) Login/Authentication page + 2) Restricted pages + 3) Logout/Cleanup page + + Example login and logout pages are in the LIBGLUE/examples directory. + + For (2), you'll be calling the same code over and over. It is a good idea + to create an init file to take care of these common tasks in your application. + In each file, you'll do a + + > $restricted = 1; + > require_once('/path/to/init.php'); + + right off the bat; libglue needs to run before anything else so it can send + HTTP headers for cookies and redirection if necessary. + + Here is a sample init.php: + + + + + libglue_param() and conf() make use of static member variables and + tests on paramter types to register/retrieve config data. When passed an + array, these functions assume you're registering config options. If given + a string, as in: + + $database_name = libglue_param('local_db'); + + the function will look for the key 'local_db' in the values that have been + previously registered with it. This is a little bit hokey, but objects + don't yet support static members in php so it's about the best we can do. + + + Session management is just taken care of; anything you put in $_SESSION in + your app is serialized, stored in the db when the page is done redering, + and retrieved on page load. + + + Database handle management is nice with libglue; if you've defined + 'dbh' in the config file, you can call dbh() to use that database handle again: + + $dbh = dbh(); + mysql_query($sql, $dbh); + + or + + mysql_query($sql, dbh()); + + +6 Help, FAQs +-------------------------------------------------------------------------------- + + Libglue is distributed at: + + http://oss.oregonstate.edu/libglue/ + + as it becomes more mature and widely used, this page may include more help + documentation. + + For now, feel free to email + + cws-prog@lists.orst.edu + + with any questions or bug reports. + +-- Central Web Services, + Oregon State University + diff --git a/libglue/auth.php b/libglue/auth.php new file mode 100644 index 00000000..0ef41e8c --- /dev/null +++ b/libglue/auth.php @@ -0,0 +1,399 @@ +error = ldap_error($ldap_link); + $auth['error'] = libglue_param('login_failed'); + } + } + } + + // + // Here means we couldn't use the service. + // So it's most likely config related. + // Check the username and password? + // + else + { + $auth['error'] = libglue_param('bad_auth_cred'); + } + } + + // + // This most often will mean we can't reach the server. + // Perhaps it's down, or we mistyped the address. + // + else + { + $auth['error'] = libglue_param('connect_error'); + } + + // Done with the link, give it back + ldap_close($ldap_link); + $auth['type'] = 'ldap'; + return $auth; +} + +/* + * MySQL authentication. + * returns true/false depending on whether the user was authenticated + * successfully + * The crypt settings below assume the php crypt() function created the passwords. + * But hopson updated it to use mysql PASSWORD() instead + */ + +function auth_mysql($username, $password) { + + $auth = array(); + $auth['success'] = 0; + + // Did we get fed proper variables? + if(!$username or !$password) { + $auth['error'] = 'Empty username/password'; + return $auth; + } + + // + // Retrieve config parameters set in config.php + // + $dbhost = libglue_param('mysql_host'); + $dbuser = libglue_param('mysql_user'); + $dbpass = libglue_param('mysql_pass'); + $dbname = libglue_param('mysql_db'); + $passfield = libglue_param('mysql_passcol'); + $table = libglue_param('mysql_table'); + $usercol = libglue_param('mysql_usercol'); + $other = libglue_param('mysql_other'); + $fields = libglue_param('mysql_fields'); + + + $mysql_uidfield = libglue_param('mysql_uidfield'); + $mysql_usernamefield = libglue_param('mysql_usernamefield'); + + if(!preg_match("/$mysql_uidfield/",$fields)) $fields .= ",$mysql_uidfield"; + if(!preg_match("/$mysql_usernamefield/",$fields)) $fields .= ",$mysql_usernamefield"; + + if($other == '') $other = '1=1'; + + if ($mysql_link = @mysql_connect($dbhost,$dbuser,$dbpass)) + { + // + // now retrieve the stored password to use as salt + // for password checking + // + $sql = "SELECT $passfield FROM $table" . + " WHERE $usercol = '$username' " . + " AND $other LIMIT 1"; + @mysql_select_db($dbname, $mysql_link); + $result = @mysql_query($sql, $mysql_link); + $row = @mysql_fetch_array($result); + + $password_check_sql = "PASSWORD('$password')"; + + $sql = "SELECT version()"; + $db_results = @mysql_query($sql, $mysql_link); + $version = @mysql_fetch_array($db_results); + + $mysql_version = substr(preg_replace("/(\d+)\.(\d+)\.(\d+).*/","$1$2$3",$version[0]),0,3); + + if ($mysql_version > "409" AND substr($row[0],0,1) !== "*") { + $password_check_sql = "OLD_PASSWORD('$password')"; + } + + $sql = "SELECT $fields FROM $table" . + " WHERE $usercol = '$username'" . + " AND $passfield = $password_check_sql" . + " AND $other LIMIT 1"; + $rs = @mysql_query($sql, $mysql_link); + //This should only fail on a badly formed query. + if(!$rs) + { + $auth['error'] = @mysql_error(); + } + + // + // Retrieved the right info, set auth->success and info. + // + if (@mysql_num_rows($rs) == 1) + { + // username and password are successful + $row = mysql_fetch_array($rs); + $sess_username = libglue_param('user_username'); + $sess_id = libglue_param('user_id'); + $auth[$info][$sess_username] = $row[$mysql_usernamefield]; + $auth[$info][$sess_id] = $row[$mysql_uidfield]; + $auth[$info] = $row; + $auth['info'] = $row; + $auth['success'] = 1; + } + + // + // We didn't find anything matching. No user, bad password, ? + // + else + { + $auth['error'] = libglue_param('login_failed'); + } + } + + // + // Couldn't connect to database at all. + // + else + { + $auth['error'] = libglue_param('bad_auth_cred'); + } + + $auth['type'] = 'mysql'; + return $auth; + +} // auth_mysql + + +function auth_sso ($username, $password) +{ + $auth = new auth_response(); + $auth->success = 0; + $auth->error = "SSO Authentication failed."; + return $auth; +} + +// This is the auth_response class that will be returned during +// and authentication - this allows us to set some variables +// by the session for later lookup +class auth_response { + var $username; + var $userid; + var $error; + var $success; + var $info; +} + + +?> diff --git a/libglue/config.php b/libglue/config.php new file mode 100644 index 00000000..c1ca07a8 --- /dev/null +++ b/libglue/config.php @@ -0,0 +1,173 @@ +"; + + $count = 0; + $config_name = ''; + foreach($data as $value) + { + $count++; + if (preg_match("/^\[([A-Za-z]+)\]$/",$value,$matches)) + { + // If we have previous data put it into $results... + if (!empty($config_name) && count(${$config_name})) $results[$config_name] = ${$config_name}; + $config_name = $matches[1]; + } // if it is a [section] name + + elseif ($config_name) + { + // if it's not a comment + if (preg_match("/^(\w[\w\d]*)\s*=\s*\"{1}(.*?)\"{1};*$/",$value,$matches) + || preg_match("/^(\w[\w\d]*)\s*=\s*\'{1}(.*?)\'{1};*$/", $value, $matches) + || preg_match("/^(\w[\w\d]*)\s*=\s*[\'\"]{0}(.*)[\'\"]{0};*$/",$value,$matches)) + { + if (isset(${$config_name}[$matches[1]]) && is_array(${$config_name}[$matches[1]]) && isset($matches[2]) ) + { + if($debug) + echo "Adding value $matches[2] to existing key $matches[1]\n"; + array_push(${$config_name}[$matches[1]], $matches[2]); + } + elseif (isset(${$config_name}[$matches[1]]) && isset($matches[2]) ) + { + if($debug) + echo "Adding value $matches[2] to existing key $matches[1]\n"; + ${$config_name}[$matches[1]] = array(${$config_name}[$matches[1]],$matches[2]); + } + elseif ($matches[2] !== "") + { + if($debug) + echo "Adding value $matches[2] for key $matches[1]\n"; + ${$config_name}[$matches[1]] = $matches[2]; + } + + // if there is something there and it's not a comment + elseif ($value{0} !== "#" AND strlen(trim($value)) > 0) + { + echo "Error Invalid Config Entry --> Line:$count"; die; + } // else if it's not a comment and there is something there + + else + { + if($debug) + echo "Key $matches[1] defined, but no value set\n"; + } + } // end if it's not a comment + + } // else if no config_name + + + elseif (preg_match("/^([\w\d]+)\s+=\s+[\"]{1}(.*?)[\"]{1}$/",$value,$matches) + || preg_match("/^([\w\d]+)\s+=\s+[\']{1}(.*?)[\']{1}$/", $value, $matches) + || preg_match("/^([\w\d]+)\s+=\s+[\'\"]{0}(.*)[\'\"]{0}$/",$value,$matches)) + { + if (is_array($results[$matches[1]]) && isset($matches[2]) ) + { + if($debug) + echo "Adding value $matches[2] to existing key $matches[1]\n"; + array_push($results[$matches[1]], $matches[2]); + } + elseif (isset($results[$matches[1]]) && isset($matches[2]) ) + { + if($debug) + echo "Adding value $matches[2] to existing key $matches[1]\n"; + $results[$matches[1]] = array($results[$matches[1]],$matches[2]); + } + elseif ($matches[2] !== "") + { + if($debug) + echo "Adding value $matches[2] for key $matches[1]\n"; + $results[$matches[1]] = $matches[2]; + } + + // if there is something there and it's not a comment + elseif ($value{0} !== "#" AND strlen(trim($value)) > 0) + { + echo "Error Invalid Config Entry --> Line:$count"; die; + } // else if it's not a comment and there is something there + + else + { + if($debug) + echo "Key $matches[1] defined, but no value set\n"; + } + + } // end else + + } // foreach + + if (count(${$config_name})) + { + $results[$config_name] = ${$config_name}; + } + + if($debug) echo ""; + + return $results; + +} // end read_config + +function libglue_param($param,$clobber=0) +{ + static $params = array(); + if(is_array($param)) + //meaning we are setting values + { + foreach ($param as $key=>$val) + { + if(!$clobber && isset($params[$key])) + { + echo "Error: attempting to clobber $key = $val\n"; + exit(); + } + $params[$key] = $val; + } + return true; + } + else + //meaning we are trying to retrieve a parameter + { + if(isset($params[$param])) return $params[$param]; + else return false; + } +} + +function conf($param,$clobber=0) +{ + static $params = array(); + if(is_array($param)) + //meaning we are setting values + { + foreach ($param as $key=>$val) + { + if(!$clobber && isset($params[$key])) + { + echo "Error: attempting to clobber $key = $val\n"; + exit(); + } + $params[$key] = $val; + } + return true; + } + else + //meaning we are trying to retrieve a parameter + { + if(isset($params[$param])) return $params[$param]; + else return false; + } +} + +function dbh($str='') +{ + if($str !== '') $dbh = libglue_param(libglue_param($str)); + else $dbh = libglue_param(libglue_param('dbh')); + if(!is_resource($dbh)) die("Bad database handle: $dbh"); + else return $dbh; +} diff --git a/libglue/dbh.php b/libglue/dbh.php new file mode 100644 index 00000000..71d04b9c --- /dev/null +++ b/libglue/dbh.php @@ -0,0 +1,53 @@ +$dbh)); + } + + return $dbh; +} + +?> diff --git a/libglue/libdb.php b/libglue/libdb.php new file mode 100644 index 00000000..00e8a9b2 --- /dev/null +++ b/libglue/libdb.php @@ -0,0 +1,95 @@ +$user); + + //Somewhat stupidly, we have to initialize $_SESSION here, + // or sess_write will blast it for us + $_SESSION = $data; + + $db_data = serialize($data); + $local_dbh = check_sess_db('local'); + + //Local stuff we need: + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_expirecol = libglue_param('local_expirecol'); + $local_typecol = libglue_param('local_typecol'); + $sql= "INSERT INTO $local_table ". + " ($local_sid,$local_usercol,$local_datacol,$local_expirecol,$local_typecol)". + " VALUES ('$sso_sid','$sso_usercol','$db_data','$sso_expire','sso')"; + $db_result = mysql_query($sql, $local_dbh); + + if($db_result) return TRUE; + else return FALSE; +} + +function get_local_session($sid) +{ + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_expirecol = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_typecol = libglue_param('local_typecol'); + + $local_dbh = check_sess_db('local'); + $time = time(); + $sql = "SELECT * FROM $local_table WHERE $local_sid='$sid' AND $local_expirecol > $time"; + $db_result = mysql_query($sql, $local_dbh); + $session = mysql_fetch_array($db_result); + + if(is_array($session)) $retval = $session; + else $retval = FALSE; + + if($retval === FALSE) + { + //Find out what's going on + } + + return $retval; +} + +function get_sso_session($sid) +{ + $sso_table = libglue_param('sso_table'); + $sso_sid = libglue_param('sso_sid'); + $sso_expirecol = libglue_param('sso_expirecol'); + $sso_length = libglue_param('sso_length'); + $sso_usercol = libglue_param('sso_usercol'); + + $sso_dbh = check_sess_db('sso'); + $time = time(); + $sql = "SELECT * FROM $sso_table WHERE $sso_sid='$sid' AND $sso_expirecol > $time"; + $db_result = mysql_query($sql, $sso_dbh); + $sso_session = mysql_fetch_array($db_result); + + $retval = (is_array($sso_session))?$sso_session:FALSE; + return $retval; +} + + + +// This will start the session tools, then destroy anything in the database then +// clear all of the session information +function logout ($id=0) +{ + sess_destroy($id); + $login_page = libglue_param('login_page'); + // should clear both the database information as well as the + // current session info + header("Location: $login_page"); + die(); + return true; +} + +// Double checks that we have a database handle +// Args are completely ignored - we're using a database here +function sess_open($save_path, $session_name) +{ + $local_dbh = check_sess_db(); + if ( !is_resource($local_dbh) ) + { + echo "\n"; + return FALSE; + } + + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(in_array('sso',$auth_methods,TRUE)) + { + $sso_dbh = check_sess_db('sso'); + if ( !is_resource($sso_dbh) ) + { + echo "\n"; + return FALSE; + } + } + return TRUE; +} + +// Placeholder function, does nothing +function sess_close() +{ + return true; +} + +// Retrieve session identified by 'key' from the database +// and return the data field +function sess_read($key) +{ + $retval = 0; + $session = get_local_session($key); + $datacol = libglue_param('local_datacol'); + if(is_array($session)) $retval = $session[$datacol]; + else $retval = ""; + return $retval; +} + + +// +// Save the session data $val to the database +// +function sess_write($key, $val) +{ + $local_dbh = check_sess_db('local'); + $local_datacol = libglue_param('local_datacol'); + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + + $auth_methods = libglue_param('auth_methods'); + $local_expirecol = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $time = $local_length+time(); + + // If they've got the long session + if ($_COOKIE['amp_longsess'] == '1') { + $time = time() + 86400*364; + } + + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(!in_array('sso',$auth_methods,TRUE)) + { + // If not using sso, we now need to update the expire time + $sql = "UPDATE $local_table SET $local_datacol='" . sql_escape($val) . "',$local_expirecol='$time'". + " WHERE $local_sid = '$key'"; + } + else $sql = "UPDATE $local_table SET $local_datacol='" . sql_escape($val) . "',$local_expirecol='$time'". + " WHERE $local_sid = '$key'"; + + return mysql_query($sql, $local_dbh); +} + +// +// Remove the current session from the database. +// +function sess_destroy($id=0) +{ + if($id == 0) { + session_start(); + $id = session_id(); + } + + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(in_array('sso',$auth_methods,TRUE)) + { + $sso_sid = libglue_param('sso_sid'); + $sso_table = libglue_param('sso_table'); + $sso_dbh = check_sess_db('sso'); + $sql = "DELETE FROM $sso_table WHERE $sso_sid = '$id' LIMIT 1"; + $result = mysql_query($sql, $sso_dbh); + } + $local_sid = libglue_param('local_sid'); + $local_table = libglue_param('local_table'); + + $local_dbh = check_sess_db('local'); + $sql = "DELETE FROM $local_table WHERE $local_sid = '$id' LIMIT 1"; + $result = mysql_query($sql, $local_dbh); + $_SESSION = array(); + + /* Delete the long ampache session cookie */ + setcookie ("amp_longsess", "", time() - 3600); + + /* Delete the ampache cookie as well... */ + setcookie (libglue_param('sess_name'),"", time() - 3600); + + return TRUE; +} + +// +// This function is called with random frequency +// to remove expired session data +// +function sess_gc($maxlifetime) +{ + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(in_array('sso',$auth_methods,TRUE)) + { + //Delete old sessions from SSO + // We do 'where length' so we don't accidentally blast + // another app's sessions + $sso_expirecol = libglue_param('sso_expirecol'); + $sso_table = libglue_param('sso_table'); + $sso_length = libglue_param('sso_length'); + $local_length = libglue_param('local_length'); + + $sso_dbh = check_sess_db('sso'); + $time = time(); + $sql = "DELETE FROM $sso_table WHERE $sso_expirecol < $time". + " AND $sso_length = '$local_length'"; + $result = mysql_query($sql, $sso_dbh); + } + $local_expirecol = libglue_param('local_expirecol'); + $local_table = libglue_param('local_table'); + $time = time(); + $local_dbh = check_sess_db('local'); + $sql = "DELETE FROM $local_table WHERE $local_expirecol < $time"; + $result = mysql_query($sql, $local_dbh); + return true; +} + +// +// Register all our cool session handling functions +// +session_set_save_handler( + "sess_open", + "sess_close", + "sess_read", + "sess_write", + "sess_destroy", + "sess_gc"); +?> diff --git a/libglue/session2.php b/libglue/session2.php new file mode 100644 index 00000000..171dc1ca --- /dev/null +++ b/libglue/session2.php @@ -0,0 +1,346 @@ +$dbh)); + + if(is_resource($dbh)) return $dbh; + else die("Could not connect to $dbtype database for session management"); +} + +/* This function is public */ +function check_session($id=null) +{ + if(is_null($id)) + { + //From Karl Vollmer, vollmerk@net.orst.edu: + // naming the session and starting it is sufficient + // to retrieve the cookie + $name = libglue_param('sess_name'); + if(!empty($name)) session_name($name); + session_start(); + $id = strip_tags($_COOKIE[$name]); + } + + // Now what we have a session id, let's verify it: + if(libglue_sso_mode()) + { + // if sso mode, we must have a valid sso session already + $sso_sess = libglue_sso_check($id); + if(!is_null($sso_sess)) + { + // if sso is valid, it's okay to create a new local session + if($local_sess = libglue_local_check($id)) + { + return true; + } + else + { + libglue_local_create($id, + $sso_sess[libglue_param('sso_username_col')], + 'sso', + $sso_sess[libglue_param('sso_expire_col')]); + return true; + } + } + else + // libglue_sso_check failed + { + libglue_sess_destroy($id); + return false; + } + } + else + { + //if not in sso mode, there must be a local session + if($local_sess = libglue_local_check($id)) + { + return true; + } + else + { + //you're gone buddy + libglue_sess_destroy($id); + return false; + } + } +} + +// private function, don't ever use this: +function libglue_sso_mode() +{ + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + return (in_array('sso',$auth_methods))?true:false; +} + +function libglue_sso_check($sess_id) +{ + // Read the sso info from the config file: + $sso_table = libglue_param('sso_table'); + $sso_sid = libglue_param('sso_sessid_col'); + $sso_expire_col = libglue_param('sso_expire_col'); + $sso_length = libglue_param('sso_length'); + $sso_username_col = libglue_param('sso_username_col'); + + $sso_dbh = libglue_sess_db('sso'); + $sql = "SELECT * FROM $sso_table WHERE $sso_sid='$sess_id' AND $sso_expire_col > UNIX_TIMESTAMP()"; + $db_result = db_query($sql, $sso_dbh); + if(is_resource($db_result)) $sso_session = db_fetch($db_result); + else $sso_session = null; + + $retval = (is_array($sso_session))?$sso_session:null; + return $retval; +} + +function libglue_local_check($sess_id) +{ + static $retval = -1; + if($retval != -1) return $retval; + + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_expirecol = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_typecol = libglue_param('local_typecol'); + + $local_dbh = libglue_sess_db('local'); + $sql = "SELECT $local_datacol FROM $local_table WHERE $local_sid='$sess_id' AND $local_expirecol > UNIX_TIMESTAMP()"; + $db_result = db_query($sql, $local_dbh); + if(is_resource($db_result)) $session = db_fetch($db_result); + else $session = null; + + if(is_array($session)) + { + $retval = $session[$local_datacol]; + } + else $retval = null; + return $retval; +} + +function libglue_local_create($sess_id, $username, $type, $expire) +{ + if($type === "sso" || $type === "ldap") + $userdata = get_ldap_user($username); + else if($type === "mysql") + $userdata = get_mysql_user($username); + + $data = array(libglue_param('user_data_name')=>$userdata); + + // It seems we have to set $_SESSION manually, or it gets blasted + // by php's session write handler + $_SESSION = $data; + $db_data = serialize($data); + $local_dbh = libglue_sess_db('local'); + + // Local parameters we need: + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_expirecol = libglue_param('local_expirecol'); + $local_typecol = libglue_param('local_typecol'); + + // session data will be saved when the script terminates, + // but not the rest of this fancy info + $sql= "INSERT INTO $local_table ". + " ($local_sid,$local_usercol,$local_datacol,$local_expirecol,$local_typecol)". + " VALUES ('$sess_id','$username','$db_data','$expire','$type')"; + $db_result = db_query($sql, $local_dbh); + if(!$db_result) die("Died trying to create local session:

$sql
"); +} + +function sess_open() +{ + if(libglue_sso_mode()) + { + if(!is_resource(libglue_sess_db('sso'))) + { + die("\n"); + return false; + } + } + + if(!is_resource(libglue_sess_db('local'))) + { + die("\n"); + return false; + } + return true; +} + +function sess_close(){ return true; } + +function sess_write($sess_id, $sess_data) +{ + $local_dbh = libglue_sess_db('local'); + $local_datacol = libglue_param('local_datacol'); + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + + $auth_methods = libglue_param('auth_methods'); + $local_expire = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $time = $local_length+time(); + + // If not using sso, we now need to update the expire time + $local_expire = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $time = $local_length+time(); + $sql = "UPDATE $local_table SET $local_datacol='$sess_data',$local_expire='$time'". + " WHERE $local_sid = '$sess_id'"; + db_query($sql, $local_dbh); + + if(libglue_sso_mode()) + { + $sso_table = libglue_param('sso_table'); + $sso_expire_col = libglue_param('sso_expire_col'); + $sso_sess_length = libglue_param('sso_length_col'); + $sso_sess_id = libglue_param('sso_sessid_col'); + $time = time(); + $sql = "UPDATE $sso_table SET $sso_expire_col = $sso_sess_length + UNIX_TIMESTAMP() WHERE $sso_sess_id = '$sess_id'"; + $sso_dbh = libglue_sess_db('sso'); + db_query($sql, $sso_dbh); + } + return true; +} + +// +// This function is called with random frequency +// to remove expired session data +// +function sess_gc($maxlifetime) +{ + if(libglue_sso_mode()) + { + //Delete old sessions from SSO + // We do 'where length' so we don't accidentally blast + // another app's sessions + $sso_expirecol = libglue_param('sso_expire_col'); + $sso_table = libglue_param('sso_table'); + $sso_length = libglue_param('sso_length_col'); + $local_length = libglue_param('local_length'); + + $sso_dbh = libglue_sess_db('sso'); + $time = time(); + $sql = "DELETE FROM $sso_table WHERE $sso_expirecol < $time". + " AND $sso_length = '$local_length'"; + $result = db_query($sql, $sso_dbh); + } + $local_expire = libglue_param('local_expire'); + $local_table = libglue_param('local_table'); + $time = time(); + $local_dbh = libglue_sess_db('local'); + $sql = "DELETE FROM $local_table WHERE $local_expire < $time"; + $result = db_query($sql, $local_dbh); + return true; +} + +function libglue_sess_destroy($id=null) +{ + if(is_null($id)) + { + //From Karl Vollmer, vollmerk@net.orst.edu: + // naming the session and starting it is sufficient + // to retrieve the cookie + $name = libglue_param('sess_name'); + if(!empty($name)) session_name($name); + session_start(); + $id = strip_tags($_COOKIE[$name]); + } + if(libglue_sso_mode()) + { + $sso_sid = libglue_param('sso_sessid_col'); + $sso_table = libglue_param('sso_table'); + $sso_dbh = libglue_sess_db('sso'); + $sql = "DELETE FROM $sso_table WHERE $sso_sid = '$id' LIMIT 1"; + $result = db_query($sql, $sso_dbh); + } + $local_sid = libglue_param('local_sid'); + $local_table = libglue_param('local_table'); + + $local_dbh = libglue_sess_db('local'); + $sql = "DELETE FROM $local_table WHERE $local_sid = '$id' LIMIT 1"; + $result = db_query($sql, $local_dbh); + + // It is very important we destroy our current session cookie, + // because if we don't, a person won't be able to log in again + // without closing their browser - SSO doesn't respect + // + // Code from http://php.oregonstate.edu/manual/en/function.session-destroy.php, + // Written by powerlord@spamless.vgmusic.com, 18-Nov-2002 08:41 + // + $cookie = session_get_cookie_params(); + if ((empty($cookie['domain'])) && (empty($cookie['secure'])) ) + { + setcookie(session_name(), '', time()-3600, $cookie['path']); + } elseif (empty($CookieInfo['secure'])) { + setcookie(session_name(), '', time()-3600, $cookie['path'], $cookie['domain']); + } else { + setcookie(session_name(), '', time()-3600, $cookie['path'], $cookie['domain'], $cookie['secure']); + } + // end powerloard + + unset($_SESSION); + unset($_COOKIE[session_name()]); + + return TRUE; +} + +function logout($id=null) +{ + libglue_sess_destroy($id); + $login_page = libglue_param('login_page'); + header("Location: $login_page"); + die(); + return true; //because why not? +} + + +// +// Register all our cool session handling functions +// +session_set_save_handler( + "sess_open", + "sess_close", + "libglue_local_check", + "sess_write", + "libglue_sess_destroy", + "sess_gc"); + +?> -- cgit