Fixed #13204: Flash can now use the session veriCode in the FE as well (Thanks to...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_userauth.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2009 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains a base class for authentication of users in TYPO3, both frontend and backend.
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
34 * @author René Fritz <r.fritz@colorcube.de>
35 */
36 /**
37 * [CLASS/FUNCTION INDEX of SCRIPT]
38 *
39 *
40 *
41 * 111: class t3lib_userAuth
42 * 195: function start()
43 * 329: function checkAuthentication()
44 *
45 * SECTION: User Sessions
46 * 569: function createUserSession ($tempuser)
47 * 606: function fetchUserSession()
48 * 657: function logoff()
49 *
50 * SECTION: SQL Functions
51 * 713: function user_where_clause()
52 * 727: function ipLockClause()
53 * 745: function ipLockClause_remoteIPNumber($parts)
54 * 766: function hashLockClause()
55 * 777: function hashLockClause_getHashInt()
56 *
57 * SECTION: Session and Configuration Handling
58 * 809: function writeUC($variable='')
59 * 824: function unpack_uc($theUC='')
60 * 840: function pushModuleData($module,$data,$noSave=0)
61 * 853: function getModuleData($module,$type='')
62 * 866: function getSessionData($key)
63 * 879: function setAndSaveSessionData($key,$data)
64 *
65 * SECTION: Misc
66 * 912: function getLoginFormData()
67 * 939: function processLoginData($loginData, $security_level='')
68 * 981: function getAuthInfoArray()
69 * 1011: function compareUident($user, $loginData, $security_level='')
70 * 1050: function gc()
71 * 1064: function redirect()
72 * 1086: function writelog($type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid)
73 * 1095: function checkLogFailures()
74 * 1108: function setBeUserByUid($uid)
75 * 1120: function setBeUserByName($name)
76 * 1131: function getRawUserByUid($uid)
77 * 1149: function getRawUserByName($name)
78 *
79 * SECTION: Create/update user - EXPERIMENTAL
80 * 1188: function fetchUserRecord($dbUser, $username, $extraWhere='' )
81 *
82 * TOTAL FUNCTIONS: 29
83 * (This index is automatically created/updated by the extension "extdeveval")
84 *
85 */
86
87
88 require_once(t3lib_extMgm::extPath('sv').'class.tx_sv_authbase.php');
89
90
91
92
93
94
95
96
97
98 /**
99 * Authentication of users in TYPO3
100 *
101 * This class is used to authenticate a login user.
102 * The class is used by both the frontend and backend. In both cases this class is a parent class to beuserauth and feuserauth
103 *
104 * See Inside TYPO3 for more information about the API of the class and internal variables.
105 *
106 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
107 * @author René Fritz <r.fritz@colorcube.de>
108 * @package TYPO3
109 * @subpackage t3lib
110 */
111 class t3lib_userAuth {
112 var $global_database = ''; // Which global database to connect to
113 var $session_table = ''; // Table to use for session data.
114 var $name = ''; // Session/Cookie name
115 var $get_name = ''; // Session/GET-var name
116
117 var $user_table = ''; // Table in database with userdata
118 var $username_column = ''; // Column for login-name
119 var $userident_column = ''; // Column for password
120 var $userid_column = ''; // Column for user-id
121 var $lastLogin_column = '';
122
123 var $enablecolumns = Array (
124 'rootLevel' => '', // Boolean: If true, 'AND pid=0' will be a part of the query...
125 'disabled' => '',
126 'starttime' => '',
127 'endtime' => '',
128 'deleted' => ''
129 );
130
131 var $formfield_uname = ''; // formfield with login-name
132 var $formfield_uident = ''; // formfield with password
133 var $formfield_chalvalue = ''; // formfield with a unique value which is used to encrypt the password and username
134 var $formfield_status = ''; // formfield with status: *'login', 'logout'. If empty login is not verified.
135 var $security_level = 'normal'; // sets the level of security. *'normal' = clear-text. 'challenged' = hashed password/username from form in $formfield_uident. 'superchallenged' = hashed password hashed again with username.
136
137 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.
138
139 var $auth_timeout_field = 0; // Server session lifetime. If > 0: session-timeout in seconds. If false or <0: no timeout. If string: The string is a fieldname from the usertable where the timeout can be found.
140 var $lifetime = 0; // Client session lifetime. 0 = Session-cookies. If session-cookies, the browser will stop the session when the browser is closed. Otherwise this specifies the lifetime of a cookie that keeps the session.
141 var $gc_time = 0; // GarbageCollection. Purge all server session data older than $gc_time seconds. 0 = default to $this->timeout or use 86400 seconds (1 day) if $this->lifetime is 0
142 var $gc_probability = 1; // Possibility (in percent) for GarbageCollection to be run.
143 var $writeStdLog = FALSE; // Decides if the writelog() function is called at login and logout
144 var $writeAttemptLog = FALSE; // If the writelog() functions is called if a login-attempt has be tried without success
145 var $sendNoCacheHeaders = TRUE; // If this is set, headers is sent to assure, caching is NOT done
146 var $getFallBack = FALSE; // 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
147 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.
148 var $getMethodEnabled = FALSE; // 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.
149 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).
150 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.
151
152 var $warningEmail = ''; // warning -emailaddress:
153 var $warningPeriod = 3600; // Period back in time (in seconds) in which number of failed logins are collected
154 var $warningMax = 3; // The maximum accepted number of warnings before an email is sent
155 var $checkPid = TRUE; // If set, the user-record must $checkPid_value as pid
156 var $checkPid_value=0; // The pid, the user-record must have as page-id
157
158 // Internals
159 var $id; // Internal: Will contain session_id (MD5-hash)
160 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).
161 var $loginFailure = FALSE; // Indicates if an authentication was started but failed
162 var $loginSessionStarted = FALSE; // Will be set to true if the login session is actually written during auth-check.
163
164 var $user; // Internal: Will contain user- AND session-data from database (joined tables)
165 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!
166
167 var $newSessionID = FALSE; // Will be set to true if a new session ID was created
168 var $forceSetCookie = FALSE; // Will force the session cookie to be set everytime (lifetime must be 0)
169 var $dontSetCookie = FALSE; // Will prevent the setting of the session cookie (takes precedence over forceSetCookie)
170 var $challengeStoredInCookie = FALSE; // If set, the challenge value will be stored in a session as well so the server can check that is was not forged.
171 var $loginType = ''; // Login type, used for services.
172
173 var $svConfig = array(); // "auth" services configuration array from $TYPO3_CONF_VARS['SVCONF']['auth']
174 var $writeDevLog = FALSE; // write messages into the devlog?
175
176
177
178
179
180
181
182
183
184 /**
185 * Starts a user session
186 * Typical configurations will:
187 * a) check if session cookie was set and if not, set one,
188 * b) check if a password/username was sent and if so, try to authenticate the user
189 * c) Lookup a session attached to a user and check timeout etc.
190 * d) Garbage collection, setting of no-cache headers.
191 * If a user is authenticated the database record of the user (array) will be set in the ->user internal variable.
192 *
193 * @return void
194 */
195 function start() {
196 global $TYPO3_CONF_VARS;
197
198 // backend or frontend login - used for auth services
199 $this->loginType = ($this->name=='fe_typo_user') ? 'FE' : 'BE';
200
201 // set level to normal if not already set
202 if (!$this->security_level) {
203 // Notice: cannot use TYPO3_MODE here because BE user can be logged in and operate inside FE!
204 $this->security_level = trim($TYPO3_CONF_VARS[$this->loginType]['loginSecurityLevel']);
205 if (!$this->security_level) {
206 $this->security_level = 'normal';
207 }
208 }
209
210 // enable dev logging if set
211 if ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['writeDevLog']) $this->writeDevLog = TRUE;
212 if ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['writeDevLog'.$this->loginType]) $this->writeDevLog = TRUE;
213 if (TYPO3_DLOG) $this->writeDevLog = TRUE;
214
215 if ($this->writeDevLog) t3lib_div::devLog('## Beginning of auth logging.', 't3lib_userAuth');
216
217 // Init vars.
218 $mode = '';
219 $this->newSessionID = FALSE;
220 // $id is set to ses_id if cookie is present. Else set to false, which will start a new session
221 $id = isset($_COOKIE[$this->name]) ? stripslashes($_COOKIE[$this->name]) : '';
222 $this->svConfig = $TYPO3_CONF_VARS['SVCONF']['auth'];
223
224 // if we have a flash client, take the ID from the GP
225 if (!$id && $GLOBALS['CLIENT']['BROWSER'] == 'flash') {
226 $id = t3lib_div::_GP($this->name);
227 }
228
229 // If fallback to get mode....
230 if (!$id && $this->getFallBack && $this->get_name) {
231 $id = isset($_GET[$this->get_name]) ? t3lib_div::_GET($this->get_name) : '';
232 if (strlen($id)!=$this->hash_length) $id='';
233 $mode='get';
234 }
235 $this->cookieId = $id;
236
237 // If new session or client tries to fix session...
238 if (!$id || !$this->isExistingSessionRecord($id)) {
239 // New random session-$id is made
240 $id = $this->createSessionId();
241 // New session
242 $this->newSessionID = TRUE;
243 }
244
245 // Internal var 'id' is set
246 $this->id = $id;
247
248 // If fallback to get mode....
249 if ($mode=='get' && $this->getFallBack && $this->get_name) {
250 $this->get_URL_ID = '&'.$this->get_name.'='.$id;
251 }
252 // Make certain that NO user is set initially
253 $this->user = '';
254
255 // 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...
256 $this->checkAuthentication();
257
258 // 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:
259 unset($this->user);
260
261 // determine whether we need to skip session update.
262 // This is used mainly for checking session timeout without
263 // refreshing the session itself while checking.
264 if (t3lib_div::_GP('skipSessionUpdate')) {
265 $skipSessionUpdate = true;
266 } else {
267 $skipSessionUpdate = false;
268 }
269
270 // re-read user session
271 $this->user = $this->fetchUserSession($skipSessionUpdate);
272
273 if ($this->writeDevLog && is_array($this->user)) t3lib_div::devLog('User session finally read: '.t3lib_div::arrayToLogString($this->user, array($this->userid_column,$this->username_column)), 't3lib_userAuth', -1);
274 if ($this->writeDevLog && !is_array($this->user)) t3lib_div::devLog('No user session found.', 't3lib_userAuth', 2);
275
276 // Setting cookies
277 if (!$this->dontSetCookie) {
278 $this->setSessionCookie();
279 }
280
281 // Hook for alternative ways of filling the $this->user array (is used by the "timtaw" extension)
282 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'])) {
283 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'] as $funcName) {
284 $_params = array(
285 'pObj' => &$this,
286 );
287 t3lib_div::callUserFunction($funcName,$_params,$this);
288 }
289 }
290
291 // If any redirection (inclusion of file) then it will happen in this function
292 $this->redirect();
293
294 // Set all posible headers that could ensure that the script is not cached on the client-side
295 if ($this->sendNoCacheHeaders) {
296 header('Expires: 0');
297 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
298 header('Cache-Control: no-cache, must-revalidate');
299 header('Pragma: no-cache');
300 }
301
302 // Set $this->gc_time if not explicitely specified
303 if ($this->gc_time==0) {
304 $this->gc_time = ($this->auth_timeout_field==0 ? 86400 : $this->auth_timeout_field); // Default to 1 day if $this->auth_timeout_field is 0
305 }
306
307 // If we're lucky we'll get to clean up old sessions....
308 if ((rand()%100) <= $this->gc_probability) {
309 $this->gc();
310 }
311
312 }
313
314 /**
315 * Sets the session cookie for the current disposal.
316 *
317 * @return void
318 */
319 protected function setSessionCookie() {
320 $isSetSessionCookie = $this->isSetSessionCookie();
321 $isRefreshTimeBasedCookie = $this->isRefreshTimeBasedCookie();
322
323 if ($isSetSessionCookie || $isRefreshTimeBasedCookie) {
324 $settings = $GLOBALS['TYPO3_CONF_VARS']['SYS'];
325
326 // Get the domain to be used for the cookie (if any):
327 $cookieDomain = $this->getCookieDomain();
328 // If no cookie domain is set, use the base path:
329 $cookiePath = ($cookieDomain ? '/' : t3lib_div::getIndpEnv('TYPO3_SITE_PATH'));
330 // If the cookie lifetime is set, use it:
331 $cookieExpire = ($isRefreshTimeBasedCookie ? $GLOBALS['EXEC_TIME'] + $this->lifetime : 0);
332 // Use the secure option when the current request is served by a secure connection:
333 $cookieSecure = (bool)$settings['cookieSecure'] && t3lib_div::getIndpEnv('TYPO3_SSL');
334 // Deliver cookies only via HTTP and prevent possible XSS by JavaScript:
335 $cookieHttpOnly = (bool)$settings['cookieHttpOnly'];
336
337 // Do not set cookie if cookieSecure is set to "1" (force HTTPS) and no secure channel is used:
338 if ((int)$settings['cookieSecure'] !== 1 || t3lib_div::getIndpEnv('TYPO3_SSL')) {
339 setcookie(
340 $this->name,
341 $this->id,
342 $cookieExpire,
343 $cookiePath,
344 $cookieDomain,
345 $cookieSecure,
346 $cookieHttpOnly
347 );
348 } else {
349 throw new t3lib_exception(
350 'Cookie was not set since HTTPS was forced in $TYPO3_CONF_VARS[SYS][cookieSecure].',
351 1254325546
352 );
353 }
354
355 if ($this->writeDevLog) {
356 $devLogMessage = ($isRefreshTimeBasedCookie ? 'Updated Cookie: ' : 'Set Cookie: ') . $this->id;
357 t3lib_div::devLog($devLogMessage . ($cookieDomain ? ', '.$cookieDomain : ''), 't3lib_userAuth');
358 }
359 }
360 }
361
362 /**
363 * Gets the domain to be used on setting cookies.
364 * The information is taken from the value in $TYPO3_CONF_VARS[SYS][cookieDomain].
365 *
366 * @return string The domain to be used on setting cookies
367 */
368 protected function getCookieDomain() {
369 $result = '';
370 $cookieDomain = $GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieDomain'];
371
372 if ($cookieDomain) {
373 if ($cookieDomain{0} == '/') {
374 $matchCnt = @preg_match($cookieDomain, t3lib_div::getIndpEnv('TYPO3_HOST_ONLY'), $match);
375 if ($matchCnt === FALSE) {
376 t3lib_div::sysLog('The regular expression of $TYPO3_CONF_VARS[SYS][cookieDomain] contains errors. The session is not shared across sub-domains.', 'Core', 3);
377 } elseif ($matchCnt) {
378 $result = $match[0];
379 }
380 } else {
381 $result = $cookieDomain;
382 }
383 }
384
385 return $result;
386 }
387
388 /**
389 * Determine whether a session cookie needs to be set (lifetime=0)
390 *
391 * @return boolean
392 * @internal
393 */
394 function isSetSessionCookie() {
395 return ($this->newSessionID || $this->forceSetCookie) && $this->lifetime==0;
396 }
397
398 /**
399 * Determine whether a non-session cookie needs to be set (lifetime>0)
400 *
401 * @return boolean
402 * @internal
403 */
404 function isRefreshTimeBasedCookie() {
405 return $this->lifetime > 0;
406 }
407
408 /**
409 * Checks if a submission of username and password is present or use other authentication by auth services
410 *
411 * @return void
412 * @internal
413 */
414 function checkAuthentication() {
415
416 // No user for now - will be searched by service below
417 $tempuserArr = array();
418 $tempuser = FALSE;
419
420 // User is not authenticated by default
421 $authenticated = FALSE;
422
423 // User want to login with passed login data (name/password)
424 $activeLogin = FALSE;
425
426 // Indicates if an active authentication failed (not auto login)
427 $this->loginFailure = FALSE;
428
429 if ($this->writeDevLog) t3lib_div::devLog('Login type: '.$this->loginType, 't3lib_userAuth');
430
431 // The info array provide additional information for auth services
432 $authInfo = $this->getAuthInfoArray();
433
434 // Get Login/Logout data submitted by a form or params
435 $loginData = $this->getLoginFormData();
436
437 if ($this->writeDevLog) t3lib_div::devLog('Login data: '.t3lib_div::arrayToLogString($loginData), 't3lib_userAuth');
438
439
440 // active logout (eg. with "logout" button)
441 if ($loginData['status']=='logout') {
442 if ($this->writeStdLog) $this->writelog(255,2,0,2,'User %s logged out',Array($this->user['username'])); // Logout written to log
443 if ($this->writeDevLog) t3lib_div::devLog('User logged out. Id: '.$this->id, 't3lib_userAuth', -1);
444
445 $this->logoff();
446 }
447
448 // active login (eg. with login form)
449 if ($loginData['status']=='login') {
450 $activeLogin = TRUE;
451
452 if ($this->writeDevLog) t3lib_div::devLog('Active login (eg. with login form)', 't3lib_userAuth');
453
454 // check referer for submitted login values
455 if ($this->formfield_status && $loginData['uident'] && $loginData['uname']) {
456 $httpHost = t3lib_div::getIndpEnv('TYPO3_HOST_ONLY');
457 if (!$this->getMethodEnabled && ($httpHost!=$authInfo['refInfo']['host'] && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer'])) {
458 die('Error: This host address ("'.$httpHost.'") and the referer host ("'.$authInfo['refInfo']['host'].'") mismatches!<br />
459 It\'s possible that the environment variable HTTP_REFERER is not passed to the script because of a proxy.<br />
460 The site administrator can disable this check in the "All Configuration" section of the Install Tool (flag: TYPO3_CONF_VARS[SYS][doNotCheckReferer]).');
461 }
462
463 // delete old user session if any
464 $this->logoff();
465 }
466
467 // Refuse login for _CLI users (used by commandline scripts)
468 if ((strtoupper(substr($loginData['uname'],0,5))=='_CLI_') && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) { // although TYPO3_cliMode should never be set when using active login...
469 die('Error: You have tried to login using a CLI user. Access prohibited!');
470 }
471 }
472
473
474 // the following code makes auto-login possible (if configured). No submitted data needed
475
476 // determine whether we need to skip session update.
477 // This is used mainly for checking session timeout without
478 // refreshing the session itself while checking.
479 if (t3lib_div::_GP('skipSessionUpdate')) {
480 $skipSessionUpdate = true;
481 } else {
482 $skipSessionUpdate = false;
483 }
484
485 // re-read user session
486 $authInfo['userSession'] = $this->fetchUserSession($skipSessionUpdate);
487 $haveSession = is_array($authInfo['userSession']) ? TRUE : FALSE;
488
489 if ($this->writeDevLog) {
490 if ($haveSession) {
491 t3lib_div::devLog('User session found: '.t3lib_div::arrayToLogString($authInfo['userSession'], array($this->userid_column,$this->username_column)), 't3lib_userAuth', 0);
492 }
493 if (is_array($this->svConfig['setup'])) {
494 t3lib_div::devLog('SV setup: '.t3lib_div::arrayToLogString($this->svConfig['setup']), 't3lib_userAuth', 0);
495 }
496 }
497
498 // fetch user if ...
499 if ($activeLogin
500 || (!$haveSession && $this->svConfig['setup'][$this->loginType.'_fetchUserIfNoSession'])
501 || $this->svConfig['setup'][$this->loginType.'_alwaysFetchUser']) {
502
503 // use 'auth' service to find the user
504 // first found user will be used
505 $serviceChain = '';
506 $subType = 'getUser'.$this->loginType;
507 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
508 $serviceChain.=','.$serviceObj->getServiceKey();
509 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
510 if ($row=$serviceObj->getUser()) {
511 $tempuserArr[] = $row;
512
513 if ($this->writeDevLog) t3lib_div::devLog('User found: '.t3lib_div::arrayToLogString($row, array($this->userid_column,$this->username_column)), 't3lib_userAuth', 0);
514
515 // user found, just stop to search for more if not configured to go on
516 if(!$this->svConfig['setup'][$this->loginType.'_fetchAllUsers']) {
517 break;
518 }
519 }
520 unset($serviceObj);
521 }
522 unset($serviceObj);
523
524 if ($this->writeDevLog && $this->svConfig['setup'][$this->loginType.'_alwaysFetchUser']) t3lib_div::devLog($this->loginType.'_alwaysFetchUser option is enabled', 't3lib_userAuth');
525 if ($this->writeDevLog && $serviceChain) t3lib_div::devLog($subType.' auth services called: '.$serviceChain, 't3lib_userAuth');
526 if ($this->writeDevLog && !count($tempuserArr)) t3lib_div::devLog('No user found by services', 't3lib_userAuth');
527 if ($this->writeDevLog && count($tempuserArr)) t3lib_div::devLog(count($tempuserArr).' user records found by services', 't3lib_userAuth');
528 }
529
530
531 // If no new user was set we use the already found user session
532 if (!count($tempuserArr) && $haveSession) {
533 $tempuserArr[] = $authInfo['userSession'];
534 $tempuser = $authInfo['userSession'];
535 // User is authenticated because we found a user session
536 $authenticated = TRUE;
537
538 if ($this->writeDevLog) t3lib_div::devLog('User session used: '.t3lib_div::arrayToLogString($authInfo['userSession'], array($this->userid_column,$this->username_column)), 't3lib_userAuth');
539 }
540
541
542 // Re-auth user when 'auth'-service option is set
543 if ($this->svConfig['setup'][$this->loginType.'_alwaysAuthUser']) {
544 $authenticated = FALSE;
545 if ($this->writeDevLog) t3lib_div::devLog('alwaysAuthUser option is enabled', 't3lib_userAuth');
546 }
547
548
549 // Authenticate the user if needed
550 if (count($tempuserArr) && !$authenticated) {
551
552 foreach ($tempuserArr as $tempuser) {
553
554 // use 'auth' service to authenticate the user
555 // if one service returns FALSE then authentication failed
556 // a service might return 100 which means there's no reason to stop but the user can't be authenticated by that service
557
558 if ($this->writeDevLog) t3lib_div::devLog('Auth user: '.t3lib_div::arrayToLogString($tempuser), 't3lib_userAuth');
559
560 $serviceChain='';
561 $subType = 'authUser'.$this->loginType;
562 while (is_object($serviceObj = t3lib_div::makeInstanceService('auth', $subType, $serviceChain))) {
563 $serviceChain.=','.$serviceObj->getServiceKey();
564 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
565 if (($ret=$serviceObj->authUser($tempuser)) > 0) {
566
567 // if the service returns >=200 then no more checking is needed - useful for IP checking without password
568 if (intval($ret) >= 200) {
569 $authenticated = TRUE;
570 break;
571 } elseif (intval($ret) >= 100) {
572 // Just go on. User is still not authenticated but there's no reason to stop now.
573 } else {
574 $authenticated = TRUE;
575 }
576
577 } else {
578 $authenticated = FALSE;
579 break;
580 }
581 unset($serviceObj);
582 }
583 unset($serviceObj);
584
585 if ($this->writeDevLog && $serviceChain) t3lib_div::devLog($subType.' auth services called: '.$serviceChain, 't3lib_userAuth');
586
587 if ($authenticated) {
588 // leave foreach() because a user is authenticated
589 break;
590 }
591 }
592 }
593
594 // If user is authenticated a valid user is in $tempuser
595 if ($authenticated) {
596 // reset failure flag
597 $this->loginFailure = FALSE;
598
599 // Insert session record if needed:
600 if (!($haveSession && (
601 $tempuser['ses_id']==$this->id || // check if the tempuser has the current session id
602 $tempuser['uid']==$authInfo['userSession']['ses_userid'] // check if the tempuser has the uid of the fetched session user
603 ))) {
604 $this->createUserSession($tempuser);
605
606 // The login session is started.
607 $this->loginSessionStarted = TRUE;
608 }
609
610 // User logged in - write that to the log!
611 if ($this->writeStdLog && $activeLogin) {
612 $this->writelog(255,1,0,1,
613 'User %s logged in from %s (%s)',
614 Array($tempuser[$this->username_column], t3lib_div::getIndpEnv('REMOTE_ADDR'), t3lib_div::getIndpEnv('REMOTE_HOST')),
615 '','','',-1,'',$tempuser['uid']
616 );
617 }
618
619 if ($this->writeDevLog && $activeLogin) t3lib_div::devLog('User '.$tempuser[$this->username_column].' logged in from '.t3lib_div::getIndpEnv('REMOTE_ADDR').' ('.t3lib_div::getIndpEnv('REMOTE_HOST').')', 't3lib_userAuth', -1);
620 if ($this->writeDevLog && !$activeLogin) t3lib_div::devLog('User '.$tempuser[$this->username_column].' authenticated from '.t3lib_div::getIndpEnv('REMOTE_ADDR').' ('.t3lib_div::getIndpEnv('REMOTE_HOST').')', 't3lib_userAuth', -1);
621
622 if($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] == 3 && $this->user_table == 'be_users') {
623 $requestStr = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'), strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL').TYPO3_mainDir));
624 $backendScript = t3lib_BEfunc::getBackendScript();
625 if($requestStr == $backendScript && t3lib_div::getIndpEnv('TYPO3_SSL')) {
626 list(,$url) = explode('://',t3lib_div::getIndpEnv('TYPO3_SITE_URL'),2);
627 list($server,$address) = explode('/',$url,2);
628 if (intval($TYPO3_CONF_VARS['BE']['lockSSLPort'])) {
629 $sslPortSuffix = ':'.intval($TYPO3_CONF_VARS['BE']['lockSSLPort']);
630 $server = str_replace($sslPortSuffix,'',$server); // strip port from server
631 }
632 t3lib_utility_Http::redirect('http://' . $server . '/' . $address . TYPO3_mainDir . $backendScript);
633 }
634 }
635
636 } elseif ($activeLogin || count($tempuserArr)) {
637 $this->loginFailure = TRUE;
638
639 if ($this->writeDevLog && !count($tempuserArr) && $activeLogin) t3lib_div::devLog('Login failed: '.t3lib_div::arrayToLogString($loginData), 't3lib_userAuth', 2);
640 if ($this->writeDevLog && count($tempuserArr)) t3lib_div::devLog('Login failed: '.t3lib_div::arrayToLogString($tempuser, array($this->userid_column,$this->username_column)), 't3lib_userAuth', 2);
641 }
642
643
644 // If there were a login failure, check to see if a warning email should be sent:
645 if ($this->loginFailure && $activeLogin) {
646 if ($this->writeDevLog) t3lib_div::devLog('Call checkLogFailures: '.t3lib_div::arrayToLogString(array('warningEmail'=>$this->warningEmail,'warningPeriod'=>$this->warningPeriod,'warningMax'=>$this->warningMax,)), 't3lib_userAuth', -1);
647
648 $this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax);
649 }
650 }
651
652 /**
653 * Creates a new session ID.
654 *
655 * @return string The new session ID
656 */
657 public function createSessionId() {
658 return substr(md5(uniqid('') . getmypid()), 0, $this->hash_length);
659 }
660
661
662
663
664
665
666
667
668
669
670
671 /*************************
672 *
673 * User Sessions
674 *
675 *************************/
676
677
678 /**
679 * Creates a user session record.
680 *
681 * @param array user data array
682 * @return void
683 */
684 function createUserSession ($tempuser) {
685
686 if ($this->writeDevLog) t3lib_div::devLog('Create session ses_id = '.$this->id, 't3lib_userAuth');
687
688 // delete session entry first
689 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
690 $this->session_table,
691 'ses_id = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
692 AND ses_name = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
693 );
694
695 // re-create session entry
696 $insertFields = $this->getNewSessionRecord($tempuser);
697 $GLOBALS['TYPO3_DB']->exec_INSERTquery($this->session_table, $insertFields);
698
699 // Updating lastLogin_column carrying information about last login.
700 if ($this->lastLogin_column) {
701 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
702 $this->user_table,
703 $this->userid_column.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($tempuser[$this->userid_column], $this->user_table),
704 array($this->lastLogin_column => $GLOBALS['EXEC_TIME'])
705 );
706 }
707 }
708
709 /**
710 * Returns a new session record for the current user for insertion into the DB.
711 * This function is mainly there as a wrapper for inheriting classes to override it.
712 *
713 * @return array user session record
714 */
715 function getNewSessionRecord($tempuser) {
716 return array(
717 'ses_id' => $this->id,
718 'ses_name' => $this->name,
719 'ses_iplock' => $tempuser['disableIPlock'] ? '[DISABLED]' : $this->ipLockClause_remoteIPNumber($this->lockIP),
720 'ses_hashlock' => $this->hashLockClause_getHashInt(),
721 'ses_userid' => $tempuser[$this->userid_column],
722 'ses_tstamp' => $GLOBALS['EXEC_TIME']
723 );
724 }
725
726 /**
727 * Read the user session from db.
728 *
729 * @return array user session data
730 */
731 function fetchUserSession($skipSessionUpdate = false) {
732
733 $user = '';
734
735 if ($this->writeDevLog) t3lib_div::devLog('Fetch session ses_id = '.$this->id, 't3lib_userAuth');
736
737 // fetch the user session from the DB
738 $dbres = $this->fetchUserSessionFromDB();
739
740 if ($dbres && $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres)) {
741 // A user was found
742 if (is_string($this->auth_timeout_field)) {
743 $timeout = intval($user[$this->auth_timeout_field]); // Get timeout-time from usertable
744 } else {
745 $timeout = intval($this->auth_timeout_field); // Get timeout from object
746 }
747 // If timeout > 0 (true) and currenttime has not exceeded the latest sessions-time plus the timeout in seconds then accept user
748 // 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...
749 if ($timeout>0 && ($GLOBALS['EXEC_TIME'] < ($user['ses_tstamp']+$timeout))) {
750 if(!$skipSessionUpdate) {
751 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
752 $this->session_table,
753 'ses_id='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
754 AND ses_name='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table),
755 array('ses_tstamp' => $GLOBALS['EXEC_TIME'])
756 );
757 $user['ses_tstamp'] = $GLOBALS['EXEC_TIME']; // Make sure that the timestamp is also updated in the array
758 }
759
760 } else {
761 $this->logoff(); // delete any user set...
762 }
763 } else {
764 $this->logoff(); // delete any user set...
765 }
766 return $user;
767 }
768
769 /**
770 * Log out current user!
771 * Removes the current session record, sets the internal ->user array to a blank string; Thereby the current user (if any) is effectively logged out!
772 *
773 * @return void
774 */
775 function logoff() {
776 if ($this->writeDevLog) t3lib_div::devLog('logoff: ses_id = '.$this->id, 't3lib_userAuth');
777
778 // Hook for pre-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
779 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'])) {
780 $_params = array();
781 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'] as $_funcRef) {
782 if ($_funcRef) {
783 t3lib_div::callUserFunction($_funcRef,$_params,$this);
784 }
785 }
786 }
787
788 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
789 $this->session_table,
790 'ses_id = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
791 AND ses_name = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
792 );
793
794 $this->user = '';
795
796 // Hook for post-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
797 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'])) {
798 $_params = array();
799 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'] as $_funcRef) {
800 if ($_funcRef) {
801 t3lib_div::callUserFunction($_funcRef,$_params,$this);
802 }
803 }
804 }
805 }
806
807 /**
808 * Determine whether there's an according session record to a given session_id
809 * in the database. Don't care if session record is still valid or not.
810 *
811 * @param integer Claimed Session ID
812 * @return boolean Returns true if a corresponding session was found in the database
813 */
814 function isExistingSessionRecord($id) {
815 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
816 'ses_id',
817 $this->session_table,
818 'ses_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($id, $this->session_table)
819 );
820 return (($count ? true : false));
821 }
822
823
824
825
826
827
828
829
830
831
832
833
834
835 /*************************
836 *
837 * SQL Functions
838 *
839 *************************/
840
841 /**
842 * The session_id is used to find user in the database.
843 * Two tables are joined: The session-table with user_id of the session and the usertable with its primary key
844 * if the client is flash (e.g. from a flash application inside TYPO3 that does a server request)
845 * then don't evaluate with the hashLockClause, as the client/browser is included in this hash
846 * and thus, the flash request would be rejected
847 *
848 * @return DB result object or false on error
849 * @access private
850 */
851 protected function fetchUserSessionFromDB() {
852
853 if ($GLOBALS['CLIENT']['BROWSER'] == 'flash') {
854 // if on the flash client, the veri code is valid, then the user session is fetched
855 // from the DB without the hashLock clause
856 if (t3lib_div::_GP('vC') == $this->veriCode()) {
857 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
858 '*',
859 $this->session_table.','.$this->user_table,
860 $this->session_table.'.ses_id = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
861 AND '.$this->session_table.'.ses_name = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table).'
862 AND '.$this->session_table.'.ses_userid = '.$this->user_table.'.'.$this->userid_column.'
863 '.$this->ipLockClause().'
864 '.$this->user_where_clause()
865 );
866 } else {
867 $dbres = false;
868 }
869 } else {
870 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
871 '*',
872 $this->session_table.','.$this->user_table,
873 $this->session_table.'.ses_id = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table).'
874 AND '.$this->session_table.'.ses_name = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table).'
875 AND '.$this->session_table.'.ses_userid = '.$this->user_table.'.'.$this->userid_column.'
876 '.$this->ipLockClause().'
877 '.$this->hashLockClause().'
878 '.$this->user_where_clause()
879 );
880 }
881 return $dbres;
882 }
883
884
885 /**
886 * This returns the where-clause needed to select the user with respect flags like deleted, hidden, starttime, endtime
887 *
888 * @return string
889 * @access private
890 */
891 function user_where_clause() {
892 return (($this->enablecolumns['rootLevel']) ? 'AND '.$this->user_table.'.pid=0 ' : '').
893 (($this->enablecolumns['disabled']) ? ' AND '.$this->user_table.'.'.$this->enablecolumns['disabled'].'=0' : '').
894 (($this->enablecolumns['deleted']) ? ' AND '.$this->user_table.'.'.$this->enablecolumns['deleted'].'=0' : '').
895 (($this->enablecolumns['starttime']) ? ' AND (' . $this->user_table . '.' . $this->enablecolumns['starttime'] . '<=' . $GLOBALS['EXEC_TIME'] . ')' : '') .
896 (($this->enablecolumns['endtime']) ? ' AND (' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '=0 OR ' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '>' . $GLOBALS['EXEC_TIME'] . ')' : '');
897 }
898
899 /**
900 * This returns the where-clause needed to lock a user to the IP address
901 *
902 * @return string
903 * @access private
904 */
905 function ipLockClause() {
906 if ($this->lockIP) {
907 $wherePart = 'AND (
908 '.$this->session_table.'.ses_iplock='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->ipLockClause_remoteIPNumber($this->lockIP),$this->session_table).'
909 OR '.$this->session_table.'.ses_iplock=\'[DISABLED]\'
910 )';
911 return $wherePart;
912 }
913 }
914
915 /**
916 * Returns the IP address to lock to.
917 * The IP address may be partial based on $parts.
918 *
919 * @param integer 1-4: Indicates how many parts of the IP address to return. 4 means all, 1 means only first number.
920 * @return string (Partial) IP address for REMOTE_ADDR
921 * @access private
922 */
923 function ipLockClause_remoteIPNumber($parts) {
924 $IP = t3lib_div::getIndpEnv('REMOTE_ADDR');
925
926 if ($parts>=4) {
927 return $IP;
928 } else {
929 $parts = t3lib_div::intInRange($parts,1,3);
930 $IPparts = explode('.',$IP);
931 for($a=4;$a>$parts;$a--) {
932 unset($IPparts[$a-1]);
933 }
934 return implode('.',$IPparts);
935 }
936 }
937
938 /**
939 * VeriCode returns 10 first chars of a md5 hash of the session cookie AND the encryptionKey from TYPO3_CONF_VARS.
940 * This code is used as an alternative verification when the JavaScript interface executes cmd's to tce_db.php from eg. MSIE 5.0 because the proper referer is not passed with this browser...
941 *
942 * @return string
943 */
944 public function veriCode() {
945 return substr(md5($this->id . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, 10);
946 }
947
948 /**
949 * This returns the where-clause needed to lock a user to a hash integer
950 *
951 * @return string
952 * @access private
953 */
954 function hashLockClause() {
955 $wherePart = 'AND '.$this->session_table.'.ses_hashlock='.intval($this->hashLockClause_getHashInt());
956 return $wherePart;
957 }
958
959 /**
960 * Creates hash integer to lock user to. Depends on configured keywords
961 *
962 * @return integer Hash integer
963 * @access private
964 */
965 function hashLockClause_getHashInt() {
966 $hashStr = '';
967
968 if (t3lib_div::inList($this->lockHashKeyWords,'useragent')) $hashStr.=':'.t3lib_div::getIndpEnv('HTTP_USER_AGENT');
969
970 return t3lib_div::md5int($hashStr);
971 }
972
973
974
975
976
977
978
979
980
981
982
983 /*************************
984 *
985 * Session and Configuration Handling
986 *
987 *************************/
988
989 /**
990 * This writes $variable to the user-record. This is a way of providing session-data.
991 * You can fetch the data again through $this->uc in this class!
992 * If $variable is not an array, $this->uc is saved!
993 *
994 * @param array An array you want to store for the user as session data. If $variable is not supplied (is blank string), the internal variable, ->uc, is stored by default
995 * @return void
996 */
997 function writeUC($variable='') {
998 if (is_array($this->user) && $this->user[$this->userid_column]) {
999 if (!is_array($variable)) { $variable = $this->uc; }
1000
1001 if ($this->writeDevLog) t3lib_div::devLog('writeUC: '.$this->userid_column.'='.intval($this->user[$this->userid_column]), 't3lib_userAuth');
1002 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->user_table, $this->userid_column.'='.intval($this->user[$this->userid_column]), array('uc' => serialize($variable)));
1003 }
1004 }
1005
1006 /**
1007 * Sets $theUC as the internal variable ->uc IF $theUC is an array. If $theUC is false, the 'uc' content from the ->user array will be unserialized and restored in ->uc
1008 *
1009 * @param mixed If an array, then set as ->uc, otherwise load from user record
1010 * @return void
1011 */
1012 function unpack_uc($theUC='') {
1013 if (!$theUC) $theUC=unserialize($this->user['uc']);
1014 if (is_array($theUC)) {
1015 $this->uc=$theUC;
1016 }
1017 }
1018
1019 /**
1020 * Stores data for a module.
1021 * The data is stored with the session id so you can even check upon retrieval if the module data is from a previous session or from the current session.
1022 *
1023 * @param string $module is the name of the module ($MCONF['name'])
1024 * @param mixed $data is the data you want to store for that module (array, string, ...)
1025 * @param boolean If $noSave is set, then the ->uc array (which carries all kinds of user data) is NOT written immediately, but must be written by some subsequent call.
1026 * @return void
1027 */
1028 function pushModuleData($module,$data,$noSave=0) {
1029 $this->uc['moduleData'][$module] = $data;
1030 $this->uc['moduleSessionID'][$module] = $this->id;
1031 if (!$noSave) $this->writeUC();
1032 }
1033
1034 /**
1035 * Gets module data for a module (from a loaded ->uc array)
1036 *
1037 * @param string $module is the name of the module ($MCONF['name'])
1038 * @param string If $type = 'ses' then module data is returned only if it was stored in the current session, otherwise data from a previous session will be returned (if available).
1039 * @return mixed The module data if available: $this->uc['moduleData'][$module];
1040 */
1041 function getModuleData($module,$type='') {
1042 if ($type!='ses' || $this->uc['moduleSessionID'][$module]==$this->id) {
1043 return $this->uc['moduleData'][$module];
1044 }
1045 }
1046
1047 /**
1048 * Returns the session data stored for $key.
1049 * The data will last only for this login session since it is stored in the session table.
1050 *
1051 * @param string Pointer to an associative key in the session data array which is stored serialized in the field "ses_data" of the session table.
1052 * @return mixed
1053 */
1054 function getSessionData($key) {
1055 $sesDat = unserialize($this->user['ses_data']);
1056 return $sesDat[$key];
1057 }
1058
1059 /**
1060 * Sets the session data ($data) for $key and writes all session data (from ->user['ses_data']) to the database.
1061 * The data will last only for this login session since it is stored in the session table.
1062 *
1063 * @param string Pointer to an associative key in the session data array which is stored serialized in the field "ses_data" of the session table.
1064 * @param mixed The variable to store in index $key
1065 * @return void
1066 */
1067 function setAndSaveSessionData($key,$data) {
1068 $sesDat = unserialize($this->user['ses_data']);
1069 $sesDat[$key] = $data;
1070 $this->user['ses_data'] = serialize($sesDat);
1071
1072 if ($this->writeDevLog) t3lib_div::devLog('setAndSaveSessionData: ses_id = '.$this->user['ses_id'], 't3lib_userAuth');
1073 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->session_table, 'ses_id='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->user['ses_id'], $this->session_table), array('ses_data' => $this->user['ses_data']));
1074 }
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088 /*************************
1089 *
1090 * Misc
1091 *
1092 *************************/
1093
1094 /**
1095 * Returns an info array with Login/Logout data submitted by a form or params
1096 *
1097 * @return array
1098 * @internal
1099 */
1100 function getLoginFormData() {
1101 $loginData=array();
1102 if ($this->getMethodEnabled) {
1103 $loginData['status'] = t3lib_div::_GP($this->formfield_status);
1104 $loginData['uname'] = t3lib_div::_GP($this->formfield_uname);
1105 $loginData['uident'] = t3lib_div::_GP($this->formfield_uident);
1106 $loginData['chalvalue'] = t3lib_div::_GP($this->formfield_chalvalue);
1107 } else {
1108 $loginData['status'] = t3lib_div::_POST($this->formfield_status);
1109 $loginData['uname'] = t3lib_div::_POST($this->formfield_uname);
1110 $loginData['uident'] = t3lib_div::_POST($this->formfield_uident);
1111 $loginData['chalvalue'] = t3lib_div::_POST($this->formfield_chalvalue);
1112 }
1113 $loginData = $this->processLoginData($loginData);
1114
1115 return $loginData;
1116 }
1117
1118 /**
1119 * Processes Login data submitted by a form or params depending on the
1120 * security_level
1121 *
1122 * @param array login data array
1123 * @param string Alternative security_level. Used when authentication services wants to override the default.
1124 * @return array processed login data array
1125 * @internal
1126 */
1127 function processLoginData($loginData, $security_level='') {
1128 global $TYPO3_CONF_VARS;
1129
1130 $loginSecurityLevel = $security_level ? $security_level : ($TYPO3_CONF_VARS[$this->loginType]['loginSecurityLevel'] ? $TYPO3_CONF_VARS[$this->loginType]['loginSecurityLevel'] : $this->security_level);
1131
1132 // Processing data according to the state it was submitted in.
1133 // ($loginSecurityLevel should reflect the security level used on the data being submitted in the login form)
1134 if ($loginSecurityLevel=='normal') {
1135 $loginData['uident_text'] = $loginData['uident'];
1136 $loginData['uident_challenged'] = (string)md5($loginData['uname'].':'.$loginData['uident'].':'.$loginData['chalvalue']);
1137 $loginData['uident_superchallenged'] = (string)md5($loginData['uname'].':'.(md5($loginData['uident'])).':'.$loginData['chalvalue']);
1138 } elseif ($loginSecurityLevel=='challenged') {
1139 $loginData['uident_text'] = '';
1140 $loginData['uident_challenged'] = $loginData['uident'];
1141 $loginData['uident_superchallenged'] = '';
1142 } elseif ($loginSecurityLevel=='superchallenged') {
1143 $loginData['uident_text'] = '';
1144 $loginData['uident_challenged'] = '';
1145 $loginData['uident_superchallenged'] = $loginData['uident'];
1146 }
1147
1148 // The password "uident" is set based on the internal security setting of TYPO3
1149 // Example:
1150 // $this->security_level for the backend must be "superchallenged" because passwords are stored as md5-hashes in the be_users table
1151 // $this->security_level for the frontend must be "normal" or "challenged" because passwords are stored as clear-text in the fe_users tables
1152 if ($this->security_level=='normal') {
1153 $loginData['uident'] = $loginData['uident_text'];
1154 } elseif ($this->security_level=='challenged') {
1155 $loginData['uident'] = $loginData['uident_challenged'];
1156 } elseif ($this->security_level=='superchallenged') {
1157 $loginData['uident'] = $loginData['uident_superchallenged'];
1158 }
1159
1160 return $loginData;
1161 }
1162
1163 /**
1164 * Returns an info array which provides additional information for auth services
1165 *
1166 * @return array
1167 * @internal
1168 */
1169 function getAuthInfoArray() {
1170 $authInfo = array();
1171 $authInfo['loginType'] = $this->loginType;
1172 $authInfo['refInfo'] = parse_url(t3lib_div::getIndpEnv('HTTP_REFERER'));
1173 $authInfo['HTTP_HOST'] = t3lib_div::getIndpEnv('HTTP_HOST');
1174 $authInfo['REMOTE_ADDR'] = t3lib_div::getIndpEnv('REMOTE_ADDR');
1175 $authInfo['REMOTE_HOST'] = t3lib_div::getIndpEnv('REMOTE_HOST');
1176 $authInfo['security_level'] = $this->security_level;
1177 $authInfo['showHiddenRecords'] = $this->showHiddenRecords;
1178 // can be overidden in localconf by SVCONF:
1179 $authInfo['db_user']['table'] = $this->user_table;
1180 $authInfo['db_user']['userid_column'] = $this->userid_column;
1181 $authInfo['db_user']['username_column'] = $this->username_column;
1182 $authInfo['db_user']['userident_column'] = $this->userident_column;
1183 $authInfo['db_user']['usergroup_column'] = $this->usergroup_column;
1184 $authInfo['db_user']['enable_clause'] = $this->user_where_clause();
1185 $authInfo['db_user']['checkPidList'] = $this->checkPid ? $this->checkPid_value : '';
1186 $authInfo['db_user']['check_pid_clause'] = $this->checkPid ? ' AND pid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($authInfo['db_user']['checkPidList']).')' : '';
1187 $authInfo['db_groups']['table'] = $this->usergroup_table;
1188 return $authInfo;
1189 }
1190
1191 /**
1192 * Check the login data with the user record data for builtin login methods
1193 *
1194 * @param array user data array
1195 * @param array login data array
1196 * @param string Alternative security_level. Used when authentication services wants to override the default.
1197 * @return boolean true if login data matched
1198 */
1199 function compareUident($user, $loginData, $security_level='') {
1200
1201 $OK = FALSE;
1202 $security_level = $security_level ? $security_level : $this->security_level;
1203
1204 switch ($security_level) {
1205 case 'superchallenged': // If superchallenged the password in the database ($user[$this->userident_column]) must be a md5-hash of the original password.
1206 case 'challenged':
1207
1208 // Check challenge stored in cookie:
1209 if ($this->challengeStoredInCookie) {
1210 session_start();
1211 if ($_SESSION['login_challenge'] !== $loginData['chalvalue']) {
1212 if ($this->writeDevLog) t3lib_div::devLog('PHP Session stored challenge "'.$_SESSION['login_challenge'].'" and submitted challenge "'.$loginData['chalvalue'].'" did not match, so authentication failed!', 't3lib_userAuth', 2);
1213 $this->logoff();
1214 return FALSE;
1215 }
1216 }
1217
1218 if ((string)$loginData['uident'] === (string)md5($user[$this->username_column].':'.$user[$this->userident_column].':'.$loginData['chalvalue'])) {
1219 $OK = TRUE;
1220 }
1221 break;
1222 default: // normal
1223 if ((string)$loginData['uident'] === (string)$user[$this->userident_column]) {
1224 $OK = TRUE;
1225 }
1226 break;
1227 }
1228
1229 return $OK;
1230 }
1231
1232 /**
1233 * Garbage collector, removing old expired sessions.
1234 *
1235 * @return void
1236 * @internal
1237 */
1238 function gc() {
1239 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
1240 $this->session_table,
1241 'ses_tstamp < ' . intval($GLOBALS['EXEC_TIME'] - ($this->gc_time)) .
1242 ' AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
1243 );
1244 }
1245
1246 /**
1247 * Redirect to somewhere (obsolete).
1248 *
1249 * @return void
1250 * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.5.
1251 * @obsolete
1252 * @ignore
1253 */
1254 function redirect() {
1255 if (!$this->userid && $this->auth_url) { // if no userid AND an include-document for login is given
1256 t3lib_div::deprecationLog('Redirection after login via PHP include is deprecated.');
1257 include ($this->auth_include);
1258 exit;
1259 }
1260 }
1261
1262 /**
1263 * DUMMY: Writes to log database table (in some extension classes)
1264 *
1265 * @param integer $type: denotes which module that has submitted the entry. This is the current list: 1=tce_db; 2=tce_file; 3=system (eg. sys_history save); 4=modules; 254=Personal settings changed; 255=login / out action: 1=login, 2=logout, 3=failed login (+ errorcode 3), 4=failure_warning_email sent
1266 * @param integer $action: denotes which specific operation that wrote the entry (eg. 'delete', 'upload', 'update' and so on...). Specific for each $type. Also used to trigger update of the interface. (see the log-module for the meaning of each number !!)
1267 * @param integer $error: flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1268 * @param integer $details_nr: The message number. Specific for each $type and $action. in the future this will make it possible to translate errormessages to other languages
1269 * @param string $details: Default text that follows the message
1270 * @param array $data: Data that follows the log. Might be used to carry special information. If an array the first 5 entries (0-4) will be sprintf'ed the details-text...
1271 * @param string $tablename: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1272 * @param integer $recuid: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1273 * @param integer $recpid: Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1274 * @return void
1275 * @see t3lib_userauthgroup::writelog()
1276 */
1277 function writelog($type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid) {
1278 }
1279
1280 /**
1281 * DUMMY: Check login failures (in some extension classes)
1282 *
1283 * @return void
1284 * @ignore
1285 */
1286 function checkLogFailures() {
1287 }
1288
1289 /**
1290 * Raw initialization of the be_user with uid=$uid
1291 * This will circumvent all login procedures and select a be_users record from the database and set the content of ->user to the record selected. Thus the BE_USER object will appear like if a user was authenticated - however without a session id and the fields from the session table of course.
1292 * Will check the users for disabled, start/endtime, etc. ($this->user_where_clause())
1293 *
1294 * @param integer The UID of the backend user to set in ->user
1295 * @return void
1296 * @internal
1297 * @see SC_mod_tools_be_user_index::compareUsers(), SC_mod_user_setup_index::simulateUser(), freesite_admin::startCreate()
1298 */
1299 function setBeUserByUid($uid) {
1300 $this->user = $this->getRawUserByUid($uid);
1301 }
1302
1303 /**
1304 * Raw initialization of the be_user with username=$name
1305 *
1306 * @param string The username to look up.
1307 * @return void
1308 * @see t3lib_userAuth::setBeUserByUid()
1309 * @internal
1310 */
1311 function setBeUserByName($name) {
1312 $this->user = $this->getRawUserByName($name);
1313 }
1314
1315 /**
1316 * Fetching raw user record with uid=$uid
1317 *
1318 * @param integer The UID of the backend user to set in ->user
1319 * @return array user record or FALSE
1320 * @internal
1321 */
1322 function getRawUserByUid($uid) {
1323 $user = FALSE;
1324 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'uid='.intval($uid).' '.$this->user_where_clause());
1325 if ($dbres) {
1326 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1327 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1328 }
1329 return $user;
1330 }
1331
1332 /**
1333 * Fetching raw user record with username=$name
1334 *
1335 * @param string The username to look up.
1336 * @return array user record or FALSE
1337 * @see t3lib_userAuth::getUserByUid()
1338 * @internal
1339 */
1340 function getRawUserByName($name) {
1341 $user = FALSE;
1342 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'username='.$GLOBALS['TYPO3_DB']->fullQuoteStr($name, $this->user_table).' '.$this->user_where_clause());
1343 if ($dbres) {
1344 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1345 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1346 }
1347 return $user;
1348 }
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364 /*************************
1365 *
1366 * Create/update user - EXPERIMENTAL
1367 *
1368 *************************/
1369
1370 /**
1371 * Get a user from DB by username
1372 * provided for usage from services
1373 *
1374 * @param array User db table definition: $this->db_user
1375 * @param string user name
1376 * @param string additional WHERE clause: " AND ...
1377 * @return mixed user array or FALSE
1378 */
1379 function fetchUserRecord($dbUser, $username, $extraWhere='' ) {
1380 $user = FALSE;
1381
1382 $usernameClause = $username ? ($dbUser['username_column'].'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($username, $dbUser['table'])) : '';
1383
1384 if ($username || $extraWhere) {
1385
1386 // Look up the user by the username and/or extraWhere:
1387 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1388 '*',
1389 $dbUser['table'],
1390 $usernameClause.
1391 $dbUser['check_pid_clause'].
1392 $dbUser['enable_clause'].
1393 $extraWhere
1394 );
1395
1396 if ($dbres) {
1397 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1398 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1399 }
1400 }
1401 return $user;
1402 }
1403 }
1404
1405
1406
1407 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauth.php']) {
1408 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauth.php']);
1409 }
1410
1411 ?>