From d93bbd46503836c85b8bec4ed308a8f54758e608 Mon Sep 17 00:00:00 2001 From: Bartek Fabiszewski Date: Thu, 6 Apr 2017 18:07:15 +0200 Subject: [PATCH] Refactor user handling to use helper classes --- adduser.php | 52 ++-------- admin.js | 13 --- auth.php | 66 +++++------- client/index.php | 33 ++---- config.default.php | 2 - download.php | 2 +- helpers/db.php | 48 +++++++++ helpers/user.php | 100 +++++++++++++++++++ index.php | 243 +++++++++++++++++++++------------------------ lang.php | 2 +- main.js | 13 +++ 11 files changed, 317 insertions(+), 257 deletions(-) create mode 100644 helpers/db.php create mode 100644 helpers/user.php diff --git a/adduser.php b/adduser.php index 1ccad89..57bc98d 100644 --- a/adduser.php +++ b/adduser.php @@ -18,7 +18,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - require_once("auth.php"); + require_once("auth.php"); // sets $mysqli, $user /** * Exit with xml response @@ -42,51 +42,17 @@ function exitWithStatus($isError, $errorMessage = NULL) { exit; } - /** - * Check if login is allowed - * @param string $login Login - */ - function checkUser($login) { - global $mysqli; - $sql = "SELECT id FROM users WHERE login = ?"; - $query = $mysqli->prepare($sql); - $query->bind_param('s', $login); - $query->execute(); - if ($query->errno) { - exitWithStatus(true, $query->error); - } - $query->store_result(); - if ($query->num_rows) { + $login = isset($_REQUEST['login']) ? trim($_REQUEST['login']) : NULL; + $hash = isset($_REQUEST['pass']) ? password_hash($_REQUEST['pass'], PASSWORD_DEFAULT) : NULL; + if ($user->isAdmin && !empty($login) && !empty($hash)) { + $newUser = new uUser($login); + if ($newUser->isValid) { exitWithStatus(true, $lang_userexists); } - $query->free_result(); - $query->close(); - } - - /** - * Add new user to database - * @param string $login Login - * @param string $hash Password hash - */ - function insertUser($login, $hash) { - global $mysqli; - $sql = "INSERT INTO users (login, password) VALUES (?, ?)"; - $query = $mysqli->prepare($sql); - $query->bind_param('ss', $login, $hash); - $query->execute(); - if ($query->errno) { - exitWithStatus(true, $query->error); - $isError = false; + if ($newUser->add($login, $hash) === false) { + exitWithStatus(true, $mysqli->error); } - $query->close(); - } - - $login = isset($_REQUEST['login']) ? trim($_REQUEST['login']) : NULL; - $hash = isset($_REQUEST['pass']) ? password_hash($_REQUEST['pass'], PASSWORD_DEFAULT) : NULL; - if ($admin && !empty($login) && !empty($hash)) { - checkUser($login); - insertUser($login, $hash); } exitWithStatus(false); - + ?> \ No newline at end of file diff --git a/admin.js b/admin.js index b118c38..6e22906 100644 --- a/admin.js +++ b/admin.js @@ -17,19 +17,6 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -function showModal(contentHTML) { - var div = document.createElement("div"); - div.setAttribute("id", "modal"); - div.innerHTML = ''; - document.body.appendChild(div); - var modalBody = document.getElementById('modal-body'); - modalBody.innerHTML = contentHTML; -} - -function removeModal() { - document.body.removeChild(document.getElementById('modal')); -} - function addUser() { var form = '
'; form += ''; diff --git a/auth.php b/auth.php index 8ca9908..c8a8295 100755 --- a/auth.php +++ b/auth.php @@ -17,46 +17,36 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -require_once("config.php"); -// if is set cookie overwrite config value -if (isset($_COOKIE["ulogger_api"])) { $mapapi = $_COOKIE["ulogger_api"]; } -if (isset($_COOKIE["ulogger_lang"])) { $lang = $_COOKIE["ulogger_lang"]; } -if (isset($_COOKIE["ulogger_units"])) { $units = $_COOKIE["ulogger_units"]; } -if (isset($_COOKIE["ulogger_interval"])) { $interval = $_COOKIE["ulogger_interval"]; } +require_once("helpers/config.php"); +$config = new uConfig(); + require_once("lang.php"); -$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); -if ($mysqli->connect_errno) { - if (defined('headless')) { - header('HTTP/1.1 503 Service Unavailable', true, 503); - } else { - printf("Connect failed: %s\n", $mysqli->connect_error); - } - exit(); -} -$mysqli->set_charset("utf8"); +require_once("helpers/db.php"); +$mysqli = uDb::getInstance(); +require_once($config::$rootDir . "/helpers/user.php"); session_name('ulogger'); session_start(); $sid = session_id(); // check for forced login to authorize admin in case of public access -$force_login = (isset($_REQUEST['force_login']) ? $_REQUEST['force_login'] : 0); +$force_login = (isset($_REQUEST['force_login']) ? $_REQUEST['force_login'] : false); if ($force_login) { - $require_authentication = 1; + $config::$require_authentication = true; } -$auth = (isset($_SESSION['auth']) ? $_SESSION['auth'] : NULL); -$admin = (isset($_SESSION['admin']) ? $_SESSION['admin'] : NULL); -if ($auth || $require_authentication || defined('headless')) { +$user = new uUser(); +$user->getFromSession(); +if (!$user->isValid && ($config::$require_authentication || defined('headless'))) { /* authentication */ - $user = (isset($_REQUEST['user']) ? $_REQUEST['user'] : ""); - $pass = (isset($_REQUEST['pass']) ? $_REQUEST['pass'] : ""); + $login = (isset($_REQUEST['user']) ? $_REQUEST['user'] : NULL); + $pass = (isset($_REQUEST['pass']) ? $_REQUEST['pass'] : NULL); $ssl = ((!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "" || $_SERVER['HTTPS'] == "off") ? "http" : "https"); $auth_error = (isset($_REQUEST['auth_error']) ? $_REQUEST['auth_error'] : 0); - // not authenticated and username not submited - // load form - if ((!$auth) && (!$user)){ + if (!$login){ + // not authenticated and username not submited + // load form if (defined('headless')) { header('HTTP/1.1 401 Unauthorized', true, 401); } else { @@ -94,19 +84,12 @@ function focus() { } $mysqli->close(); exit(); - } + } else { + // username submited + $user = new uUser($login); - // username submited - if ((!$auth) && ($user)){ - $query = $mysqli->prepare("SELECT id, login, password FROM users WHERE login=? LIMIT 1"); - $query->bind_param('s', $user); - $query->execute(); - $query->bind_result($rec_id, $rec_user, $rec_pass); - $query->fetch(); - $query->free_result(); //correct pass - - if (($user == $rec_user) && password_verify($pass, $rec_pass)) { + if ($user->isValid && $user->validPassword($pass)) { // login successful //delete old session $_SESSION = NULL; @@ -114,10 +97,7 @@ function focus() { // start new session session_name('ulogger'); session_start(); - if (($user == $admin_user) && !empty($admin_user)) { - $_SESSION['admin'] = $admin_user; - } - $_SESSION['auth'] = $rec_id; + $user->storeInSession(); $url = str_replace("//", "/", $_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME'])."/index.php"); header("Location: $ssl://$url"); exit(); @@ -130,15 +110,15 @@ function focus() { setcookie(session_name('ulogger'),'',time()-42000,'/'); } session_destroy(); - $mysqli->close(); if (defined('headless')) { header('HTTP/1.1 401 Unauthorized', true, 401); } else { $url = str_replace("//", "/", $_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME'])."/index.php"); header("Location: $ssl://$url$error"); } - exit(); } + $mysqli->close(); + exit(); } /* end of authentication */ } diff --git a/client/index.php b/client/index.php index d92859d..9296b82 100644 --- a/client/index.php +++ b/client/index.php @@ -24,43 +24,32 @@ function setError(&$response, $message) { } define("headless", true); -require_once("../auth.php"); +require_once("../auth.php"); // sets $mysqli, $user +$userid = $user->id; $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; -$userid = $_SESSION['auth']; - $response = [ 'error' => false ]; -$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); -if ($mysqli->connect_errno) { - setError($response, $mysqli->error); - $action = null; -} - switch ($action) { // action: authorize case "auth": break; - // action: adduser + // action: adduser (currently unused) case "adduser": $login = isset($_REQUEST['login']) ? $_REQUEST['login'] : NULL; $hash = isset($_REQUEST['password']) ? password_hash($_REQUEST['password'], PASSWORD_DEFAULT) : NULL; if (!empty($login) && !empty($hash)) { - $sql = "INSERT INTO users (login, password) VALUES (?, ?)"; - $query = $mysqli->prepare($sql); - $query->bind_param('ss', $login, $hash); - $query->execute(); - $userid = $mysqli->insert_id; - $query->close(); - if ($mysqli->errno) { - setError($response, $mysqli->error); - break; + $newUser = new uUser(); + $newId = $newUser->add($login, $hash); + if ($newId !== false) { + // return user id + $response['userid'] = $newId; + } else { + setError($response, "Server error"); } - // return user id - $response['userid'] = $userid; } else { - setError($response, "Empty login"); + setError($response, "Empty login or password"); } break; diff --git a/config.default.php b/config.default.php index e4d32c0..9ea42eb 100755 --- a/config.default.php +++ b/config.default.php @@ -21,8 +21,6 @@ // This is default configuration file. // Copy it to config.php and customize -$version = "0.1"; - // default map drawing framework // (gmaps = google maps, openlayers = openlayers/osm) //$mapapi = "gmaps"; diff --git a/download.php b/download.php index 58c4019..55da216 100755 --- a/download.php +++ b/download.php @@ -22,7 +22,7 @@ $userid = ((isset($_REQUEST["userid"]) && is_numeric($_REQUEST["userid"])) ? $_REQUEST["userid"] : 0); $trackid = ((isset($_REQUEST["trackid"]) && is_numeric($_REQUEST["trackid"])) ? $_REQUEST["trackid"] : 0); -if ($units=="imperial") { +if ($config::$units=="imperial") { $factor_kmh = 0.62; //to mph $unit_kmh = "mph"; $factor_m = 3.28; // to feet diff --git a/helpers/db.php b/helpers/db.php new file mode 100644 index 0000000..94063e3 --- /dev/null +++ b/helpers/db.php @@ -0,0 +1,48 @@ +connect_error) { + if (defined('headless')) { + header("HTTP/1.1 503 Service Unavailable"); + exit; + } + die("Database connection error (" . $this->connect_errno . ")"); + } + $this->set_charset('utf8'); + } + + // returns singleton instance + public static function getInstance() { + if (!self::$instance) { + $config = new uConfig(); + self::$instance = new self($config::$dbhost, $config::$dbuser, $config::$dbpass, $config::$dbname); + } + return self::$instance; + } +} +?> \ No newline at end of file diff --git a/helpers/user.php b/helpers/user.php new file mode 100644 index 0000000..4fa51ae --- /dev/null +++ b/helpers/user.php @@ -0,0 +1,100 @@ +prepare("SELECT id, login, password FROM users WHERE login = ? LIMIT 1"); + $stmt->bind_param('s', $login); + $stmt->execute(); + $stmt->bind_result($this->id, $this->login, $this->hash); + if ($stmt->fetch()) { + $this->isValid = true; + } + $stmt->close(); + $config = new uConfig(); + if (!empty($config::$admin_user) && $config::$admin_user == $this->login) { + $this->isAdmin = true; + } + } + } + + public function add($login, $hash) { + $userid = false; + if (!empty($login) && !empty($hash)) { + $sql = "INSERT INTO users (login, password) VALUES (?, ?)"; + $stmt = self::$db->prepare($sql); + $stmt->bind_param('ss', $login, $hash); + $stmt->execute(); + if (!self::$db->error && !$stmt->errno) { + $userid = self::$db->insert_id; + } + $stmt->close(); + } + return $userid; + } + + public function validPassword($password) { + return password_verify($password, $this->hash); + } + + public function storeInSession() { + $_SESSION['user'] = $this; + } + + public function getFromSession() { + if (isset($_SESSION['user'])) { + $sessionUser = $_SESSION['user']; + $this->id = $sessionUser->id; + $this->login = $sessionUser->login; + $this->hash = $sessionUser->hash; + $this->isAdmin = $sessionUser->isAdmin; + $this->isValid = $sessionUser->isValid; + } + } + + public function listAll() { + $query = "SELECT id, login FROM users ORDER BY login"; + $result = self::$db->query($query); + if ($result === false) { + return false; + } + $userArr = []; + while ($row = $result->fetch_assoc()) { + $userArr[$row['id']] = $row['login']; + } + $result->close(); + return $userArr; + } +} + + ?> \ No newline at end of file diff --git a/index.php b/index.php index f8383f1..3f9ada1 100755 --- a/index.php +++ b/index.php @@ -16,191 +16,169 @@ * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -require_once("auth.php"); - -if ($auth && !$admin && !$public_tracks) { - // only authorized user tracks - // get username - $query = "SELECT login FROM users WHERE id='$auth' LIMIT 1"; - $result = $mysqli->query($query); - $row = $result->fetch_assoc(); - $user = $row["login"]; - - // users - $user_form = ''.$lang_user.'
'.$user.' ('.$lang_logout.')'; +*/ +require_once ("auth.php"); +if ($user->isValid) { + $userHeader = $user->login . ' (' . $lang_logout . ')'; +} else { + $userHeader = '' . $lang_login . ''; } -else { +$lastUserId = NULL; +$userForm = ''; +if ($user->isAdmin || $config::$public_tracks) { // public access or admin user // prepare user select form - if ($admin) { - $user = $admin_user; - } - $user_form = ' - '.$lang_user.' '; - if ($auth) { - $user_form .= ' '.$user.' ('.$lang_logout.')'; - } else { - $user_form .= ' '.$lang_login.''; - } - $user_form .= ' + $userForm = ' +
' . $lang_user . '
'; } - // prepare track select form -$track_form = ' -'.$lang_track.'
+$trackForm = ' +' . $lang_track . '
- '.$lang_latest.'
+ ' . $lang_latest . '
'; // map api select form -$api_form = ' -'.$lang_api.'
+$apiForm = ' +' . $lang_api . '
'; - // language select form -$lang_form = ' -'.$lang_language.'
+$langForm = ' +' . $lang_language . '
'; // units select form -$units_form = ' -'.$lang_units.'
+$unitsForm = ' +' . $lang_units . '
'; // admin menu -$admin_menu = ''; -$admin_script = ''; -if ($admin) { - $admin_menu = ' +$adminMenu = ''; +$adminScript = ''; +if ($user->isAdmin) { + $adminMenu = '
- '.$lang_adminmenu.'
- '.$lang_adduser.'
+ ' . $lang_adminmenu . '
+ ' . $lang_adduser . '
'; - $admin_script = ''; + $adminScript = ''; } - -print -' +print ' - '.$lang_title.' + ' . $lang_title . ' '; -if ($mapapi == "gmaps") { - print -' +if ($config::$mapapi == "gmaps") { + print ' '; -} -else { - print -' +} else { + print ' '; } print ' - '.$admin_script.' + ' . $adminScript . ' +