diff --git a/auth.php b/auth.php
deleted file mode 100755
index 5ee2d45..0000000
--- a/auth.php
+++ /dev/null
@@ -1,142 +0,0 @@
-.
- */
-
-if (defined('headless')) {
- if (ob_get_level()) {
- ob_end_clean();
- }
- ini_set('display_errors', '0');
-}
-define('ROOT_DIR', __DIR__);
-require_once(ROOT_DIR . "/helpers/config.php");
-require_once(ROOT_DIR . "/lang.php");
-require_once(ROOT_DIR . "/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'] : false;
-if ($force_login) {
- uConfig::$require_authentication = true;
-}
-
-$user = new uUser();
-$user->getFromSession();
-if (!$user->isValid && (uConfig::$require_authentication || defined('client'))) {
- /* authentication */
- $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'] : false;
-
- if (!$login) {
- // not authenticated and username not submited
- // load form
- if (defined('headless')) {
- header('WWW-Authenticate: OAuth realm="users@ulogger"');
- header('HTTP/1.1 401 Unauthorized', true, 401);
- } else {
- print
- '
-
-
- ' . $lang["title"] . '
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
' . $lang["title"] . '
-
' . $lang["private"] . '
-
-
' . (($auth_error) ? $lang["authfail"] : "") . '
-
-
- ';
- }
- exit();
- } else {
- // username submited
- $user = new uUser($login);
-
- //correct pass
- if ($user->isValid && $user->validPassword($pass)) {
- // login successful
- //delete old session
- $_SESSION = NULL;
- session_destroy();
- // start new session
- session_name('ulogger');
- session_start();
- $user->storeInSession();
- if (!defined('client')) {
- // redirect
- $url = str_replace("//", "/", $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . "/index.php");
- header("Location: $ssl://$url");
- exit();
- }
- } else {
- // unsuccessful
- $error = "?auth_error=1";
- if ($force_login) { $error .= "&force_login=1"; }
- // destroy session
- $_SESSION = NULL;
- if (isset($_COOKIE[session_name('ulogger')])) {
- setcookie(session_name('ulogger'), '', time() - 42000, '/');
- }
- session_destroy();
- if (defined('headless')) {
- header('WWW-Authenticate: OAuth realm="users@ulogger"');
- 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();
- }
- }
- /* end of authentication */
-}
-?>
diff --git a/client/index.php b/client/index.php
index 5195e94..c57eb10 100644
--- a/client/index.php
+++ b/client/index.php
@@ -17,101 +17,113 @@
* along with this program; if not, see .
*/
-/**
- * Set response error status and message
- *
- * @param array $response Respons
- * @param string $message Message
- */
-function setError(&$response, $message) {
- $response['error'] = true;
- $response['message'] = $message;
-}
-
-define("headless", true);
-define("client", true);
-require_once(dirname(__DIR__) . "/auth.php"); // sets $user
-
-$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
-$response = [ 'error' => false ];
-
-switch ($action) {
- // action: authorize
- case "auth":
- break;
-
- // action: adduser (currently unused)
- case "adduser":
- if (!$user->isAdmin) {
- setError($response, "User not authorized");
- break;
- }
- $login = isset($_REQUEST['login']) ? $_REQUEST['login'] : NULL;
- $pass = isset($_REQUEST['password']) ? $_REQUEST['password'] : NULL;
- if (!empty($login) && !empty($pass)) {
- $newId = uUser::add($login, $pass);
- if ($newId !== false) {
- // return user id
- $response['userid'] = $newId;
- } else {
- setError($response, "Server error");
- }
- } else {
- setError($response, "Empty login or password");
- }
- break;
-
- // action: addtrack
- case "addtrack":
- $trackName = isset($_REQUEST['track']) ? $_REQUEST['track'] : NULL;
- if (empty($trackName)) {
- setError($response, "Missing required parameter");
- break;
- }
- require_once(ROOT_DIR . "/helpers/track.php");
- $trackId = uTrack::add($user->id, $trackName);
- if ($trackId === false) {
- setError($response, "Server error");
- break;
- }
- // return track id
- $response['trackid'] = $trackId;
- break;
-
- // action: addposition
- case "addpos":
- $lat = isset($_REQUEST["lat"]) ? $_REQUEST["lat"] : NULL;
- $lon = isset($_REQUEST["lon"]) ? $_REQUEST["lon"] : NULL;
- $timestamp = isset($_REQUEST["time"]) ? $_REQUEST["time"] : NULL;
- $altitude = isset($_REQUEST["altitude"]) ? $_REQUEST["altitude"] : NULL;
- $speed = isset($_REQUEST["speed"]) ? $_REQUEST["speed"] : NULL;
- $bearing = isset($_REQUEST["bearing"]) ? $_REQUEST["bearing"] : NULL;
- $accuracy = isset($_REQUEST["accuracy"]) ? $_REQUEST["accuracy"] : NULL;
- $provider = isset($_REQUEST["provider"]) ? $_REQUEST["provider"] : NULL;
- $comment = isset($_REQUEST["comment"]) ? $_REQUEST["comment"] : NULL;
- $imageId = isset($_REQUEST["imageid"]) ? $_REQUEST["imageid"] : NULL;
- $trackId = isset($_REQUEST["trackid"]) ? $_REQUEST["trackid"] : NULL;
-
- if (!is_numeric($lat) || !is_numeric($lon) || !is_numeric($timestamp) || !is_numeric($trackId)) {
- setError($response, "Missing required parameter");
- break;
- }
-
- require_once(ROOT_DIR . "/helpers/position.php");
- $positionId = uPosition::add($user->id, $trackId,
- $timestamp, $lat, $lon, $altitude, $speed, $bearing, $accuracy, $provider, $comment, $imageId);
-
- if ($positionId === false) {
- setError($response, "Server error");
- }
- break;
-
- default:
- setError($response, "Unknown command");
- break;
+ /**
+ * Exit with error status and message
+ *
+ * @param string $message Message
+ */
+ function exitWithError($message) {
+ $response = [];
+ $response['error'] = true;
+ $response['message'] = $message;
+ header('Content-Type: application/json');
+ echo json_encode($response);
+ exit();
+ }
+
+ /**
+ * Exit with success status
+ *
+ * @param array $params Optional params
+ * @return void
+ */
+ function exitWithSuccess($params = []) {
+ $response = [];
+ $response['error'] = false;
+ header('Content-Type: application/json');
+ echo json_encode(array_merge($response, $params));
+ exit();
+ }
+
+ require_once(dirname(__DIR__) . "/helpers/auth.php");
+
+ $auth = new uAuth();
+ if (!$auth->isAuthenticated()) {
+ $auth->sendUnauthorizedHeader();
+ exitWithError("Unauthorized");
+ }
+
+ $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
+
+ switch ($action) {
+ // action: authorize
+ case "auth":
+ exitWithSuccess();
+ break;
+
+ // action: adduser (currently unused)
+ case "adduser":
+ if (!$auth->user->isAdmin) {
+ exitWithError("Not allowed");
+ }
+ $login = isset($_REQUEST['login']) ? $_REQUEST['login'] : NULL;
+ $pass = isset($_REQUEST['password']) ? $_REQUEST['password'] : NULL;
+ if (empty($login) || empty($pass)) {
+ exitWithError("Empty login or password");
+ }
+ $newId = uUser::add($login, $pass);
+ if ($newId === false) {
+ exitWithError("Server error");
+ }
+ exitWithSuccess(['userid'=> $newId]);
+ break;
+
+ // action: addtrack
+ case "addtrack":
+ $trackName = isset($_REQUEST['track']) ? $_REQUEST['track'] : NULL;
+ if (empty($trackName)) {
+ exitWithError("Missing required parameter");
+ }
+ require_once(ROOT_DIR . "/helpers/track.php");
+ $trackId = uTrack::add($auth->user->id, $trackName);
+ if ($trackId === false) {
+ exitWithError("Server error");
+ }
+ // return track id
+ exitWithSuccess(['trackid' => $trackId]);
+ break;
+
+ // action: addposition
+ case "addpos":
+ $lat = isset($_REQUEST["lat"]) ? $_REQUEST["lat"] : NULL;
+ $lon = isset($_REQUEST["lon"]) ? $_REQUEST["lon"] : NULL;
+ $timestamp = isset($_REQUEST["time"]) ? $_REQUEST["time"] : NULL;
+ $altitude = isset($_REQUEST["altitude"]) ? $_REQUEST["altitude"] : NULL;
+ $speed = isset($_REQUEST["speed"]) ? $_REQUEST["speed"] : NULL;
+ $bearing = isset($_REQUEST["bearing"]) ? $_REQUEST["bearing"] : NULL;
+ $accuracy = isset($_REQUEST["accuracy"]) ? $_REQUEST["accuracy"] : NULL;
+ $provider = isset($_REQUEST["provider"]) ? $_REQUEST["provider"] : NULL;
+ $comment = isset($_REQUEST["comment"]) ? $_REQUEST["comment"] : NULL;
+ $imageId = isset($_REQUEST["imageid"]) ? $_REQUEST["imageid"] : NULL;
+ $trackId = isset($_REQUEST["trackid"]) ? $_REQUEST["trackid"] : NULL;
+
+ if (!is_numeric($lat) || !is_numeric($lon) || !is_numeric($timestamp) || !is_numeric($trackId)) {
+ exitWithError("Missing required parameter");
+ }
+
+ require_once(ROOT_DIR . "/helpers/position.php");
+ $positionId = uPosition::add($auth->user->id, $trackId,
+ $timestamp, $lat, $lon, $altitude, $speed, $bearing, $accuracy, $provider, $comment, $imageId);
+
+ if ($positionId === false) {
+ exitWithError("Server error");
+ }
+ exitWithSuccess();
+ break;
+
+ default:
+ exitWithError("Unknown command");
+ break;
}
-header('Content-Type: application/json');
-echo json_encode($response);
-exit();
?>
\ No newline at end of file
diff --git a/helpers/auth.php b/helpers/auth.php
new file mode 100644
index 0000000..e8b49c5
--- /dev/null
+++ b/helpers/auth.php
@@ -0,0 +1,187 @@
+.
+ */
+
+ define('ROOT_DIR', dirname(__DIR__));
+ require_once(ROOT_DIR . "/helpers/user.php");
+
+ /**
+ * Authentication
+ */
+ class uAuth {
+
+ private $isAuthenticated = false;
+ private $isLoginAttempt = false;
+ public $user = null;
+
+ public function __construct() {
+ $this->sessionStart();
+
+ $user = (new uUser())->getFromSession();
+ if ($user->isValid) {
+ $this->setAuthenticated($user);
+ } else {
+ $this->checkLogin();
+ }
+ }
+
+ /**
+ * Is user authenticated
+ *
+ * @return boolean True if authenticated, false otherwise
+ */
+ public function isAuthenticated() {
+ return $this->isAuthenticated;
+ }
+
+ /**
+ * Has user attempted to log in
+ *
+ * @return boolean True if attempted login, false otherwise
+ */
+ public function isLoginAttempt() {
+ return $this->isLoginAttempt;
+ }
+
+ /**
+ * Is authenticated user admin
+ *
+ * @return boolean True if admin, false otherwise
+ */
+ public function isAdmin() {
+ return ($this->isAuthenticated && $this->user->isAdmin);
+ }
+
+ /**
+ * Start php session
+ *
+ * @return void
+ */
+ private function sessionStart() {
+ session_name("ulogger");
+ session_start();
+ }
+
+ /**
+ * Terminate php session
+ *
+ * @return void
+ */
+ private function sessionEnd() {
+ $_SESSION = [];
+ if (ini_get("session.use_cookies")) {
+ $params = session_get_cookie_params();
+ setcookie(session_name('ulogger'), '', time() - 42000,
+ $params["path"], $params["domain"],
+ $params["secure"], $params["httponly"]
+ );
+ }
+ session_destroy();
+ }
+
+ /**
+ * Clean session variables
+ *
+ * @return void
+ */
+ private function sessionCleanup() {
+ $_SESSION = [];
+ }
+
+ /**
+ * Mark as authenticated, set user
+ *
+ * @param [type] $user
+ * @return void
+ */
+ private function setAuthenticated($user) {
+ $this->isAuthenticated = true;
+ $this->user = $user;
+ }
+
+ /**
+ * Process log in request
+ *
+ * @return void
+ */
+ private function checkLogin() {
+ $action = isset($_REQUEST["action"]) ? $_REQUEST["action"] : NULL;
+ $login = isset($_REQUEST["user"]) ? $_REQUEST["user"] : NULL;
+ $pass = isset($_REQUEST["pass"]) ? $_REQUEST["pass"] : NULL;
+
+ if ($action == "auth" && !is_null($login) && !is_null($pass)) {
+ $this->isLoginAttempt = true;
+ if (!empty($login) && !empty($pass)) {
+ $user = new uUser($login);
+ if ($user->isValid && $user->validPassword($pass)) {
+ $this->setAuthenticated($user);
+ $this->sessionCleanup();
+ $user->storeInSession();
+ }
+ }
+ }
+ }
+
+ /**
+ * Log out with redirect
+ *
+ * @param string $path URL path
+ * @return void
+ */
+ public function logOutWithRedirect($path = NULL) {
+ $this->sessionEnd();
+ $this->exitWithRedirect($path);
+ }
+
+ /**
+ * Send 401 headers
+ *
+ * @return void
+ */
+ public function sendUnauthorizedHeader() {
+ header('WWW-Authenticate: OAuth realm="users@ulogger"');
+ header('HTTP/1.1 401 Unauthorized', true, 401);
+ }
+
+ /**
+ * Send 401 headers and exit
+ *
+ * @return void
+ */
+ public function exitWithUnauthorized() {
+ $this->sendUnauthorizedHeader();
+ exit();
+ }
+
+ /**
+ * Redirect browser and exit
+ *
+ * @param string $path Redirect URL path
+ * @return void
+ */
+ public function exitWithRedirect($path = NULL) {
+ $ssl = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "" || $_SERVER['HTTPS'] == "off") ? "http" : "https";
+ $url = $_SERVER['HTTP_HOST'];
+ if (is_null($path)) {
+ $path = dirname($_SERVER['SCRIPT_NAME']) . "/";
+ }
+ $url = str_replace("//", "/", $url . $path);
+ header("Location: $ssl://$url");
+ exit();
+ }
+ }
\ No newline at end of file
diff --git a/helpers/db.php b/helpers/db.php
index 2504bd6..eb57a03 100644
--- a/helpers/db.php
+++ b/helpers/db.php
@@ -50,10 +50,7 @@
public function __construct($host, $user, $pass, $name, $port = null, $socket = null) {
@parent::__construct($host, $user, $pass, $name, $port, $socket);
if ($this->connect_error) {
- if (defined('headless')) {
- header("HTTP/1.1 503 Service Unavailable");
- exit;
- }
+ header("HTTP/1.1 503 Service Unavailable");
die("Database connection error (" . $this->connect_error . ")");
}
$this->set_charset('utf8');
diff --git a/helpers/user.php b/helpers/user.php
index 474c736..e8cf1bc 100644
--- a/helpers/user.php
+++ b/helpers/user.php
@@ -173,7 +173,7 @@
/**
* Fill uUser object properties from session data
- * @return uPosition Self
+ * @return uUser
*/
public function getFromSession() {
if (isset($_SESSION['user'])) {
diff --git a/index.php b/index.php
index fbd70c8..5da234e 100755
--- a/index.php
+++ b/index.php
@@ -17,14 +17,26 @@
* along with this program; if not, see .
*/
- require_once(__DIR__ . "/auth.php"); // sets $user
+ require_once(__DIR__ . "/helpers/auth.php");
+ require_once(ROOT_DIR . "/helpers/config.php");
require_once(ROOT_DIR . "/helpers/position.php");
require_once(ROOT_DIR . "/helpers/track.php");
require_once(ROOT_DIR . "/helpers/utils.php");
+ require_once(ROOT_DIR . "/lang.php");
+
+ $auth = new uAuth();
+
+ if (!$auth->isAuthenticated() && $auth->isLoginAttempt()) {
+ $auth->exitWithRedirect("/login.php?auth_error=1");
+ }
+ if (!$auth->isAuthenticated() && uConfig::$require_authentication) {
+ $auth->exitWithRedirect("/login.php");
+ }
+
$displayUserId = NULL;
$usersArr = [];
- if ($user->isAdmin || uConfig::$public_tracks) {
+ if ($auth->isAdmin() || uConfig::$public_tracks) {
// public access or admin user
// get last position user
$lastPosition = uPosition::getLast();
@@ -34,9 +46,9 @@
}
// populate users array (for