1<?php
2/**
3* Authorization and login functionality
4* @author Nick Korbel <lqqkout13@users.sourceforge.net>
5* @author David Poole <David.Poole@fccc.edu>
6* @version 02-19-05
7* @package phpScheduleIt
8*
9* Copyright (C) 2003 - 2005 phpScheduleIt
10* License: GPL, see LICENSE
11*/
12/**
13* Base directory of application
14*/
15@define('BASE_DIR', dirname(__FILE__) . '/..');
16/**
17* DBEngine class
18*/
19include_once(BASE_DIR . '/lib/DBEngine.class.php');
20/**
21* PHPMailer
22*/
23include_once('PHPMailer.class.php');
24/**
25* Include Auth template functions
26*/
27include_once(BASE_DIR . '/templates/auth.template.php');
28
29/**
30* This class provides all authoritiative and verification
31*  functionality, including login/logout, registration,
32*  and user verification
33*/
34class Auth {
35	var $is_loggedin = false;
36	var $login_msg = '';
37	var $is_attempt = false;
38	//var $db;
39	var $success;
40
41	/**
42	* Create a reference to the database class
43	*  and start the session
44	* @param none
45	*/
46	//public static function Auth() {
47	//	$this->db = new AuthDB();
48	//}
49
50	/**
51	* Check if user is a super administrator
52	* This public static function checks to see if the currently
53	*  logged in user is the administrator, granting
54	*  them special permissions
55	* @param none
56	* @return boolean whether the user is a s_admin
57	*/
58	public static function isAdmin() {
59		return isset($_SESSION['sessionAdmin']);
60	}
61
62	/**
63        * Check if user is a mail administrator
64        * This public static function checks to see if the currently
65        *  logged in user is the administrator, granting
66        *  them special permissions
67        * @param none
68        * @return boolean whether the user is a m_admin
69        */
70        public static function isMailAdmin() {
71                return (isset($_SESSION['sessionMailAdmin']) || isset($_SESSION['sessionAdmin']));
72        }
73
74	/**
75	* Check user login
76	* This public static function checks to see if the user has
77	* a valid session set (if they are logged in)
78	* @param none
79	* @return boolean whether the user is logged in
80	*/
81	public static function is_logged_in() {
82		return isset($_SESSION['sessionID']);
83	}
84
85	/**
86	* Returns the currently logged in user's userid
87	* @param none
88	* @return the userid, or null if the user is not logged in
89	*/
90	public static function getCurrentID() {
91		return $_SESSION['sessionID'];//isset($_SESSION['sessionID']) ? $_SESSION['sessionID'] : null;
92	}
93
94	/**
95	* Logs the user in
96	* @param string $login login
97	* @param string $pass password
98	* @param string $cookieVal y or n if we are using cookie
99	* @param string $isCookie id value of user stored in the cookie
100	* @param string $resume page to forward the user to after a login
101	* @param string $lang language code to set
102	* @return any error message that occured during login
103	*/
104	function doLogin($login, $pass, $cookieVal = null, $isCookie = false, $resume = '', $lang = '', $domain = '') {
105		global $conf;
106		$msg = '';
107		$allowedToLogin = true;
108
109		if (empty($resume)) $resume = 'summary.php';		// Go to control panel by default
110
111		$_SESSION['sessionID'] = null;
112		$_SESSION['sessionName'] = null;
113		$_SESSION['sessionMail'] = null;
114		$_SESSION['sessionAdmin'] = null;
115		$_SESSION['sessionMailAdmin'] = null;
116		$_SESSION['sessionNav'] = null;
117
118		$login = stripslashes($login);
119		$pass = stripslashes($pass);
120		$ok_user = $ok_pass = false;
121		$authMethod = $conf['auth']['serverType'];
122
123		if ($isCookie != false) {		// Cookie is set
124			$id = $isCookie;
125			if ($this->db->verifyID($id))
126				$ok_user = $ok_pass = true;
127			else {
128				$ok_user = $ok_pass = false;
129				setcookie('ID', '', time()-3600, '/');	// Clear out all cookies
130				$msg .= translate('That cookie seems to be invalid') . '<br/>';
131			}
132		} else {
133
134			switch ( strtolower($authMethod) ) {
135
136				case "ad":
137                        	case "ldap":
138
139					// Added this check for LDAP servers that switch to anonymous bind whenever
140					// provided password is left blank
141					if ($pass == '') return (translate ('Invalid User Name/Password.'));
142
143		    			// Include LDAPEngine class
144            				include_once('LDAPEngine.class.php');
145
146            				$ldap = new LDAPEngine();
147
148	        			if( $ldap->connect() ) {
149
150						// Get user DN
151						// For AD it could be of the form of 'user@domain' or standard LDAP dn
152						$dn = $ldap->getUserDN($login);
153
154						// Check if user is allowed to log in
155						if ( ! $this->isAllowedToLogin($login) ) {
156                                                        $allowedToLogin = false;
157                                                        $msg .= 'User is not allowed to login';
158						// If user is allowed to log in try a bind
159                                                } elseif ( ($dn != '') && $ldap->authBind($dn, $pass) ) {
160							$ldap->logonName = $login;
161							$ldap->loadUserData($dn);
162           						$data = $ldap->getUserData();
163                    					$ok_user = true; $ok_pass = true;
164            					} else {
165                					$msg .= 'Invalid User Name/Password.';
166            					}
167
168						$ldap->disconnect();
169					}
170					break;
171
172                        	case "sql":
173
174		    			// Include DBAuth class
175            				include_once('DBAuth.class.php');
176
177					$db = new DBAuth();
178
179					// Check if user is allowed to log in
180					if ( ! $this->isAllowedToLogin($login) ) {
181                                        	$allowedToLogin = false;
182                                        	$msg .= 'User is not allowed to login';
183					// If user is allowed to log in try to authenticate
184					} elseif ( $db->authUser($login, $pass) ) {
185						$data = $db->getUserData();
186                    				$ok_user = true; $ok_pass = true;
187					} else {
188						$msg .= 'Invalid User Name/Password.';
189					}
190
191					break;
192				case "exchange":
193				        // Include ExchAuth class
194					include_once('ExchAuth.class.php');
195					$exch = new ExchAuth();
196					// Check if user is allowed to log in
197					if ( ! $this->isAllowedToLogin($login) ) {
198					       	$allowedToLogin = false;
199					       	$msg .= 'User is not allowed to login';
200					// If user is allowed to log in try to authenticate
201					} elseif ( $exch->authUser($login, $pass, $domain) ) {
202					        $data = $exch->getUserData();
203					        $ok_user = true; $ok_pass = true;
204					} else {
205					        $msg .= 'Invalid User Name/Password.';
206					}
207
208					break;
209
210                        	case "imap":
211
212		    			// Include IMAPAuth class
213            				include_once('IMAPAuth.class.php');
214
215					$imap = new IMAPAuth();
216					// Check if user is allowed to log in
217					if ( ! $this->isAllowedToLogin($login) ) {
218                                        	$allowedToLogin = false;
219                                        	$msg .= 'User is not allowed to login';
220					// If user is allowed to log in try to authenticate
221					} elseif ( $imap->authUser($login, $pass) ) {
222						$data = $imap->getUserData();
223                    				$ok_user = true; $ok_pass = true;
224					} else {
225						$msg .= 'Invalid User Name/Password.';
226					}
227					break;
228
229				default:
230                                CmnFns::do_error_box(translate('Unknown server type'), '', false);
231			}
232        	}
233
234		// If the login failed, notify the user and quit the app
235		if (!$ok_user || !$ok_pass || !$allowedToLogin) {
236			CmnFns::write_log('Authentication failed' . ', ' . $msg, $login);
237			return translate($msg);
238		} else {
239
240			$this->is_loggedin = true;
241			CmnFns::write_log('Authentication successful', $login);
242
243			/*
244			$user = new User($id);	// Get user info
245
246			// If the user wants to set a cookie, set it
247			// for their ID and fname.  Expires in 30 days (2592000 seconds)
248			if (!empty($cookieVal)) {
249				//die ('Setting cookie');
250				setcookie('ID', $user->get_id(), time() + 2592000, '/');
251			}
252
253			*/
254
255			// Set other session variables
256			$_SESSION['sessionID'] = $data['logonName'];
257			$_SESSION['sessionName'] = $data['firstName'];
258			$_SESSION['sessionMail'] = $data['emailAddress'];
259
260
261			// If it is the super admin, set session variable
262			foreach ($conf['auth']['s_admins'] as $s_admin) {
263				if (strtolower($s_admin) == strtolower($_SESSION['sessionID'])) {
264				  $_SESSION['sessionAdmin'] = true;
265				}
266			}
267
268			// If it is the mail admin, set session variable
269			foreach ($conf['auth']['m_admins'] as $m_admin) {
270				if (strtolower($m_admin) == strtolower($_SESSION['sessionID'])) {
271					$_SESSION['sessionMailAdmin'] = true;
272				}
273			}
274
275			if ($lang != '') {
276				set_language($lang);
277			}
278
279			// Send them to the control panel
280			CmnFns::redirect(urldecode($resume));
281		}
282	}
283
284	public static function isAllowedToLogin( $username ) {
285
286		global $conf;
287
288		// If not defined or set to false, $username is allowed to log in
289		if ( ! isset($conf['auth']['login_restriction']) || ! $conf['auth']['login_restriction'] ) return true;
290		// merge the allowed users together and match case-insensitive
291		$allowed = array_merge($conf['auth']['s_admins'],  $conf['auth']['m_admins'], $conf['auth']['restricted_users']);
292		foreach ($allowed as $allow) {
293			if ( strtolower($username) == strtolower($allow) ) {
294				return(true);
295			}
296		}
297	}
298
299
300	/**
301	* Log the user out of the system
302	* @param none
303	*/
304	function doLogout() {
305		// Check for valid session
306		if (!$this->is_logged_in()) {
307			$this->print_login_msg();
308			die;
309		}
310		else {
311			$login = $_SESSION['sessionID'];
312			// Destroy all session variables
313			unset($_SESSION['sessionID']);
314			unset($_SESSION['sessionName']);
315			unset($_SESSION['sessionMail']);
316			unset($_SESSION['sessionNav']);
317			if (isset($_SESSION['sessionAdmin'])) unset($_SESSION['sessionAdmin']);
318			session_destroy();
319
320			// Clear out all cookies
321			setcookie('ID', '', time()-3600, '/');
322
323			// Log in logfile
324			CmnFns::write_log('Logout successful', $login);
325
326			// Refresh page
327			CmnFns::redirect($_SERVER['PHP_SELF']);
328		}
329	}
330
331	/**
332	* Returns whether the user is attempting to log in
333	* @param none
334	* @return whether the user is attempting to log in
335	*/
336	public static function isAttempting() {
337		return $this->is_attempt;
338	}
339
340	/**
341	* Kills app
342	* @param none
343	*/
344	public static function kill() {
345		die;
346	}
347
348	/**
349	* Destroy any lingering sessions
350	* @param none
351	*/
352	public static function clean() {
353		// Destroy all session variables
354		unset($_SESSION['sessionID']);
355		unset($_SESSION['sessionName']);
356		unset($_SESSION['sessionMail']);
357		if (isset($_SESSION['sessionAdmin'])) unset($_SESSION['sessionAdmin']);
358		session_destroy();
359	}
360
361	/**
362	* Wrapper public static function to call template 'printLoginForm' function
363	* @param string $msg error messages to display for user
364	* @param string $resume page to resume after a login
365	*/
366	public static function printLoginForm($msg = '', $resume = '') {
367		printLoginForm($msg, $resume);
368	}
369
370	/**
371	* Prints a message telling the user to log in
372	* @param boolean $kill whether to end the program or not
373	*/
374	public static function print_login_msg($kill = true) {
375		CmnFns::redirect(CmnFns::getScriptURL() . '/index.php?auth=no&resume=' . urlencode($_SERVER['PHP_SELF']) . '?' . urlencode($_SERVER['QUERY_STRING']));
376	}
377
378	/**
379	* Prints out the latest success box
380	* @param none
381	*/
382	public static function print_success_box() {
383		CmnFns::do_message_box($this->success);
384	}
385}
386?>
387