From b04b2fb48027acbee441eebd0a5ee01b9e9e7b0e Mon Sep 17 00:00:00 2001 From: djpbessems Date: Wed, 23 Jan 2019 22:08:30 +0100 Subject: [PATCH] Rudimentary implementation of authentication processflow --- include/lucidAuth.functions.php | 46 ++++++++++++++++++++++++---- include/lucidAuth.template.php | 3 +- lucidAuth.config.php.example | 2 +- public/lucidAuth.login.php | 16 ++++++++-- public/lucidAuth.validateRequest.php | 21 ++++++++----- public/misc/script.index.js | 3 +- 6 files changed, 71 insertions(+), 20 deletions(-) diff --git a/include/lucidAuth.functions.php b/include/lucidAuth.functions.php index 0b3f5ec..805268b 100644 --- a/include/lucidAuth.functions.php +++ b/include/lucidAuth.functions.php @@ -5,6 +5,16 @@ if (!file_exists($configurationFile)) { throw new Exception(sprintf('Missing config file. Please rename \'%1$s.example\' to \'%1$s\' and edit it to reflect your setup.', explode('../', $configurationFile)[1])); } $settings = include_once($configurationFile); +try { +# switch ($settings->Database['Driver']) { +# case 'sqlite': +# $database = new PDO('sqlite:' . $settings->Database['Path']); + $pdoDB = new PDO('sqlite:' . $settings->Sqlite['Path']); +# } +} +catch (Exception $e) { + throw new Exception(sprintf('Unable to connect to database \'%1$s\'', $settings->Sqlite['Path'])); +} function authenticateLDAP (string $username, string $password) { global $settings; @@ -45,21 +55,45 @@ function authenticateLDAP (string $username, string $password) { function storeToken (string $username, string $password, object $cookie) { global $settings; - } -function retrieveToken (string $username, string $foo) { +function retrieveTokenFromDB (string $username, string $foo) { global $settings; } -function validateCookie (int $expiration, string $username, string $securetoken) { -# $_COOKIE['Exp'], $_COOKIE['Sub'], $_COOKIE['JWT'] +function validateToken (array $cookieData) { global $settings; - If ($expiration > time()) { - #moo + try { + $jwtPayload = JWT::decode($cookieData['token'], base64_decode($settings->JWT['PrivateKey_base64']), $settings->JWT['Algorithm']); + } catch (Exception $e) { + // Invalid token, inform client (client should handle discarding invalid token) + return ['status' => 'Fail', 'reason' => '3']; } + + $pdoQuery = $pdoDB->prepare(' + SELECT SecureToken.Payload + FROM SecureToken + LEFT JOIN User + ON (User.Id=SecureToken.UserId) + WHERE User.Username = :username + '); + $pdoQuery->execute([ + 'username' => ($_COOKIE['Sub'] ?? "Danny") + ]); + foreach($pdoQuery->fetchAll(PDO::FETCH_ASSOC) as $row) { + $tokens[] = $row['Payload']; + } + print_r($tokens); +# if ($pdoResult['Username']) + + + If ($cookieData['Exp'] < time()) { + // Expired cookie (shouldn't the browser disregard it?) + return ['status' => 'Fail', 'reason' => '3']; + } + } ?> \ No newline at end of file diff --git a/include/lucidAuth.template.php b/include/lucidAuth.template.php index d972ec6..e6db275 100644 --- a/include/lucidAuth.template.php +++ b/include/lucidAuth.template.php @@ -69,7 +69,8 @@ $contentLayout['login'] = <<
  • - + +
  •   diff --git a/lucidAuth.config.php.example b/lucidAuth.config.php.example index 9165393..46768b6 100644 --- a/lucidAuth.config.php.example +++ b/lucidAuth.config.php.example @@ -21,7 +21,7 @@ return (object) array( 'DomainNames' => ['*.subdomain.domain.{(tld1|tld2)}'], 'Sqlite' => [ - 'Path' => '../config/lucidAuth.sqlite.db' + 'Path' => '../data/lucidAuth.sqlite.db' // Relative path to the location where the database should be stored ], diff --git a/public/lucidAuth.login.php b/public/lucidAuth.login.php index 3dc7af2..73f36fb 100644 --- a/public/lucidAuth.login.php +++ b/public/lucidAuth.login.php @@ -3,13 +3,23 @@ include_once('../include/lucidAuth.functions.php'); - echo $settings->Debug['Verbose']; - if ($_POST['do'] == 'login') { $result = authenticateLDAP($_POST['username'], $_POST['password']); if ($result['status'] == 'Success') { + // Convert base64 encoded string back from JSON; + // forcing it into an associative array (instead of javascript's default StdClass object) + try { + $proxyHeaders = json_decode(base64_decode($_POST['ref']), JSON_OBJECT_AS_ARRAY); + } + catch (Exception $e) { + // Since this request is only ever called through an AJAX-request; return JSON object + echo '{"Result":"Fail","Reason":"Original request URI lost in transition"}' . PHP_EOL; + exit; + } + $originalUri = $proxyHeaders['XForwardedProto'] . '://' . $proxyHeaders['XForwardedHost'] . $proxyHeaders['XForwardedUri']; + // Since this request is only ever called through an AJAX-request; return JSON object - echo '{"Result":"Success","Location":""}' . PHP_EOL; + echo '{"Result":"Success","Location":"' . $originalUri . '"}' . PHP_EOL; } else { switch ($result['reason']) { case '1': diff --git a/public/lucidAuth.validateRequest.php b/public/lucidAuth.validateRequest.php index c0d88a1..336d594 100644 --- a/public/lucidAuth.validateRequest.php +++ b/public/lucidAuth.validateRequest.php @@ -16,7 +16,10 @@ }, ARRAY_FILTER_USE_KEY); // For debugging purposes - enable it in ../lucidAuth.config.php - if ($settings->Debug['LogToFile']) file_put_contents('../requestHeaders.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- ' . (json_encode($proxyHeaders, JSON_FORCE_OBJECT) . PHP_EOL), FILE_APPEND); + if ($settings->Debug['LogToFile']) { + file_put_contents('../requestHeaders.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- ' . (json_encode($proxyHeaders, JSON_FORCE_OBJECT)) . PHP_EOL, FILE_APPEND); + file_put_contents('../requestHeaders.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --+ ' . (base64_encode(json_encode($proxyHeaders))) . PHP_EOL, FILE_APPEND); + } # if (sizeof($proxyHeaders) == 0) { if (False) { @@ -25,16 +28,18 @@ exit; } -# if (validateToken($_COOKIE['Exp'], $_COOKIE['Sub'], $_COOKIE['JWT']) != True) { - if (False) { - // No or invalid authentication token found, redirecting to loginpage - header("HTTP/1.1 401 Unauthorized"); -#remember to include cookies/headers/something - header("Location: lucidAuth.login.php"); - } else { + if ((!empty($_COOKIE['Exp']) && !empty($_COOKIE['Sub']) && !empty($_COOKIE['JWT'])) && validateToken([ + 'Exp' => $_COOKIE['Exp'], + 'Sub' => $_COOKIE['Sub'], + 'JWT' => $_COOKIE['JWT'] + ])['status'] == "Success") { // Valid authentication token found header("HTTP/1.1 202 Accepted"); exit; + } else { + // No cookie containing valid authentication token found, redirecting to loginpage + header("HTTP/1.1 401 Unauthorized"); + header("Location: lucidAuth.login.php?ref=" . base64_encode(json_encode($proxyHeaders))); } ?> \ No newline at end of file diff --git a/public/misc/script.index.js b/public/misc/script.index.js index e1f4254..e0c925e 100644 --- a/public/misc/script.index.js +++ b/public/misc/script.index.js @@ -16,7 +16,8 @@ $(document).ready(function(){ $.post("lucidAuth.login.php", { do: "login", username: $('#username').val(), - password: $('#password').val() + password: $('#password').val(), + ref: $('#ref').val() }) .done(function(data,status) { try {