Przeglądaj źródła

Merge pull request #235 from Cerothen/master

Backend Authorization Support & Emby Home Music Bugfix
causefx 9 lat temu
rodzic
commit
07fc4ebb36
6 zmienionych plików z 363 dodań i 193 usunięć
  1. 204 8
      functions.php
  2. 2 1
      index.php
  3. 2 1
      js/user.js
  4. 7 1
      lang/en.ini
  5. 33 1
      settings.php
  6. 115 181
      user.php

+ 204 - 8
functions.php

@@ -1,11 +1,85 @@
 <?php
 
+// Debugging output functions
 function debug_out($variable, $die = false) {
 	$trace = debug_backtrace()[0];
-	echo '<pre style="background-color: #f2f2f2; border: 2px solid black; border-radius: 5px; padding: 5px; margin: 5px";>'.$trace['file'].':'.$trace['line']."\n\n".print_r($variable, true).'</pre>';
+	echo '<pre style="background-color: #f2f2f2; border: 2px solid black; border-radius: 5px; padding: 5px; margin: 5px;">'.$trace['file'].':'.$trace['line']."\n\n".print_r($variable, true).'</pre>';
 	if ($die) { http_response_code(503); die(); }
 }
 
+// Auth Plugins
+// Pass credentials to LDAP backend
+function plugin_auth_ldap($username, $password) {
+	// returns true or false
+	$ldap = ldap_connect(AUTHBACKENDHOST.(AUTHBACKENDPORT?':'.AUTHBACKENDPORT:'389'));
+	if ($bind = ldap_bind($ldap, AUTHBACKENDDOMAIN.'\\'.$username, $password)) {
+		return true;
+	} else {
+		return false;
+	}
+	return false;
+}
+
+// Pass credentials to FTP backend
+function plugin_auth_ftp($username, $password) {
+	// returns true or false
+	
+	// Connect to FTP
+	$conn_id = ftp_ssl_connect(AUTHBACKENDHOST, (AUTHBACKENDPORT?AUTHBACKENDPORT:21), 20); // 20 Second Timeout
+	
+	// Check if valid FTP connection
+	if ($conn_id) {
+		// Attempt login
+		@$login_result = ftp_login($conn_id, $username, $password);
+		
+		// Return Result
+		if ($login_result) {
+			return true;
+		} else {
+			return false;
+		}
+	} else {
+		return false;
+	}
+	return false;
+}
+
+// Pass credentials to Emby Backend
+function plugin_auth_emby($username, $password) {
+	$urlCheck = stripos(AUTHBACKENDHOST, "http");
+	if ($urlCheck === false) {
+		$embyAddress = "http://" . AUTHBACKENDHOST;
+	} else {
+		$embyAddress = AUTHBACKENDHOST;	
+	}
+	if(AUTHBACKENDPORT !== ""){ $embyAddress .= ":" . AUTHBACKENDPORT; }
+	
+	$headers = array(
+		'Authorization'=> 'MediaBrowser UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", Client="None", Device="Organizr", DeviceId="xxx", Version="1.0.0.0"',
+		'Content-type' => 'application/json',
+	);
+	$body = array(
+		'Username' => $username,
+		'Password' => sha1($password),
+		'PasswordMd5' => md5($password),
+	);
+	
+	$response = post_router($embyAddress.'/Users/AuthenticateByName', $body, $headers);
+	
+	if (isset($response['content'])) {
+		$json = json_decode($response['content'], true);
+		if (is_array($json) && isset($json['SessionInfo']) && isset($json['User']) && $json['User']['HasPassword'] == true) {
+			// Login Success - Now Logout Emby Session As We No Longer Need It
+			$headers = array(
+				'X-Mediabrowser-Token' => $json['AccessToken'],
+			);
+			$response = post_router($embyAddress.'/Sessions/Logout', array(), $headers);
+			return true;
+		}
+	}
+	return false;
+}
+
 function clean($strin) {
     $strout = null;
 
@@ -245,19 +319,22 @@ function resolveEmbyItem($address, $token, $item) {
 			$title = $item['SeriesName'].': '.$item['Name'].' (Season '.$item['ParentIndexNumber'].': Episode '.$item['IndexNumber'].')';
 			$imageId = $itemDetails['SeriesId'];
 			$width = 100;
-			$image = 'season';
+			$image = 'carousel-image season';
+			$style = '';
 			break;
-		case 'Music':
+		case 'MusicAlbum':
 			$title = $item['Name'];
-			$imageId = $itemDetails['AlbumId'];
+			$imageId = $itemDetails['Id'];
 			$width = 150;
 			$image = 'music';
+			$style = 'left: 160px !important;';
 			break;
 		default:
 			$title = $item['Name'];
 			$imageId = $item['Id'];
 			$width = 100;
-			$image = 'movie';
+			$image = 'carousel-image movie';
+			$style = '';
 	}
 	
 	// If No Overview
@@ -266,7 +343,7 @@ function resolveEmbyItem($address, $token, $item) {
 	}
 	
 	// Assemble Item And Cache Into Array 
-	return '<div class="item"><a href="'.$address.'/web/itemdetails.html?id='.$item['Id'].'" target="_blank"><img alt="'.$item['Name'].'" class="carousel-image '.$image.'" src="image.php?source=emby&img='.$imageId.'&height='.$height.'&width='.$width.'"></a><div class="carousel-caption '.$image.'""><h4>'.$title.'</h4><small><em>'.$itemDetails['Overview'].'</em></small></div></div>';
+	return '<div class="item"><a href="'.$address.'/web/itemdetails.html?id='.$item['Id'].'" target="_blank"><img alt="'.$item['Name'].'" class="'.$image.'" src="image.php?source=emby&img='.$imageId.'&height='.$height.'&width='.$width.'"></a><div class="carousel-caption" style="'.$style.'"><h4>'.$title.'</h4><small><em>'.$itemDetails['Overview'].'</em></small></div></div>';
 }
 
 function outputCarousel($header, $size, $type, $items) {
@@ -338,14 +415,20 @@ function getEmbyRecent($url, $port, $type, $token, $size, $header) {
 			$embyTypeQuery = 'IncludeItemTypes=Episode&';
 			break;
 		case 'album':
-			$embyTypeQuery = 'IncludeItemTypes=Music&';
+			$embyTypeQuery = 'IncludeItemTypes=MusicAlbum&';
 			break;
 		default:
 			$embyTypeQuery = '';
 	}
 	
 	// Get A User
-	$userId = json_decode(file_get_contents($address.'/Users?api_key='.$token),true)[0]['Id'];
+	$userIds = json_decode(file_get_contents($address.'/Users?api_key='.$token),true);
+	foreach ($userIds as $value) { // Scan for admin user
+		$userId = $value['Id'];
+		if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
+			break;
+		}
+	}
 	
 	// Get the latest Items
 	$latest = json_decode(file_get_contents($address.'/Users/'.$userId.'/Items/Latest?'.$embyTypeQuery.'EnableImages=false&api_key='.$token),true);
@@ -908,4 +991,117 @@ function getHeadphonesCalendar($url, $port, $key, $list){
     if ($i != 0){ return $gotCalendar; }
 
 }
+
+function post_router($url, $data, $headers = array(), $referer='') {
+	if (function_exists('curl_version')) {
+		return curl_post($url, $data, $headers, $referer);
+	} else {
+		return post_request($url, $data, $headers, $referer);
+	}
+}
+
+function curl_post($url, $data, $headers = array(), $referer='') {
+	// Initiate cURL
+	$curlReq = curl_init($url);
+	// As post request
+	curl_setopt($curlReq, CURLOPT_CUSTOMREQUEST, "POST"); 
+	curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
+	// Format Headers
+	$cHeaders = array();
+	foreach ($headers as $k => $v) {
+		$cHeaders[] = $k.': '.$v;
+	}
+	if (count($cHeaders)) {
+		curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
+	}
+	// Format Data
+	curl_setopt($curlReq, CURLOPT_POSTFIELDS, json_encode($data));
+	// Execute
+	$result = curl_exec($curlReq);
+	// Close
+	curl_close($curlReq);
+	// Return
+	return array('content'=>$result);
+}
+
+function post_request($url, $data, $headers = array(), $referer='') {
+	// Adapted from http://stackoverflow.com/a/28387011/6810513
+	
+    // Convert the data array into URL Parameters like a=b&foo=bar etc.
+	if (isset($headers['Content-type'])) {
+		switch ($headers['Content-type']) {
+			case 'application/json':
+				$data = json_encode($data);
+				break;
+			case 'application/x-www-form-urlencoded':
+				$data = http_build_query($data);
+				break;
+		}
+	} else {
+		$headers['Content-type'] = 'application/x-www-form-urlencoded';
+		$data = http_build_query($data);
+	}
+    
+    // parse the given URL
+    $urlDigest = parse_url($url);
+
+    // extract host and path:
+    $host = $urlDigest['host'].(isset($urlDigest['port'])?':'.$urlDigest['port']:'');
+    $path = $urlDigest['path'];
+	
+    if ($urlDigest['scheme'] != 'http') {
+        die('Error: Only HTTP request are supported, please use cURL to add HTTPS support! ('.$urlDigest['scheme'].'://'.$host.')');
+    }
+
+    // open a socket connection on port 80 - timeout: 30 sec
+    $fp = fsockopen($host, 80, $errno, $errstr, 30);
+
+    if ($fp){
+
+        // send the request headers:
+        fputs($fp, "POST $path HTTP/1.1\r\n");
+        fputs($fp, "Host: $host\r\n");
+
+        if ($referer != '')
+            fputs($fp, "Referer: $referer\r\n");
+		
+        fputs($fp, "Content-length: ". strlen($data) ."\r\n");
+		foreach($headers as $k => $v) {
+			fputs($fp, $k.": ".$v."\r\n");
+		}
+        fputs($fp, "Connection: close\r\n\r\n");
+        fputs($fp, $data);
+
+        $result = '';
+        while(!feof($fp)) {
+            // receive the results of the request
+            $result .= fgets($fp, 128);
+        }
+    }
+    else {
+        return array(
+            'status' => 'err',
+            'error' => "$errstr ($errno)"
+        );
+    }
+
+    // close the socket connection:
+    fclose($fp);
+
+    // split the result header from the content
+    $result = explode("\r\n\r\n", $result, 2);
+
+    $header = isset($result[0]) ? $result[0] : '';
+    $content = isset($result[1]) ? $result[1] : '';
+
+    // return as structured array:
+    return array(
+        'status' => 'ok',
+        'header' => $header,
+        'content' => $content,
+	);
+}
+
+	
+	
 ?>

+ 2 - 1
index.php

@@ -1065,6 +1065,7 @@ endif; ?>
 
                             <input type="hidden" name="op" value="update"/>
                             <input type="hidden" name="sha1" value=""/>
+			    <input type="hidden" name="password" value="">
                             <input type="hidden" name="username" value="<?php echo $USER->username; ?>"/>
                             <input type="hidden" name="role" value="<?php echo $USER->role; ?>"/>
 
@@ -1982,4 +1983,4 @@ endif; ?>
 
     </body>
 
-</html>
+</html>

+ 2 - 1
js/user.js

@@ -133,8 +133,9 @@ User = {
 
 		valid &= this.validName(form["username"]);
 		valid &= this.validPassword(form["password1"]);
-
+		
 		if(valid) {
+			form["password"].value = form["password1"].value;
 			form["sha1"].value = Sha1.hash(form["password1"].value);
 			form["password1"].value = this.randomString(16);
 			form.submit(); }

+ 7 - 1
lang/en.ini

@@ -224,4 +224,10 @@ EMBY_URL = "Emby URL"
 EMBY_PORT = "Emby Port"
 EMBY_TOKEN = "Emby Token"
 PLAYING_NOW_ON_EMBY = "Playing Now on EMBY"
-RECENTLY_ADDED_TO_EMBY = "Recently Added to EMBY"
+RECENTLY_ADDED_TO_EMBY = "Recently Added to EMBY"
+AUTHTYPE = "Which databases should be used to allow login"
+AUTHBACKEND = "Select backend to use"
+AUTHBACKENDCREATE = "Should accounts be created in Organizr if successfully authenticated against backend"
+AUTHBACKENDHOST = "http(s)://192.168.1.100"
+AUTHBACKENDPORT = "Backend Port (eg 21 for FTP, 389 for LDAP, 8096 for Emby)"
+AUTHBACKENDDOMAIN = "Domain to use for LDAP"

+ 33 - 1
settings.php

@@ -1747,7 +1747,39 @@ endif;?></textarea>
                                                 <form class="content-form" name="systemSettings" id="systemSettings" action="" method="POST">
                         								    
                                                     <input type="hidden" name="action" value="createLocation" />
-
+							
+                                                    <div class="form-group" style="background-color: #fafafa; border: 2px solid black; border-radius: 5px; padding: 5px; margin: 5px;">
+														<select id="authType" name="authType" class="form-control material input-sm" required>
+															<option value="internal" <?php echo (AUTHTYPE=='internal' || !AUTHTYPE?'selected':''); ?>>Internal Only</option>
+															<option value="external" <?php echo (AUTHTYPE=='external'?'selected':''); ?>>External Only</option>
+															<option value="both" <?php echo (AUTHTYPE=='both'?'selected':''); ?>>Both</option>
+														</select>
+														<p class="help-text"><?php echo $language->translate("AUTHTYPE"); ?></p>
+															
+														<select id="authBackend" name="authBackend" class="form-control material input-sm" required>
+															<option value="ldap" <?php echo (AUTHBACKEND=='ldap' || !AUTHBACKEND?'selected':''); ?>>LDAP</option>
+															<option value="ftp" <?php echo (AUTHBACKEND=='ftp'?'selected':''); ?>>sFTP</option>
+															<option value="emby" <?php echo (AUTHBACKEND=='emby'?'selected':''); ?>>Emby</option>
+															<option value="plex" <?php echo (AUTHBACKEND=='plex'?'selected':''); ?> disabled>Plex</option>
+														</select>
+														<p class="help-text"><?php echo $language->translate("AUTHBACKEND"); ?></p>
+														
+														<select id="authBackendCreate" name="authBackendCreate" class="form-control material input-sm" required>
+															<option value="false" <?php echo (AUTHBACKENDCREATE=='false' || !AUTHBACKENDCREATE?'selected':''); ?>>Do Not Create Accounts</option>
+															<option value="true" <?php echo (AUTHBACKENDCREATE=='true'?'selected':''); ?>>Create Accounts As Needed</option>
+														</select>
+														<p class="help-text"><?php echo $language->translate("AUTHBACKENDCREATE"); ?></p>
+														
+														<input type="text" class="form-control material input-sm" name="authBackendHost" placeholder="<?php echo $language->translate("AUTHBACKENDHOST");?>" autocorrect="off" autocapitalize="off" value="<?php echo AUTHBACKENDHOST;?>">
+                                                        <p class="help-text"><?php echo $language->translate("AUTHBACKENDHOST");?></p>
+														
+														<input type="text" class="form-control material input-sm" name="authBackendPort" placeholder="<?php echo $language->translate("AUTHBACKENDPORT");?>" autocorrect="off" autocapitalize="off" value="<?php echo AUTHBACKENDPORT;?>">
+                                                        <p class="help-text"><?php echo $language->translate("AUTHBACKENDPORT");?></p>
+														
+														<input type="text" class="form-control material input-sm" name="authBackendDomain" placeholder="<?php echo $language->translate("AUTHBACKENDDOMAIN");?>" autocorrect="off" autocapitalize="off" value="<?php echo AUTHBACKENDDOMAIN;?>">
+                                                        <p class="help-text"><?php echo $language->translate("AUTHBACKENDDOMAIN");?></p>
+                                                    </div>
+							
                                                     <div class="form-group">
 
                                                         <input type="text" class="form-control material input-sm" name="databaseLocation" placeholder="<?php echo $language->translate("DATABASE_PATH");?>" autocorrect="off" autocapitalize="off" value="<?php echo DATABASE_LOCATION;?>">

+ 115 - 181
user.php

@@ -7,11 +7,8 @@
 	 *	entry is assigned a new random token,  which is used in
 	 * salting subsequent password checks.
 	 */
-
     define('INSTALLEDVERSION', '1.30');
-
     require __DIR__ . '/vendor/autoload.php';
-
     $databaseConfig = parse_ini_file('databaseLocation.ini.php', true);
     define('USER_HOME', $databaseConfig['databaseLocation'] . '/users/');
     define('DATABASE_LOCATION', $databaseConfig['databaseLocation'] . '/');
@@ -34,11 +31,18 @@
     if(!empty($databaseConfig['smtpHostPassword'])) : define('SMTPHOSTPASSWORD', $databaseConfig['smtpHostPassword']); else : define('SMTPHOSTPASSWORD', ''); endif;
     if(!empty($databaseConfig['smtpHostSenderName'])) : define('SMTPHOSTSENDERNAME', $databaseConfig['smtpHostSenderName']); else : define('SMTPHOSTSENDERNAME', 'Organizr'); endif;
     if(!empty($databaseConfig['smtpHostSenderEmail'])) : define('SMTPHOSTSENDEREMAIL', $databaseConfig['smtpHostSenderEmail']); else : define('SMTPHOSTSENDEREMAIL', 'no-reply@Organizr'); endif;
-
+	
+    if(!empty($databaseConfig['authType'])) : define('AUTHTYPE', $databaseConfig['authType']); else : define('AUTHTYPE', ''); endif;
+    if(!empty($databaseConfig['authBackend'])) : define('AUTHBACKEND', $databaseConfig['authBackend']); else : define('AUTHBACKEND', ''); endif;
+    if(!empty($databaseConfig['authBackendHost'])) : define('AUTHBACKENDHOST', $databaseConfig['authBackendHost']); else : define('AUTHBACKENDHOST', ''); endif;
+    if(!empty($databaseConfig['authBackendPort'])) : define('AUTHBACKENDPORT', $databaseConfig['authBackendPort']); else : define('AUTHBACKENDPORT', ''); endif;
+    if(!empty($databaseConfig['authBackendDomain'])) : define('AUTHBACKENDDOMAIN', $databaseConfig['authBackendDomain']); else : define('AUTHBACKENDDOMAIN', ''); endif;
+    if(!empty($databaseConfig['authBackendCreate'])) : define('AUTHBACKENDCREATE', $databaseConfig['authBackendCreate']); else : define('AUTHBACKENDCREATE', 'false'); endif;
+	
     if(!file_exists('homepageSettings.ini.php')){ touch('homepageSettings.ini.php'); }
-        
     $homepageConfig = parse_ini_file('homepageSettings.ini.php', true);        
-    if(!empty($homepageConfig['plexURL'])) : define('PLEXURL', $homepageConfig['plexURL']); else : define('PLEXURL', ''); endif;
+    
+	if(!empty($homepageConfig['plexURL'])) : define('PLEXURL', $homepageConfig['plexURL']); else : define('PLEXURL', ''); endif;
     if(!empty($homepageConfig['plexPort'])) : define('PLEXPORT', $homepageConfig['plexPort']); else : define('PLEXPORT', ''); endif;
     if(!empty($homepageConfig['plexToken'])) : define('PLEXTOKEN', $homepageConfig['plexToken']); else : define('PLEXTOKEN', ''); endif;
     if(!empty($homepageConfig['plexRecentMovie'])) : define('PLEXRECENTMOVIE', $homepageConfig['plexRecentMovie']); else : define('PLEXRECENTMOVIE', 'false'); endif;
@@ -74,32 +78,26 @@
     if(!empty($homepageConfig['calendarEndDay'])) : define('CALENDARENDDAY', $homepageConfig['calendarEndDay']); else : define('CALENDARENDDAY', '30'); endif;
     if(!empty($homepageConfig['sickrageKey'])) : define('SICKRAGEKEY', $homepageConfig['sickrageKey']); else : define('SICKRAGEKEY', ''); endif;
     if(!empty($homepageConfig['sickrageURL'])) : define('SICKRAGEURL', $homepageConfig['sickrageURL']); else : define('SICKRAGEURL', ''); endif;
-
     
     if(file_exists('custom.css')) : define('CUSTOMCSS', 'true'); else : define('CUSTOMCSS', 'false'); endif; 
     $notifyExplode = explode("-", NOTIFYEFFECT);
     define('FAIL_LOG', 'loginLog.json');
     date_default_timezone_set(TIMEZONE);
-
+	
 	class User
 	{
 		// =======================================================================
 		// IMPORTANT VALUES THAT YOU *NEED* TO CHANGE FOR THIS TO BE SECURE
 		// =======================================================================
-
 			// Keeping this location on ./... means that it will be publically visible to all,
 			// and you need to use htaccess rules or some such to ensure no one
 			// grabs your user's data.
-
 			//const USER_HOME = "../users/";
-
 			// In order for users to be notified by email of certain things, set this to true.
 			// Note that the server you run this on should have sendmail in order for
 			// notification emails to work. Also note that password resetting doesn't work
 			// unless mail notification is turned on.
-
 			const use_mail = ENABLEMAIL;
-
 			// This value should point to a directory that is not available to web users.
 			// If your documents are in ./public_html, for instance., then put database
 			// in something like ./database - that way, you don't have to rely on
@@ -109,23 +107,18 @@
 			// By default it's set to the stupidly dangerous and publically accessible same
 			// base dir as your web page. So change it, because people are going to try
 			// to download your database file. And succeed.
-
 			//const DATABASE_LOCATION = "../";
-
 			// if this is set to "true", registration failure due to known usernames is reported,
 			// and login failures are explained as either the wrong username or the wrong password.
 			// You really want to set this to 'false', but it's on true by default because goddamnit
 			// I'm going to confront you with security issues right off the bat =)
-
 			const unsafe_reporting = false;
-
 			/**
 				Think about security for a moment. On the one hand, you want your website
 				to not reveal whether usernames are already taken, so when people log in
 				you will want to say "username or password incorrect". However, you also want
 				to be able to tell people that they can't register because the username they
 				picked is already taken.
-
 				Because these are mutually exclusive, you can't do both using this framework.
 				You can either use unsafe reporting, where the system will will tell you that
 				a username exists, both during registration and login, or you can use safe
@@ -133,79 +126,56 @@
 				similarity, not exact match. But then it also won't say which of the username
 				or password in a login attempt was incorrect.
 			**/
-
 		// =======================================================================
 		// 	You can modify the following values, but they're not security related
 		// =======================================================================
-
 			// rename this to whatever you like
 			const DATABASE_NAME = "users";
-
 			// this is the session timeout. If someone hasn't performed any page requests
 			// in [timeout] seconds, they're considered logged out.
 			const time_out = 604800;
-
 			// You'll probably want to change this to something sensible. If your site is
 			// www.sockmonkey.com, then you want this to be "sockmonkey.com"
 			const DOMAIN_NAME = "Organizr";
-
 			// This is going to be the "from" address
 			const MAILER_NAME = "noreply@organizr";
-
 			// if you want people to be able to reply to a real address, override
 			// this variable to "yourmail@somedomain.ext" here.
 			const MAILER_REPLYTO = "noreply@organizr";
-
 		// =======================================================================
 		// 	Don't modify any variables beyond this point =)
 		// =======================================================================
-
 		// this is the global error message. If anything goes wrong, this tells you why.
 		var $error = "";
-
 		// progress log
 		var $info_log = array();
-
 		// Information logging
 		function info($string) { $this->info_log[] = $string; }
-
 		// error log
 		var $error_log = array();
-
 		// Error logging
 		function error($string) { $this->error_log[] = $string; }
-
 		// all possible values for a hexadecimal number
 		var $hex = "0123456789abcdef";
-
 		// all possible values for an ascii password, skewed a bit so the number to letter ratio is closer to 1:1
 		var $ascii = "0a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6A7B8C9D0E1F2G3H4I5J6K7L8M9N0O1P2Q3R4S5T6U7V8W9X0Y1Z23456789";
-
 		// the regular expression for email matching (see http://www.regular-expressions.info/email.html)
 		const emailregexp = "/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/";
-
 		// the regular expression for SHA1 hash matching
 		const sha1regexp = "/[0123456789abcdef]{40,40}/";
-
 		// this will tell us whether the client that requested the page is authenticated or not.
 		var $authenticated = false;
-
 		// the guest user name
 		const GUEST_USER  = "guest user";
-
 		// this will contain the user name for the user doing the page request
 		var $username = User::GUEST_USER;
-
 		// if this is a properly logged in user, this will contain the data directory location for this user
 		var $userdir = false;
-
 		// the user's email address, if logged in.
 		var $email = "";
-
 		// the user's role in the system
 		var $role = "";
 		var $group = "";
-
 		// global database handle
 		var $database = false;
         
@@ -230,7 +200,6 @@
             
         }
        
-
 		// class object constructor
 		function __construct($registration_callback=false)
 		{
@@ -241,25 +210,19 @@
             }else{
                 $_SESSION["username"] = $_COOKIE['OrganizrU'];
             }
-
 			// file location for the user database
 			$dbfile = DATABASE_LOCATION  . User::DATABASE_NAME . ".db";
-
 			// do we need to build a new database?
 			$rebuild = false;
 			if(!file_exists($dbfile)) { $rebuild = true;}
-
 			// bind the database handler
 			$this->database = new PDO("sqlite:" . $dbfile);
-
 			// If we need to rebuild, the file will have been automatically made by the PDO call,
 			// but we'll still need to define the user table before we can use the database.
 			if($rebuild) { $this->rebuild_database($dbfile); }
-
 			// finally, process the page request.
 			$this->process($registration_callback);
 		}
-
 		// this function rebuilds the database if there is no database to work with yet
 		function rebuild_database($dbfile)
 		{
@@ -269,7 +232,6 @@
 			$this->database->exec($create);
 			$this->database->commit();
 		}
-
 		// process a page request
 		function process(&$registration_callback=false)
 		{
@@ -288,7 +250,6 @@
 				// we only allow password resetting if we can send notification mails
 				elseif($operation == "reset" && User::use_mail) { $this->reset_password(); }
 			}
-
 			// if the previous operations didn't authorise the current user,
 			// see if they're already marked as authorised in the database.
 			if(!$this->authenticated) {
@@ -296,23 +257,19 @@
 				if($username != User::GUEST_USER) {
 					$this->authenticated = $this->authenticate_user($username,"");
 					if($this->authenticated) { $this->mark_user_active($username); }}}
-
 			// at this point we can make some globals available.
 			$this->username = $_SESSION["username"];
 			$this->userdir = ($this->username !=User::GUEST_USER? USER_HOME . $this->username : false);
 			$this->email = $this->get_user_email($this->username);
 			$this->role = $this->get_user_role($this->username);
 			//$this->group = $this->get_user_group($this->username);
-
 			// clear database
 			$this->database->commit();
 			$this->database = null;
 		}
-
 	// ---------------------
 	// validation passthroughs
 	// ---------------------
-
 		/**
 		 * Called when the requested POST operation is "login"
 		 */
@@ -321,6 +278,7 @@
 			// get relevant values
 			$username = $_POST["username"];
 			$sha1 = $_POST["sha1"];
+			$password = $_POST["password"];
             $rememberMe = $_POST["rememberMe"];
 			// step 1: someone could have bypassed the javascript validation, so validate again.
 			if(!$this->validate_user_name($username)) {
@@ -330,13 +288,8 @@
 				$this->info("<strong>log in error:</strong> password did not pass validation");
 				return false; }
 			// step 2: if validation passed, log the user in
-			if($rememberMe == "true") {
-                return $this->login_user($username, $sha1, true);    
-            }else{
-                return $this->login_user($username, $sha1, false);                    
-            }
+			return $this->login_user($username, $sha1, $rememberMe == "true", $password); 
 		}
-
 		/**
 		 * Called when the requested POST operation is "logout"
 		 */
@@ -351,7 +304,6 @@
 			// step 2: if validation passed, log the user out
 			return $this->logout_user($username);
 		}
-
 		/**
 		 * Users should always have the option to unregister
 		 */
@@ -366,7 +318,6 @@
 			// step 2: if validation passed, drop the user from the system
 			return $this->unregister_user($username);
 		}
-
 		/**
 		 * Called when the requested POST operation is "register"
 		 */
@@ -398,17 +349,11 @@
 				$subject = User::DOMAIN_NAME . " registration";
 				$body = <<<EOT
 	Hi,
-
 	this is an automated message to let you know that someone signed up at $domain_name with the user name "$username", using this email address as mailing address.
-
 	Because of the way our user registration works, we have no idea which password was used to register this account (it gets one-way hashed by the browser before it is sent to our user registration system, so that we don't know your password either), so if you registered this account, hopefully you wrote your password down somewhere.
-
 	However, if you ever forget your password, you can click the "I forgot my password" link in the log-in section for $domain_name and you will be sent an email containing a new, ridiculously long and complicated password that you can use to log in. You can change your password after logging in, but that's up to you. No one's going to guess it, or brute force it, but if other people can read your emails, it's generally a good idea to change passwords.
-
 	If you were not the one to register this account, you can either contact us the normal way or —much easier— you can ask the system to reset the password for the account, after which you can simply log in with the temporary password and delete the account. That'll teach whoever pretended to be you not to mess with you!
-
 	Of course, if you did register it yourself, welcome to $domain_name!
-
 	- the $domain_name team
 EOT;
 				$headers = "From: $from\r\n";
@@ -417,10 +362,8 @@ EOT;
 				//mail($email, $subject, $body, $headers);
                 $this->startEmail($email, $username, $subject, $body);
 			}
-
 			return $registered;
 		}
-
 		/**
 		 * Called when the requested POST operation is "update"
 		 */
@@ -441,7 +384,6 @@ EOT;
 			// step 2: if validation passed, update the user's information
 			return $this->update_user($username, $email, $sha1, $role);
 		}
-
 		/**
 		 * Reset a user's password
 		 */
@@ -449,12 +391,10 @@ EOT;
 		{
 			// get the email for which we should reset
 			$email = $_POST["email"];
-
 			// step 1: someone could have bypassed the javascript validation, so validate again.
 			if(preg_match(User::emailregexp, $email)==0) {
 				$this->info("email address did not pass validation");
 				return false; }
-
 			// step 2: if validation passed, see if there is a matching user, and reset the password if there is
 			$newpassword = $this->random_ascii_string(64);
 			$sha1 = sha1($newpassword);
@@ -462,16 +402,13 @@ EOT;
 			$username = "";
 			$token = "";
 			foreach($this->database->query($query) as $data) { $username = $data["username"]; $token = $data["token"]; break; }
-
 			// step 2a: if there was no user to reset a password for, stop.
 			if($username == "" || $token == "") return false;
-
 			// step 2b: if there was a user to reset a password for, reset it.
 			$dbpassword = $this->token_hash_password($username, $sha1, $token);
 			$update = "UPDATE users SET password = '$dbpassword' WHERE email= '$email'";
 			$this->database->exec($update);
             $this->info("Email has been sent with new password");
-
 			// step 3: notify the user of the new password
 			$from = User::MAILER_NAME;
 			$replyto = User::MAILER_REPLYTO;
@@ -479,17 +416,11 @@ EOT;
 			$subject = User::DOMAIN_NAME . " password reset request";
 			$body = <<<EOT
 	Hi,
-
 	this is an automated message to let you know that someone requested a password reset for the $domain_name user account with user name "$username", which is linked to this email address.
-
 	We've reset the password to the following 64 character string, so make sure to copy/paste it without any leading or trailing spaces:
-
 	$newpassword
-
 	If you didn't even know this account existed, now is the time to log in and delete it. How dare people use your email address to register accounts! Of course, if you did register it yourself, but you didn't request the reset, some jerk is apparently reset-spamming. We hope he gets run over by a steam shovel driven by rabid ocelots or something.
-
 	Then again, it's far more likely that you did register this account, and you simply forgot the password so you asked for the reset yourself, in which case: here's your new password, and thank you for your patronage at $domain_name!
-
 	- the $domain_name team
 EOT;
 			$headers = "From: $from\r\n";
@@ -498,18 +429,15 @@ EOT;
 			//mail($email, $subject, $body, $headers);
             $this->startEmail($email, $username, $subject, $body);
 		}
-
 	// ------------------
 	// specific functions
 	// ------------------
-
 		// session management: set session values
 		function setSession($username, $token)
 		{
 			$_SESSION["username"]=$username;
 			$_SESSION["token"]=$token;
 		}
-
 		// session management: reset session values
 		function resetSession()
 		{
@@ -525,7 +453,6 @@ EOT;
             setcookie("cookiePassword", '', time() - 3600, '/', DOMAIN);
             setcookie("cookiePassword", '', time() - 3600, '/');
 		}
-
 		/**
 		 * Validate a username. Empty usernames or names
 		 * that are modified by making them SQL safe are
@@ -538,7 +465,6 @@ EOT;
 			if(!$validated) { $this->error = "user name did not pass validation."; $this->error("user name did not pass validation."); }
 			return $validated;
 		}
-
 		/**
 		 * Clean strings for SQL insertion as string in SQLite (single quote enclosed).
 		 * Note that if the cleaning changes the string, this system won't insert.
@@ -551,7 +477,6 @@ EOT;
 			$replace = array('', '', '');
 			return trim(str_replace($search, $replace, $string));
 		}
-
 		/**
 		 * Verify that the given username is allowed
 		 * to perform the given operation.
@@ -563,17 +488,12 @@ EOT;
             
 			// logged in, but do the tokens match?
 			$token = $this->get_user_token($username);
-
             if(MULTIPLELOGIN == "false"){
             
                 if(isset($_COOKIE["Organizr"])){
-
                     if($_COOKIE["Organizr"] == $token){
-
                         return true;
-
                     }else{
-
                         $this->error("cookie token mismatch for $username");
                         unset($_COOKIE['Organizr']);
                         setcookie('Organizr', '', time() - 3600, '/', DOMAIN);
@@ -585,18 +505,14 @@ EOT;
                         setcookie("cookiePassword", '', time() - 3600, '/', DOMAIN);
                         setcookie("cookiePassword", '', time() - 3600, '/');
                         return false;
-
                     }
-
                 }else{
-
                     if($token != $_SESSION["token"]) {
                         
                         $this->error("token mismatch for $username");
                         return false; 
                     
                     }
-
                     // active, using the correct token -> authenticated
                      setcookie("cookiePassword", COOKIEPASSWORD, time() + (86400 * 7), "/", DOMAIN);
                      return true;
@@ -611,7 +527,6 @@ EOT;
             }    
             
 		}
-
 		/**
 		 * Unicode friendly(ish) version of strtolower
 		 * see: http://ca3.php.net/manual/en/function.strtolower.php#91805
@@ -630,7 +545,6 @@ EOT;
 							"Ь", "Э", "Ю", "Я" );
 			return str_replace($convert_from, $convert_to, $string);
 		}
-
 		/**
 		 * This functions flattens user name strings for similarity comparison purposes
 		 */
@@ -646,7 +560,6 @@ EOT;
 			// finally, collapse case
 			return $this->strtolower_utf8($string);
 		}
-
 		/**
 		 * We don't require assloads of personal information.
 		 * A username and a password are all we want. The rest
@@ -662,7 +575,6 @@ EOT;
             foreach($this->database->query($queryAdmin) as $data) {
                 $newRole = "user";
             }
-
 			// Does user already exist? (see notes on safe reporting)
 			if(User::unsafe_reporting) {
 				$query = "SELECT username FROM users WHERE username LIKE '$username'";
@@ -670,23 +582,29 @@ EOT;
 					$this->info("user account for $username not created.");
 					$this->error = "this user name is already being used by someone else.";
                     $this->error("this user name is already being used by someone else.");
-					return false; }}
-			else{	$query = "SELECT username FROM users";
+					return false; }
+			} else {	
+				$query = "SELECT username FROM users";
 				$usernames = array();
 				foreach($this->database->query($query) as $data) { $usernames[] = $this->homogenise_username($data["username"]); }
 				if(in_array($this->homogenise_username($username), $usernames)) {
 					//$this->info("user account for $username not created.");
 					$this->error = "<strong>$username</strong> is not allowed, because it is too similar to other user names.";
                     $this->error("<strong>$username</strong> is not allowed, because it is too similar to other user names.");
-					return false; }}
-
+					return false; }
+			}
 			// Is email address already in use? (see notes on safe reporting)
-			$query = "SELECT * FROM users WHERE email = '$email'";
-			foreach($this->database->query($query) as $data) {
-				$this->info("user account for $username not created.");
-				$this->error = "this email address is already in use by someone else.";
-                $this->error("this email address is already in use by someone else.");
-				return false; }
+			if (isset($email) && $email) {
+				$query = "SELECT * FROM users WHERE email = '$email'";
+				foreach($this->database->query($query) as $data) {
+					$this->info("user account for $username not created.");
+					$this->error = "this email address is already in use by someone else.";
+					$this->error("this email address is already in use by someone else.");
+					return false; 
+				}
+			} else {
+				$email = $this->random_ascii_string(32).'@placeholder.eml';
+			}
 
 			// This user can be registered
 			$insert = "INSERT INTO users (username, email, password, token, role, active, last) ";
@@ -702,92 +620,123 @@ EOT;
 				//$this->info("created user directory $dir");
 				// if there is a callback, call it
 				if($registration_callback !== false) { $registration_callback($username, $email, $dir); }
-                if($settings !== "true") { $this->login_user($username, $sha1, true); }
+                if($settings !== 'true' && $settings !== true) { $this->login_user($username, $sha1, true, '', false); }
 				return true; }
 			$this->error = "unknown database error occured.";
             $this->error("unknown database error occured.");
 			return false;
 		}
-
 		/**
 		 * Log a user in
 		 */
-		function login_user($username, $sha1, $remember)
-		{
+		function login_user($username, $sha1, $remember, $password, $surface = true) {
 
-            function buildLog($username, $authType){
-                
-                if(file_exists(FAIL_LOG)) { 
-                    
+            $buildLog = function($username, $authType) {
+                if(file_exists(FAIL_LOG)) {
                     $getFailLog = str_replace("\r\ndate", "date", file_get_contents(FAIL_LOG));
-                    
                     $gotFailLog = json_decode($getFailLog, true);
-                
                 }
                 
                 $failLogEntryFirst = array('logType' => 'login_log', 'auth' => array(array('date' => date("Y-m-d H:i:s"), 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR'], 'auth_type' => $authType)));
-                
                 $failLogEntry = array('date' => date("Y-m-d H:i:s"), 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR'], 'auth_type' => $authType);
-                
                 if(isset($gotFailLog)) { 
-
                     array_push($gotFailLog["auth"], $failLogEntry);
-                    
                     $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotFailLog));
-
-                }else{
-
+                } else {
                     $writeFailLog = str_replace("date", "\r\ndate", json_encode($failLogEntryFirst));
-
                 }
-                
                 return $writeFailLog;
-                
-            }
-
-            // transform sha1 into real password
-			$dbpassword = $this->token_hash_password($username, $sha1, $this->get_user_token($username));
-			if($dbpassword==$sha1) {
-				$this->info("password hashing is not implemented.");
-				return false; }
-
-			// perform the authentication step
-			$query = "SELECT password FROM users WHERE username = '$username'";
-			foreach($this->database->query($query) as $data) {
-				if($dbpassword==$data["password"]) {
+            };
+			
+			// External Authentication
+			$authSuccess = false;
+			$function = 'plugin_auth_'.AUTHBACKEND;
+			switch (AUTHTYPE) {
+				case 'external':
+					if (function_exists($function)) {
+						$authSuccess = $function($username, $password);
+					}
+					break;
+				case 'both':
+					if (function_exists($function)) {
+						$authSuccess = $function($username, $password);
+					}
+				default: // Internal
+					if (!$authSuccess) {
+						// perform the internal authentication step
+						$query = "SELECT password FROM users WHERE username = '$username'";
+						foreach($this->database->query($query) as $data) {
+							
+							if (password_verify($password, $data["password"])) { // Better
+								$authSuccess = true;
+							} else {
+								// Legacy - Less Secure
+								$dbpassword = $this->token_hash_password($username, $sha1, $this->get_user_token($username));
+								if($dbpassword==$data["password"]) { 
+									$authSuccess = true;
+								}
+							}
+						}
+					}
+			}
+			
+			if ($authSuccess) {
+				// Make sure user exists in database
+				$query = "SELECT username FROM users WHERE username = '$username'";
+				$userExists = false;
+				foreach($this->database->query($query) as $data) {
+					if ($data['username'] == $username) {
+						$userExists = true;
+						break;
+					}
+				}
+				
+				if ($userExists) {
 					// authentication passed - 1) mark active and update token
 					$this->mark_user_active($username);
 					$this->setSession($username, $this->update_user_token($username, $sha1, false));
 					// authentication passed - 2) signal authenticated
-                    if($remember == "true") {
-                        setcookie("Organizr", $this->get_user_token($username), time() + (86400 * 7), "/", DOMAIN);
-                        setcookie("OrganizrU", $username, time() + (86400 * 7), "/", DOMAIN);
-                        
-                    }
+					if($remember == "true") {
+						setcookie("Organizr", $this->get_user_token($username), time() + (86400 * 7), "/", DOMAIN);
+						setcookie("OrganizrU", $username, time() + (86400 * 7), "/", DOMAIN);
+						
+					}
 					$this->info("Welcome $username");
-                    file_put_contents(FAIL_LOG, buildLog($username, "good_auth"));
-                    chmod(FAIL_LOG, 0660);
-                    setcookie("cookiePassword", COOKIEPASSWORD, time() + (86400 * 7), "/", DOMAIN);
-                    return true; 
-                    
-                }
+					file_put_contents(FAIL_LOG, $buildLog($username, "good_auth"));
+					chmod(FAIL_LOG, 0660);
+					setcookie("cookiePassword", COOKIEPASSWORD, time() + (86400 * 7), "/", DOMAIN);
+					return true; 
+				} else if (AUTHBACKENDCREATE !== 'false' && $surface) {
+					// Create User
+					$falseByRef = false;
+					$this->register_user($username, "", $sha1, $falseByRef, !$remember);
+				} else {
+					// authentication failed
+					//$this->info("Successful Backend Auth, No User in DB, Create Set to False");
+					file_put_contents(FAIL_LOG, $buildLog($username, "bad_auth"));
+					chmod(FAIL_LOG, 0660);
+					if(User::unsafe_reporting) { $this->error = "Successful Backend Auth, $username not in DB, Create Set to False."; $this->error("Successful Backend Auth, $username not in DB, Create Set to False."); }
+					else { $this->error = "Not permitted to login as this user, please contact an administrator."; $this->error("Not permitted to login as this user, please contact an administrator"); }
+					return false; 
+				}
+			} else if (!$authSuccess) {
 				// authentication failed
 				//$this->info("password mismatch for $username");
-                file_put_contents(FAIL_LOG, buildLog($username, "bad_auth"));
-                chmod(FAIL_LOG, 0660);
+				file_put_contents(FAIL_LOG, $buildLog($username, "bad_auth"));
+				chmod(FAIL_LOG, 0660);
 				if(User::unsafe_reporting) { $this->error = "incorrect password for $username."; $this->error("incorrect password for $username."); }
 				else { $this->error = "the specified username/password combination is incorrect."; $this->error("the specified username/password combination is incorrect."); }
-				return false; }
-
-			// authentication could not take place
-			//$this->info("there was no user $username in the database");
-            file_put_contents(FAIL_LOG, buildLog($username, "bad_auth"));
-            chmod(FAIL_LOG, 0660);
-			if(User::unsafe_reporting) { $this->error = "user $username is unknown."; $this->error("user $username is unknown."); }
-			else { $this->error = "you either did not correctly input your username, or password (... or both)."; $this->error("you either did not correctly input your username, or password (... or both)."); }
-			return false;
+				return false; 
+			} else {
+				// authentication could not take place
+				//$this->info("there was no user $username in the database");
+				file_put_contents(FAIL_LOG, $buildLog($username, "bad_auth"));
+				chmod(FAIL_LOG, 0660);
+				if(User::unsafe_reporting) { $this->error = "user $username is unknown."; $this->error("user $username is unknown."); }
+				else { $this->error = "you either did not correctly input your username, or password (... or both)."; $this->error("you either did not correctly input your username, or password (... or both)."); }
+				return false;
+			}
 		}
-
 		/**
 		 * Update a user's information
 		 */
@@ -805,7 +754,6 @@ EOT;
 				$this->database->exec($update); }
 			$this->info("updated the information for <strong>$username</strong>");
 		}
-
 		/**
 		 * Log a user out.
 		 */
@@ -826,7 +774,6 @@ EOT;
             setcookie("cookiePassword", '', time() - 3600, '/');
 			return true;
 		}
-
 		/**
 		 * Drop a user from the system
 		 */
@@ -841,7 +788,6 @@ EOT;
             $this->info("and we deleted user directory $dir");
 			return true;
 		}
-
 		/**
 		 * The incoming password will already be a sha1 print (40 bytes) long,
 		 * but for the database we want it to be hased as sha256 (using 64 bytes).
@@ -850,7 +796,6 @@ EOT;
 		{
 			return hash("sha256", $username . $sha1 . $token);
 		}
-
 		/**
 		 * Get a user's email address
 		 */
@@ -861,7 +806,6 @@ EOT;
 				foreach($this->database->query($query) as $data) { return $data["email"]; }}
 			return "";
 		}
-
 		/**
 		 * Get a user's role
 		 */
@@ -880,7 +824,6 @@ EOT;
 				foreach($this->database->query($query) as $data) { return $data["group"]; }}
 			return User::GUEST_USER;
 		}*/
-
 		/**
 		 * Get the user token
 		 */
@@ -890,7 +833,6 @@ EOT;
 			foreach($this->database->query($query) as $data) { return $data["token"]; }
 			return false;
 		}
-
 		/**
 		 * Update the user's token and password upon successful login
 		 */
@@ -900,7 +842,6 @@ EOT;
 			$token = $this->random_hex_string(32);
 			$update = "UPDATE users SET token = '$token' WHERE username = '$username'";
 			$this->database->exec($update);
-
 			// update the user's password
 			$newpassword = $this->token_hash_password($username, $sha1, $token);
 			$update = "UPDATE users SET password = '$newpassword' WHERE username = '$username'";
@@ -908,10 +849,8 @@ EOT;
 			if($noMsg == "false"){
                 $this->info("token and password updated for <strong>$username</strong>");   
             }
-
 			return $token;
 		}
-
 		/**
 		 * Mark a user as active.
 		 */
@@ -922,7 +861,6 @@ EOT;
 			//$this->info("$username has been marked currently active.");
 			return true;
 		}
-
 		/**
 		 * Check if user can be considered active
 		 */
@@ -935,7 +873,6 @@ EOT;
 				$last = intval($data["last"]);
 				$active = $data["active"];
 				break; }
-
 			if($active=="true") {
 				$diff = time() - $last;
 				if($diff >= User::time_out) {
@@ -944,12 +881,10 @@ EOT;
 					return false; }
 				//$this->info("$username is active");
 				return true; }
-
 			$this->error("<strong>$username</strong> is not active");
 			$this->resetSession();
 			return false;
 		}
-
 		/**
 		 * Random hex string generator
 		 */
@@ -960,7 +895,6 @@ EOT;
 			while($len-->0) { $string .= $this->hex[mt_rand(0, $max)]; }
 			return $string;
 		}
-
 		/**
 		 * Random password string generator
 		 */