Documentation TYPO3 par Ameos |
00001 <?php 00002 /*************************************************************** 00003 * Copyright notice 00004 * 00005 * (c) 1999-2004 Kasper Skaarhoj (kasperYYYY@typo3.com) 00006 * All rights reserved 00007 * 00008 * This script is part of the TYPO3 project. The TYPO3 project is 00009 * free software; you can redistribute it and/or modify 00010 * it under the terms of the GNU General Public License as published by 00011 * the Free Software Foundation; either version 2 of the License, or 00012 * (at your option) any later version. 00013 * 00014 * The GNU General Public License can be found at 00015 * http://www.gnu.org/copyleft/gpl.html. 00016 * A copy is found in the textfile GPL.txt and important notices to the license 00017 * from the author is found in LICENSE.txt distributed with these scripts. 00018 * 00019 * 00020 * This script is distributed in the hope that it will be useful, 00021 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00022 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00023 * GNU General Public License for more details. 00024 * 00025 * This copyright notice MUST APPEAR in all copies of the script! 00026 ***************************************************************/ 00089 class t3lib_userAuth { 00090 var $global_database = ''; // Which global database to connect to 00091 var $session_table = ''; // Table to use for session data. 00092 var $name = ''; // Session/Cookie name 00093 var $get_name = ''; // Session/GET-var name 00094 00095 var $user_table = ''; // Table in database with userdata 00096 var $username_column = ''; // Column for login-name 00097 var $userident_column = ''; // Column for password 00098 var $userid_column = ''; // Column for user-id 00099 var $lastLogin_column = ''; 00100 00101 var $enablecolumns = Array ( 00102 'rootLevel' => '', // Boolean: If true, 'AND pid=0' will be a part of the query... 00103 'disabled' => '', 00104 'starttime' => '', 00105 'endtime' => '', 00106 'deleted' => '' 00107 ); 00108 00109 var $formfield_uname = ''; // formfield with login-name 00110 var $formfield_uident = ''; // formfield with password 00111 var $formfield_chalvalue = ''; // formfield with a unique value which is used to encrypt the password and username 00112 var $formfield_status = ''; // formfield with status: *'login', 'logout'. If empty login is not verified. 00113 var $security_level = ''; // sets the level of security. *'normal' = clear-text. 'challenged' = hashed password/username from form in $formfield_uident. 'superchallenged' = hashed password hashed again with username. 00114 00115 var $auth_include = ''; // this is the name of the include-file containing the login form. If not set, login CAN be anonymous. If set login IS needed. 00116 00117 var $auth_timeout_field = 0; // if > 0 : session-timeout in seconds. if string: The string is fieldname from the usertable where the timeout can be found. 00118 var $lifetime = 0; // 0 = Session-cookies. If session-cookies, the browser will stop session when the browser is closed. Else it keeps the session for $lifetime seconds. 00119 var $gc_time = 24; // GarbageCollection. Purge all session data older than $gc_time hours. 00120 var $gc_probability = 1; // Possibility (in percent) for GarbageCollection to be run. 00121 var $writeStdLog = 0; // Decides if the writelog() function is called at login and logout 00122 var $writeAttemptLog = 0; // If the writelog() functions is called if a login-attempt has be tried without success 00123 var $sendNoCacheHeaders = 1; // If this is set, headers is sent to assure, caching is NOT done 00124 var $getFallBack = 0; // If this is set, authentication is also accepted by the $_GET. Notice that the identification is NOT 128bit MD5 hash but reduced. This is done in order to minimize the size for mobile-devices, such as WAP-phones 00125 var $hash_length = 32; // The ident-hash is normally 32 characters and should be! But if you are making sites for WAP-devices og other lowbandwidth stuff, you may shorten the length. Never let this value drop below 6. A length of 6 would give you more than 16 mio possibilities. 00126 var $getMethodEnabled = 0; // Setting this flag true lets user-authetication happen from GET_VARS if POST_VARS are not set. Thus you may supply username/password from the URL. 00127 var $lockIP = 4; // If set, will lock the session to the users IP address (all four numbers. Reducing to 1-3 means that only first, second or third part of the IP address is used). 00128 var $lockHashKeyWords = 'useragent'; // Keyword list (commalist with no spaces!): "useragent". Each keyword indicates some information that can be included in a integer hash made to lock down usersessions. 00129 00130 var $warningEmail = ''; // warning -emailaddress: 00131 var $warningPeriod = 3600; // Period back in time (in seconds) in which number of failed logins are collected 00132 var $warningMax = 3; // The maximum accepted number of warnings before an email is sent 00133 var $checkPid=1; // If set, the user-record must $checkPid_value as pid 00134 var $checkPid_value=0; // The pid, the user-record must have as page-id 00135 00136 // Internals 00137 var $id; // Internal: Will contain session_id (MD5-hash) 00138 var $cookieId; // Internal: Will contain the session_id gotten from cookie or GET method. This is used in statistics as a reliable cookie (one which is known to come from $_COOKIE). 00139 var $loginSessionStarted = 0; // Will be set to 1 if the login session is actually written during auth-check. 00140 00141 var $user; // Internal: Will contain user- AND session-data from database (joined tables) 00142 var $get_URL_ID = ''; // Internal: Will will be set to the url--ready (eg. '&login=ab7ef8d...') GET-auth-var if getFallBack is true. Should be inserted in links! 00143 00144 var $forceSetCookie=0; // Will force the session cookie to be set everytime (liftime must be 0) 00145 var $dontSetCookie=0; // Will prevent the setting of the session cookie (takes precedence over forceSetCookie) 00146 00147 00159 function start() { 00160 00161 // Init vars. 00162 $mode=''; 00163 $new_id = false; // Default: not a new session 00164 $id = isset($_COOKIE[$this->name]) ? stripslashes($_COOKIE[$this->name]) : ''; // $id is set to ses_id if cookie is present. Else set to false, which will start a new session 00165 $this->hash_length = t3lib_div::intInRange($this->hash_length,6,32); 00166 00167 // If fallback to get mode.... 00168 if (!$id && $this->getFallBack && $this->get_name) { 00169 $id = isset($_GET[$this->get_name]) ? t3lib_div::_GET($this->get_name) : ''; 00170 if (strlen($id)!=$this->hash_length) $id=''; 00171 $mode='get'; 00172 } 00173 $this->cookieId = $id; 00174 00175 if (!$id) { // If new session... 00176 $id = substr(md5(uniqid('')),0,$this->hash_length); // New random session-$id is made 00177 $new_id = true; // New session 00178 } 00179 // Internal var 'id' is set 00180 $this->id = $id; 00181 if ($mode=='get' && $this->getFallBack && $this->get_name) { // If fallback to get mode.... 00182 $this->get_URL_ID = '&'.$this->get_name.'='.$id; 00183 } 00184 $this->user = ''; // Make certain that NO user is set initially 00185 00186 // Setting cookies 00187 if (($new_id || $this->forceSetCookie) && $this->lifetime==0 ) { // If new session and the cookie is a sessioncookie, we need to set it only once! 00188 if (!$this->dontSetCookie) SetCookie($this->name, $id, 0, '/'); // Cookie is set 00189 } 00190 if ($this->lifetime > 0) { // If it is NOT a session-cookie, we need to refresh it. 00191 if (!$this->dontSetCookie) SetCookie($this->name, $id, time()+$this->lifetime, '/'); 00192 } 00193 00194 // Check to see if anyone has submitted login-information and if so register the user with the session. $this->user[uid] may be used to write log... 00195 if ($this->formfield_status) { 00196 $this->check_authentication(); 00197 } 00198 unset($this->user); // Make certain that NO user is set initially. ->check_authentication may have set a session-record which will provide us with a user record in the next section: 00199 00200 00201 // The session_id is used to find user in the database. Two tables are joined: The session-table with user_id of the session and the usertable with its primary key 00202 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery( 00203 '*', 00204 $this->session_table.','.$this->user_table, 00205 $this->session_table.'.ses_id = "'.$GLOBALS['TYPO3_DB']->quoteStr($this->id, $this->session_table).'" 00206 AND '.$this->session_table.'.ses_name = "'.$GLOBALS['TYPO3_DB']->quoteStr($this->name, $this->session_table).'" 00207 AND '.$this->session_table.'.ses_userid = '.$this->user_table.'.'.$this->userid_column.' 00208 '.$this->ipLockClause().' 00209 '.$this->hashLockClause().' 00210 '.$this->user_where_clause() 00211 ); 00212 00213 if ($this->user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres)) { 00214 // A user was found 00215 if (is_string($this->auth_timeout_field)) { 00216 $timeout = intval($this->user[$this->auth_timeout_field]); // Get timeout-time from usertable 00217 } else { 00218 $timeout = intval($this->auth_timeout_field); // Get timeout from object 00219 } 00220 // If timeout > 0 (true) and currenttime has not exceeded the latest sessions-time plus the timeout in seconds then accept user 00221 // Option later on: We could check that last update was at least x seconds ago in order not to update twice in a row if one script redirects to another... 00222 if ($timeout>0 && ($GLOBALS['EXEC_TIME'] < ($this->user['ses_tstamp']+$timeout))) { 00223 $GLOBALS['TYPO3_DB']->exec_UPDATEquery( 00224 $this->session_table, 00225 'ses_id="'.$GLOBALS['TYPO3_DB']->quoteStr($this->id, $this->session_table).'" 00226 AND ses_name="'.$GLOBALS['TYPO3_DB']->quoteStr($this->name, $this->session_table).'"', 00227 array('ses_tstamp' => $GLOBALS['EXEC_TIME']) 00228 ); 00229 $this->user['ses_tstamp'] = $GLOBALS['EXEC_TIME']; // Make sure that the timestamp is also updated in the array 00230 } else { 00231 $this->user = ''; 00232 $this->logoff(); // delete any user set... 00233 } 00234 } else { 00235 $this->logoff(); // delete any user set... 00236 } 00237 00238 $this->redirect(); // If any redirection (inclusion of file) then it will happen in this function 00239 00240 // Set all posible headers that could ensure that the script is not cached on the client-side 00241 if ($this->sendNoCacheHeaders) { 00242 header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); 00243 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); 00244 header('Expires: 0'); 00245 header('Cache-Control: no-cache, must-revalidate'); 00246 header('Pragma: no-cache'); 00247 } 00248 00249 // If we're lucky we'll get to clean up old sessions.... 00250 if ((rand()%100) <= $this->gc_probability) { 00251 $this->gc(); 00252 } 00253 } 00254 00261 function check_authentication() { 00262 00263 // The values fetched from input variables here are supposed to already BE slashed... 00264 if ($this->getMethodEnabled) { 00265 $F_status = t3lib_div::_GP($this->formfield_status); 00266 $F_uname = t3lib_div::_GP($this->formfield_uname); 00267 $F_uident = t3lib_div::_GP($this->formfield_uident); 00268 $F_chalvalue = t3lib_div::_GP($this->formfield_chalvalue); 00269 } else { 00270 $F_status = t3lib_div::_POST($this->formfield_status); 00271 $F_uname = t3lib_div::_POST($this->formfield_uname); 00272 $F_uident = t3lib_div::_POST($this->formfield_uident); 00273 $F_chalvalue = t3lib_div::_POST($this->formfield_chalvalue); 00274 } 00275 00276 switch ($F_status) { 00277 case 'login': 00278 $refInfo=parse_url(t3lib_div::getIndpEnv('HTTP_REFERER')); 00279 $httpHost = t3lib_div::getIndpEnv('TYPO3_HOST_ONLY'); 00280 if (!$this->getMethodEnabled && ($httpHost!=$refInfo['host'] && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer'])) { 00281 die('Error: This host address ("'.$httpHost.'") and the referer host ("'.$refInfo['host'].'") mismatches!<br /> 00282 It\'s possible that the environment variable HTTP_REFERER is not passed to the script because of a proxy.<br /> 00283 The site administrator can disable this check in the "All Configuration" section of the Install Tool (flag: TYPO3_CONF_VARS[SYS][doNotCheckReferer]).'); 00284 } 00285 if ($F_uident && $F_uname) { 00286 00287 // Reset this flag 00288 $loginFailure=0; 00289 00290 // delete old user session if any 00291 $this->logoff(); 00292 00293 // Look up the new user by the username: 00294 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery( 00295 '*', 00296 $this->user_table, 00297 ($this->checkPid ? 'pid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->checkPid_value).') AND ' : ''). 00298 $this->username_column.'="'.$GLOBALS['TYPO3_DB']->quoteStr($F_uname, $this->user_table).'" '. 00299 $this->user_where_clause() 00300 ); 00301 00302 // Enter, if a user was found: 00303 if ($tempuser = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres)) { 00304 // Internal user record set (temporarily) 00305 $this->user = $tempuser; 00306 00307 // Default: not OK - will be set true if password matches in the comparison hereafter 00308 $OK = false; 00309 00310 // check the password 00311 switch ($this->security_level) { 00312 case 'superchallenged': // If superchallenged the password in the database ($tempuser[$this->userident_column]) must be a md5-hash of the original password. 00313 case 'challenged': 00314 if (!strcmp($F_uident,md5($tempuser[$this->username_column].':'.$tempuser[$this->userident_column].':'.$F_chalvalue))) { 00315 $OK = true; 00316 }; 00317 break; 00318 default: // normal 00319 if (!strcmp($F_uident,$tempuser[$this->userident_column])) { 00320 $OK = true; 00321 }; 00322 break; 00323 } 00324 00325 // Write session-record in case user was verified OK 00326 if ($OK) { 00327 // Checking the domain (lockToDomain) 00328 if ($this->user['lockToDomain'] && $this->user['lockToDomain']!=t3lib_div::getIndpEnv('HTTP_HOST')) { 00329 // Lock domain didn't match, so error: 00330 if ($this->writeAttemptLog) { 00331 $this->writelog(255,3,3,1, 00332 "Login-attempt from %s (%s), username '%s', locked domain '%s' did not match '%s'!", 00333 Array(t3lib_div::getIndpEnv('REMOTE_ADDR'),t3lib_div::getIndpEnv('REMOTE_HOST'),$F_uname,$this->user['lockToDomain'],t3lib_div::getIndpEnv('HTTP_HOST'))); 00334 } 00335 $loginFailure=1; 00336 } else { 00337 // The loginsession is started. 00338 $this->loginSessionStarted = 1; 00339 00340 // Inserting session record: 00341 $insertFields = array( 00342 'ses_id' => $this->id, 00343 'ses_name' => $this->name, 00344 'ses_iplock' => $this->user['disableIPlock'] ? '[DISABLED]' : $this->ipLockClause_remoteIPNumber($this->lockIP), 00345 'ses_hashlock' => $this->hashLockClause_getHashInt(), 00346 'ses_userid' => $tempuser[$this->userid_column], 00347 'ses_tstamp' => $GLOBALS['EXEC_TIME'] 00348 ); 00349 $GLOBALS['TYPO3_DB']->exec_INSERTquery($this->session_table, $insertFields); 00350 00351 // Updating column carrying information about last login. 00352 if ($this->lastLogin_column) { 00353 $GLOBALS['TYPO3_DB']->exec_UPDATEquery( 00354 $this->user_table, 00355 $this->userid_column.'="'.$GLOBALS['TYPO3_DB']->quoteStr($tempuser[$this->userid_column], $this->user_table).'"', 00356 array($this->lastLogin_column => $GLOBALS['EXEC_TIME']) 00357 ); 00358 } 00359 // User logged in - write that to the log! 00360 if ($this->writeStdLog) { 00361 $this->writelog(255,1,0,1, 00362 'User %s logged in from %s (%s)', 00363 Array($this->user['username'],t3lib_div::getIndpEnv('REMOTE_ADDR'),t3lib_div::getIndpEnv('REMOTE_HOST'))); 00364 } 00365 } 00366 } else { 00367 // Failed login attempt (wrong password) - write that to the log! 00368 if ($this->writeAttemptLog) { 00369 $this->writelog(255,3,3,1, 00370 "Login-attempt from %s (%s), username '%s', password not accepted!", 00371 Array(t3lib_div::getIndpEnv('REMOTE_ADDR'),t3lib_div::getIndpEnv('REMOTE_HOST'),$F_uname)); 00372 } 00373 $loginFailure=1; 00374 } 00375 // Make sure to clear the user again!! 00376 unset($this->user); 00377 } else { 00378 // Failed login attempt (no username found) 00379 if ($this->writeAttemptLog) { 00380 $this->writelog(255,3,3,2, 00381 "Login-attempt from %s (%s), username '%s' not found!!", 00382 Array(t3lib_div::getIndpEnv('REMOTE_ADDR'),t3lib_div::getIndpEnv('REMOTE_HOST'),$F_uname)); // Logout written to log 00383 } 00384 $loginFailure=1; 00385 } 00386 00387 // If there were a login failure, check to see if a warning email should be sent: 00388 if ($loginFailure) { 00389 $this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax); 00390 } 00391 } 00392 00393 // Return "login" - since this was the $F_status 00394 return 'login'; 00395 break; 00396 case 'logout': 00397 // Just logout: 00398 if ($this->writeStdLog) $this->writelog(255,2,0,2,'User %s logged out',Array($this->user['username'])); // Logout written to log 00399 $this->logoff(); 00400 00401 // Return "logout" - since this was the $F_status 00402 return 'logout'; 00403 break; 00404 } 00405 } 00406 00413 function redirect() { 00414 if (!$this->userid && $this->auth_url) { // if no userid AND an include-document for login is given 00415 include ($this->auth_include); 00416 exit; 00417 } 00418 } 00419 00426 function logoff() { 00427 $GLOBALS['TYPO3_DB']->exec_DELETEquery( 00428 $this->session_table, 00429 'ses_id = "'.$GLOBALS['TYPO3_DB']->quoteStr($this->id, $this->session_table).'" 00430 AND ses_name = "'.$GLOBALS['TYPO3_DB']->quoteStr($this->name, $this->session_table).'"' 00431 ); 00432 $this->user = ""; 00433 } 00434 00441 function gc() { 00442 $GLOBALS['TYPO3_DB']->exec_DELETEquery( 00443 $this->session_table, 00444 'ses_tstamp < '.intval(time()-($this->gc_time*60*60)).' 00445 AND ses_name = "'.$GLOBALS['TYPO3_DB']->quoteStr($this->name, $this->session_table).'"' 00446 ); 00447 } 00448 00455 function user_where_clause() { 00456 return (($this->enablecolumns['rootLevel']) ? 'AND '.$this->user_table.'.pid=0 ' : ''). 00457 (($this->enablecolumns['disabled']) ? ' AND NOT '.$this->user_table.'.'.$this->enablecolumns['disabled'] : ''). 00458 (($this->enablecolumns['deleted']) ? ' AND NOT '.$this->user_table.'.'.$this->enablecolumns['deleted'] : ''). 00459 (($this->enablecolumns['starttime']) ? ' AND ('.$this->user_table.'.'.$this->enablecolumns['starttime'].'<='.time().')' : ''). 00460 (($this->enablecolumns['endtime']) ? ' AND ('.$this->user_table.'.'.$this->enablecolumns['endtime'].'=0 OR '.$this->user_table.'.'.$this->enablecolumns['endtime'].'>'.time().')' : ''); 00461 } 00462 00469 function ipLockClause() { 00470 if ($this->lockIP) { 00471 $wherePart = 'AND ( 00472 '.$this->session_table.'.ses_iplock="'.$GLOBALS['TYPO3_DB']->quoteStr($this->ipLockClause_remoteIPNumber($this->lockIP),$this->session_table).'" 00473 OR '.$this->session_table.'.ses_iplock="[DISABLED]" 00474 )'; 00475 return $wherePart; 00476 } 00477 } 00478 00487 function ipLockClause_remoteIPNumber($parts) { 00488 $IP = t3lib_div::getIndpEnv('REMOTE_ADDR'); 00489 00490 if ($parts>=4) { 00491 return $IP; 00492 } else { 00493 $parts = t3lib_div::intInRange($parts,1,3); 00494 $IPparts = explode('.',$IP); 00495 for($a=4;$a>$parts;$a--) { 00496 unset($IPparts[$a-1]); 00497 } 00498 return implode('.',$IPparts); 00499 } 00500 } 00501 00508 function hashLockClause() { 00509 $wherePart = 'AND '.$this->session_table.'.ses_hashlock='.intval($this->hashLockClause_getHashInt()); 00510 return $wherePart; 00511 } 00512 00519 function hashLockClause_getHashInt() { 00520 $hashStr = ''; 00521 00522 if (t3lib_div::inList($this->lockHashKeyWords,'useragent')) $hashStr.=':'.t3lib_div::getIndpEnv('HTTP_USER_AGENT'); 00523 00524 return t3lib_div::md5int($hashStr); 00525 } 00526 00535 function writeUC($variable='') { 00536 if (is_array($this->user) && $this->user['uid']) { 00537 if (!is_array($variable)) { $variable = $this->uc; } 00538 00539 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->user_table, 'uid='.intval($this->user['uid']), array('uc' => serialize($variable))); 00540 } 00541 } 00542 00558 function writelog($type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid) { 00559 } 00560 00567 function checkLogFailures() { 00568 } 00569 00576 function unpack_uc($theUC='') { 00577 if (!$theUC) $theUC=unserialize($this->user['uc']); 00578 if (is_array($theUC)) { 00579 $this->uc=$theUC; 00580 } 00581 } 00582 00592 function pushModuleData($module,$data,$noSave=0) { 00593 $this->uc['moduleData'][$module] = $data; 00594 $this->uc['moduleSessionID'][$module] = $this->id; 00595 if (!$noSave) $this->writeUC(); 00596 } 00597 00605 function getModuleData($module,$type='') { 00606 if ($type!='ses' || $this->uc['moduleSessionID'][$module]==$this->id) { 00607 return $this->uc['moduleData'][$module]; 00608 } 00609 } 00610 00618 function getSessionData($key) { 00619 $sesDat = unserialize($this->user['ses_data']); 00620 return $sesDat[$key]; 00621 } 00622 00631 function setAndSaveSessionData($key,$data) { 00632 $sesDat = unserialize($this->user['ses_data']); 00633 $sesDat[$key] = $data; 00634 $this->user['ses_data'] = serialize($sesDat); 00635 00636 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->session_table, 'ses_id="'.$GLOBALS['TYPO3_DB']->quoteStr($this->user['ses_id'], $this->session_table).'"', array('ses_data' => $this->user['ses_data'])); 00637 } 00638 00650 function setBeUserByUid($uid) { 00651 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'uid="'.intval($uid).'" '.$this->user_where_clause()); 00652 $this->user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres); 00653 } 00654 00663 function setBeUserByName($name) { 00664 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'username="'.$GLOBALS['TYPO3_DB']->quoteStr($name, $this->user_table).'" '.$this->user_where_clause()); 00665 $this->user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres); 00666 } 00667 } 00668 00669 00670 00671 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauth.php']) { 00672 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauth.php']); 00673 } 00674 ?>