Skip to content

Commit

Permalink
Refactor user handling to use helper classes
Browse files Browse the repository at this point in the history
  • Loading branch information
bfabiszewski committed Apr 6, 2017
1 parent 1052b31 commit d93bbd4
Show file tree
Hide file tree
Showing 11 changed files with 317 additions and 257 deletions.
52 changes: 9 additions & 43 deletions adduser.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);

?>
13 changes: 0 additions & 13 deletions admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '<div id="modal-header"><button type="button" onclick="removeModal()">&times;</button></div><div id="modal-body"></div>';
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 id="userForm" method="post" onsubmit="submitUser(); return false">';
form += '<label><b>' + lang_username + '</b></label><input type="text" placeholder="' + lang_usernameenter + '" name="login" required>';
Expand Down
66 changes: 23 additions & 43 deletions auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -94,30 +84,20 @@ 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;
session_destroy();
// 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();
Expand All @@ -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 */
}
Expand Down
33 changes: 11 additions & 22 deletions client/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
2 changes: 0 additions & 2 deletions config.default.php
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
2 changes: 1 addition & 1 deletion download.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 48 additions & 0 deletions helpers/db.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/* μlogger
*
* Copyright(C) 2017 Bartek Fabiszewski (www.fabiszewski.net)
*
* This is free software; you can redistribute it and/or modify it under
* the terms of the GNU Library General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* 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 (__DIR__ . "/config.php");
class uDb extends mysqli {
// singleton instance
protected static $instance;

// private constuctor
private function __construct($host, $user, $pass, $name) {
parent::__construct($host, $user, $pass, $name);
if ($this->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;
}
}
?>
Loading

0 comments on commit d93bbd4

Please sign in to comment.