feat(session): check for a valid session using function in session.php

This commit is contained in:
eapl.mx 2024-12-26 11:56:44 -06:00
parent 57737e8cd4
commit 865b0d7e78
No known key found for this signature in database
11 changed files with 85 additions and 104 deletions

View file

@ -39,13 +39,13 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## 🛠 Installation and setup ## 🛠 Installation and setup
0. You need to have a webhosting with **PHP 8** and perferable running Apache or similar for timeline to work. 0. You need to have a webhosting with **PHP 8** and perferable running Apache or similar for timeline to work.
> There are free options, but I would suggest that you pay for your hosting and also get a nice domain, so you have more ownership over your data and online idetenty. > There are free options, but I would suggest that you pay for your hosting and also get a nice domain, so you have more ownership over your data and online idetenty.
1. Download the code from https://github.com/sorenpeter/timeline as a zip 1. Download the code from https://github.com/sorenpeter/timeline as a zip
2. Upload the content of the zip to you webhosting using a FTP client 2. Upload the content of the zip to you webhosting using a FTP client
- The default would be to put eveything from within the timeline-main folder in the root so you will have: - The default would be to put eveything from within the timeline-main folder in the root so you will have:
``` ```
@ -66,7 +66,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### Webfinger endpoint setup ### Webfinger endpoint setup
6. For allowing others to look you on using webfinger, you need to move the `.well-known` folder from within the `_webfinger_endpoint` to the root of your domain, so it is accesable from www.example.net/.well-know/webfinger 6. For allowing others to look you on using webfinger, you need to move the `.well-known` folder from within the `_webfinger_endpoint` to the root of your domain, so it is accesable from www.example.net/.well-know/webfinger
7. You also need to edit the `index.php` file wihtin the `.well-know/webfinger` folder and set the correct path for you timeline installation in `$timeline_dir` variable. 7. You also need to edit the `index.php` file wihtin the `.well-know/webfinger` folder and set the correct path for you timeline installation in `$timeline_dir` variable.
@ -84,6 +84,8 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## 🐞 Bugs to fix ## 🐞 Bugs to fix
- [x] (2024-11-30) Fix issues with parsing markdown vs. twtxt syntax (replaceed slimdown with Parsedown, supporting lists, block quotes, code/blocks, links, images) - [x] (2024-11-30) Fix issues with parsing markdown vs. twtxt syntax (replaceed slimdown with Parsedown, supporting lists, block quotes, code/blocks, links, images)
- [x] (2024-12-26) Extend session duration for 30 days
- [ ] (2024-12-26) Read the config.ini in a centralized place and add validations useful when installing or upgrading `timeline`.
## 🚀 Features to code ## 🚀 Features to code
@ -97,7 +99,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 🙏 Credits / shoutouts # 🙏 Credits / shoutouts
## Ideas and inspiration ## Ideas and inspiration
- [twtxt](https://twtxt.readthedocs.io) - The original decentralised, minimalist microblogging service for hackers - [twtxt](https://twtxt.readthedocs.io) - The original decentralised, minimalist microblogging service for hackers
@ -109,7 +111,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- [twtxt-php](https://github.com/eapl-gemugami/twtxt-php) - A minimalistic and personal PHP site for your twtxt microblogging. - [twtxt-php](https://github.com/eapl-gemugami/twtxt-php) - A minimalistic and personal PHP site for your twtxt microblogging.
- [Slimdown](https://github.com/jbroadway/slimdown) - A simple regex-based Markdown parser in PHP. - [Slimdown](https://github.com/jbroadway/slimdown) - A simple regex-based Markdown parser in PHP.
- Tag cloud feature is based on php code by [Domingos Faria](https://social.dfaria.eu/search) - Tag cloud feature is based on php code by [Domingos Faria](https://social.dfaria.eu/search)

View file

@ -1 +1 @@
2024.12.23 2024.12.26

View file

@ -32,7 +32,7 @@ session_start([
function hasValidSession(): bool { function hasValidSession(): bool {
# If short lived session is valid # If short lived session is valid
if (isset($_SESSION['session_expiration'])) { if (isset($_SESSION['session_expiration']) && $_SESSION['session_expiration'] > time()) {
return true; return true;
} }
@ -62,23 +62,21 @@ function getCookieData() {
$config = parse_ini_file('private/config.ini'); $config = parse_ini_file('private/config.ini');
# The cookie data contains the actual data w/ the hash concatonated to the end, # The cookie data contains the actual data w/ the hash concatenated to the end,
# since the hash is a fixed length, we can extract the last hash_length chars # since the hash is a fixed length, we can extract the last hash_length chars
# to get the hash. # to get the hash.
$hash = substr($raw, strlen($raw) - HASH_LENGTH, HASH_LENGTH); $hash = substr($raw, strlen($raw) - HASH_LENGTH, HASH_LENGTH);
$data = substr($raw, 0, - (HASH_LENGTH)); $data = substr($raw, 0, - (HASH_LENGTH));
# Calculate what the hash should be, based on the data. If the data has not been # Calculate the expected hash from the data. If the data has not been
# tampered with, $hash and $hash_calculated will be the same # tampered with, $hash and $hash_calculated will be the same
$hash_calculated = hash_hmac(HASH_ALGORITHM, $data, $config['secret_key']); $hash_calculated = hash_hmac(HASH_ALGORITHM, $data, $config['secret_key']);
# If we calculate a different hash, we can't trust the data.
if ($hash_calculated !== $hash) { if ($hash_calculated !== $hash) {
#echo "Different HASH"; #echo "Different HASH. Tempered data?";
return False; return False;
} }
# Is it expired ?
if (intval($data) < time()) { if (intval($data) < time()) {
#echo "Cookie expired"; #echo "Cookie expired";
return False; return False;
@ -91,7 +89,7 @@ function makePersistentCookie() {
$config = parse_ini_file('private/config.ini'); $config = parse_ini_file('private/config.ini');
$cookieExpiry = EXPIRATION_DAYS * 24 * 60 * 60 + time(); # X days $cookieExpiry = EXPIRATION_DAYS * 24 * 60 * 60 + time(); # X days
#$cookieExpiry = 10 + time(); # Debug value - 5 minutes #$cookieExpiry = 10 + time(); # Debug value - 10 seconds
# Calculate a hash for the data and append it to the end of the data string # Calculate a hash for the data and append it to the end of the data string
$cookieValue = strval($cookieExpiry); $cookieValue = strval($cookieExpiry);
@ -123,6 +121,9 @@ function isSavedCookieValid() {
return false; return false;
} }
# @eapl As it's implemented, the user has to login again in 30 days
# since the first login, which I think is a good compromise.
# Refresh session # Refresh session
$_SESSION['session_expiration'] = intval($cookieExpiry); $_SESSION['session_expiration'] = intval($cookieExpiry);

View file

@ -5,9 +5,12 @@ require_once 'libs/persistent_session.php';
$config = parse_ini_file('private/config.ini'); $config = parse_ini_file('private/config.ini');
$passwordInConfig = $config['password']; $passwordInConfig = $config['password'];
# TODO: Replace using $_SESSION['password'] in other files function checkValidSessionOrRedirectToLogin() {
# to check for a valid session, as in 'new_twt.php' if (!hasValidSession()) {
# Use hasValidSession() instead header('Location: ./login');
exit();
}
}
if (isset($_POST['submit_pass']) && $_POST['pass']) { if (isset($_POST['submit_pass']) && $_POST['pass']) {
$passwordInForm = $_POST['pass']; $passwordInForm = $_POST['pass'];

View file

@ -39,7 +39,7 @@
if (isset($_SESSION['password'])) { if (isset($_SESSION['password'])) {
echo ' | <a href="' . $baseURL . '/new?hash=' . $twt->hash . '">Reply</a>'; echo ' | <a href="' . $baseURL . '/new?hash=' . $twt->hash . '">Reply</a>';
} }
?> ?>
<!-- (<a href="new_twt.php?hash=<?=$twt->hash?>">via email</a>) TODO: mailto-link --> <!-- (<a href="new_twt.php?hash=<?=$twt->hash?>">via email</a>) TODO: mailto-link -->
@ -49,9 +49,8 @@
</article> </article>
<?php } <?php }
require_once 'libs/session.php';
if (!isset($_SESSION['password'])) { if (!hasValidSession()) {
echo '<center><a href="mailto:' . $config['email'] . '?subject=RE: ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '" class="button">Comment via email</a></center>'; echo '<center><a href="mailto:' . $config['email'] . '?subject=RE: ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '" class="button">Comment via email</a></center>';
} }
?>

View file

@ -8,16 +8,13 @@ require_once('libs/twtxt.php');
require_once('libs/hash.php'); require_once('libs/hash.php');
*/ */
require_once("partials/base.php"); require_once "partials/base.php";
require_once "libs/session.php";
checkValidSessionOrRedirectToLogin();
$config = parse_ini_file('private/config.ini'); $config = parse_ini_file('private/config.ini');
if (!isset($_SESSION['password'])) {
header('Location: ./login');
exit();
}
$max_execution_time = intval($config['max_execution_time']); $max_execution_time = intval($config['max_execution_time']);
if ($max_execution_time < 1) { if ($max_execution_time < 1) {
$max_execution_time = 1; $max_execution_time = 1;
@ -69,15 +66,15 @@ foreach ($fileLines as $currentLine) {
$i = 1; $i = 1;
$total = count($twtFollowingList); $total = count($twtFollowingList);
foreach ($twtFollowingList as $following) { foreach ($twtFollowingList as $following) {
$float = $i/$total; $float = $i/$total;
$percent = intval($float * 100)."%"; $percent = intval($float * 100)."%";
// Javascript for updating the progress bar and information // Javascript for updating the progress bar and information
echo '<script language="javascript"> echo '<script language="javascript">
document.getElementById("refreshLabel").innerHTML = "Updating: '.$following[1].' ('.$i.'/'.$total.')"; document.getElementById("refreshLabel").innerHTML = "Updating: '.$following[1].' ('.$i.'/'.$total.')";
document.getElementById("refreshProgress").value = "'.$float.'"; document.getElementById("refreshProgress").value = "'.$float.'";
document.getElementById("refreshProgress").innerHTML = "'.$percent.'"; document.getElementById("refreshProgress").innerHTML = "'.$percent.'";
</script>'; </script>';
updateCachedFile($following[1]); updateCachedFile($following[1]);

View file

@ -1,6 +1,9 @@
<?php <?php
require_once('partials/base.php'); require_once 'partials/base.php';
require_once('partials/webfinger_lookup.php'); require_once 'partials/webfinger_lookup.php';
require_once 'libs/session.php';
checkValidSessionOrRedirectToLogin();
// TODO: Give a warning if the file is not found // TODO: Give a warning if the file is not found
$config = parse_ini_file('private/config.ini'); $config = parse_ini_file('private/config.ini');
@ -13,18 +16,6 @@ if ($config['debug_mode']) {
$txt_file_path = $config['txt_file_path']; $txt_file_path = $config['txt_file_path'];
if (!isset($_SESSION['password'])) {
header('Location: ./login');
exit();
}
/*
if (!has_valid_session()) {
header('Location: login.php');
exit();
}
*/
if (isset($_POST['url'])) { if (isset($_POST['url'])) {
$url = trim(filter_input(INPUT_POST, 'url')); $url = trim(filter_input(INPUT_POST, 'url'));
$nick = trim(filter_input(INPUT_POST, 'nick')); $nick = trim(filter_input(INPUT_POST, 'nick'));
@ -67,36 +58,36 @@ if (isset($_POST['url'])) {
exit; exit;
} else { ?> } else { ?>
<?php <?php
$title = "Add feed - ".$title; $title = "Add feed - " . $title;
include 'partials/header.php'; include 'partials/header.php';
?> ?>
<h2>Webfinger lookup</h2> <h2>Webfinger lookup</h2>
<form method="post" action=""> <form method="post" action="">
<label>Check if a webfinger handle has a link to a twtxt.txt feed</label> <label>Check if a webfinger handle has a link to a twtxt.txt feed</label>
<input type="text" name="webfinger" size="50" autocomplete="off" required placeholder="name@example.com" value="<?= $wf_request; ?>"> <input type="text" name="webfinger" size="50" autocomplete="off" required placeholder="name@example.com" value="<?= $wf_request; ?>">
<br>
<input type="submit" name="submit" value="Lookup"><br>
</form>
<?= $wf_error; ?>
<h1>Add a new feed to follow</h1>
<form method="POST" class="column">
<div id="follow">
<label for="nick">Nick</label>
<input type="text" id="nick" name="nick" class="input" size="50" autocomplete="off" required value="<?= $wf_nick; ?>">
<label for="url">URL to follow</label>
<input type="url" id="url" name="url" class="input" size="50" autocomplete="off" required value="<?= $wf_url; ?>">
<br> <br>
<input type="submit" value="Follow" class="btn"> <input type="submit" name="submit" value="Lookup"><br>
</div> </form>
</form>
<!-- PHP: GET FOOTER --><?php include 'partials/footer.php';?> <?= $wf_error; ?>
<?php } ?> <h1>Add a new feed to follow</h1>
<form method="POST" class="column">
<div id="follow">
<label for="nick">Nick</label>
<input type="text" id="nick" name="nick" class="input" size="50" autocomplete="off" required value="<?= $wf_nick; ?>">
<label for="url">URL to follow</label>
<input type="url" id="url" name="url" class="input" size="50" autocomplete="off" required value="<?= $wf_url; ?>">
<br>
<input type="submit" value="Follow" class="btn">
</div>
</form>
<!-- PHP: GET FOOTER --><?php include 'partials/footer.php'; ?>
<?php } ?>

View file

@ -18,25 +18,23 @@ if (!empty($_GET['profile'])) { // Show twts for some user (Profile view)
// Load twts, taking $paginateTwts into consideration // Load twts, taking $paginateTwts into consideration
require_once 'partials/base.php'; require_once 'partials/base.php';
require_once 'libs/session.php';
$title = "Timeline for ".$title; $title = "Timeline for $title";
// Redirect guests to Profile view, if URL isn't set to home twtxt.txt
// Redirect guests to Profile view, if url not set til home twtxt.txt if (!hasValidSession() && isset($_GET['url'])) {
if ($_GET['url'] != $config['public_txt_url']) {
if (!isset($_SESSION['password']) && (isset($_GET['url']))) { header('Location: ./profile');
if ($_GET['url'] != $config['public_txt_url']) { exit();
header('Location: ./profile'); }
exit();
}
} }
include_once 'partials/header.php'; include_once 'partials/header.php';
if (isset($_SESSION['password'])) { if (hasValidSession()) {
include 'views/new_twt.php'; // TODO: Split up new_twt into a view and a partial include 'views/new_twt.php'; // TODO: Split up new_twt into a view and a partial
} else { } else {
echo '<center><h2>Timeline</h2>'; echo '<center><h2>Timeline</h2>';
echo '<p>Recent posts from feeds followed by <a href="./profile"> echo '<p>Recent posts from feeds followed by <a href="./profile">

View file

@ -1,4 +1,8 @@
<?php <?php
require_once 'libs/session.php';
checkValidSessionOrRedirectToLogin();
// TODO: Give a warning if the file is not found // TODO: Give a warning if the file is not found
$config = parse_ini_file('private/config.ini'); $config = parse_ini_file('private/config.ini');
@ -12,12 +16,6 @@ $txt_file_path = $config['txt_file_path'];
$public_txt_url = $config['public_txt_url']; $public_txt_url = $config['public_txt_url'];
$timezone = $config['timezone']; $timezone = $config['timezone'];
require_once 'libs/session.php';
if (!isset($_SESSION['password'])) {
header('Location: ./login');
exit();
}
if (isset($_POST['submit'])) { if (isset($_POST['submit'])) {
$new_post = filter_input(INPUT_POST, 'new_post'); $new_post = filter_input(INPUT_POST, 'new_post');

View file

@ -1,10 +1,8 @@
<?php <?php
require_once "partials/base.php"; require_once "partials/base.php";
require_once 'libs/session.php';
if (!isset($_SESSION['password'])) { checkValidSessionOrRedirectToLogin();
header('Location: ./login');
exit();
}
ob_start(); ob_start();

View file

@ -1,20 +1,14 @@
<?php <?php
require_once "partials/base.php";
require_once 'libs/session.php';
require_once("partials/base.php"); checkValidSessionOrRedirectToLogin();
if (!isset($_SESSION['password'])) { $title = "Upload - $title";
header('Location: ./login');
die();
}
$title = "Upload - ".$title;
include_once 'partials/header.php'; include_once 'partials/header.php';
if (!empty($_POST)) { if (!empty($_POST)) {
// Based on code from: https://www.w3schools.com/php/php_file_upload.asp // Based on code from: https://www.w3schools.com/php/php_file_upload.asp
//echo getcwd() ."<br>"; //echo getcwd() ."<br>";