Signed-off-by: boris <boris@borishub.co.uk>
This commit is contained in:
boris
2025-04-20 16:49:23 +01:00
parent 709596eea2
commit 78508a7cbd
29 changed files with 2623 additions and 2956 deletions

8
.gitignore vendored
View File

@@ -14,4 +14,10 @@
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
Thumbs.db
# Generated Files
generate*.*
user_credentials.txt
add_facilities.py
facility_generation_log.txt

7
.idea/dataSources.xml generated
View File

@@ -36,5 +36,12 @@
<jdbc-url>jdbc:sqlite:Databases/ecobuddy.sqlite</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
<data-source source="LOCAL" name="ecobuddyupdated.sqlite" uuid="a451dcaa-33f3-4c5d-9b63-c111bb5ed2fb">
<driver-ref>sqlite.xerial</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
<jdbc-url>jdbc:sqlite:Databases/ecobuddyupdated.sqlite</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

Binary file not shown.

Binary file not shown.

View File

@@ -1,4 +1,4 @@
Starting facility generation at 2025-03-14 22:20:38.302675
Starting facility generation at 2025-03-20 12:34:00.832910
Target: 1000 new facilities
Generating facilities...
@@ -60,7 +60,7 @@ Inserted comment batch 21/23
Inserted comment batch 22/23
Inserted comment batch 23/23
Generation complete at 2025-03-14 22:20:38.336715
Total facilities in database: 1030
Total status comments in database: 1147
Generation complete at 2025-03-20 12:34:00.860477
Total facilities in database: 12025
Total status comments in database: 13385
Generated facilities saved to generated_facilities.csv for reference

View File

@@ -5,7 +5,7 @@ import os
from datetime import datetime
# Connect to the SQLite database
conn = sqlite3.connect('Databases/ecobuddy.sqlite')
conn = sqlite3.connect('ecobuddy.sqlite')
cursor = conn.cursor()
# Get current max facility ID

File diff suppressed because it is too large Load Diff

View File

@@ -1,112 +0,0 @@
<?php
/**
* Example controller showing how to use the simplified authentication
*
* This file demonstrates how to use the User::checkAuth() and User::checkAdmin()
* methods to protect routes without using middleware.
*/
require_once('Models/User.php');
/**
* Example of a protected endpoint that requires authentication
*/
function protectedEndpoint() {
// Check if user is authenticated
$auth = User::checkAuth();
if (!$auth) {
// The checkAuth method already sent the error response
return;
}
// User is authenticated, proceed with the endpoint logic
$response = [
'status' => 'success',
'message' => 'You are authenticated',
'user' => [
'id' => $auth['uid'],
'username' => $auth['username']
]
];
// Send response
header('Content-Type: application/json');
echo json_encode($response);
}
/**
* Example of an admin-only endpoint
*/
function adminEndpoint() {
// Check if user is an admin
$auth = User::checkAdmin();
if (!$auth) {
// The checkAdmin method already sent the error response
return;
}
// User is an admin, proceed with the admin-only logic
$response = [
'status' => 'success',
'message' => 'You have admin access',
'user' => [
'id' => $auth['uid'],
'username' => $auth['username']
]
];
// Send response
header('Content-Type: application/json');
echo json_encode($response);
}
/**
* Example of a public endpoint that doesn't require authentication
* but can still use authentication data if available
*/
function publicEndpoint() {
// Check if user is authenticated, but don't require it
$auth = User::checkAuth(false);
$response = [
'status' => 'success',
'message' => 'This is a public endpoint'
];
// Add user info if authenticated
if ($auth) {
$response['user'] = [
'id' => $auth['uid'],
'username' => $auth['username']
];
} else {
$response['user'] = 'Guest';
}
// Send response
header('Content-Type: application/json');
echo json_encode($response);
}
/**
* Example of how to use these functions in a simple router
*/
function handleRequest() {
$route = $_GET['route'] ?? 'public';
switch ($route) {
case 'protected':
protectedEndpoint();
break;
case 'admin':
adminEndpoint();
break;
case 'public':
default:
publicEndpoint();
break;
}
}
// Call the router function
handleRequest();

View File

@@ -45,7 +45,6 @@ class User {
*
* Checks for a JWT token in the Authorization header and validates it.
* If valid, sets user properties based on the token payload.
* Also starts a session if needed for CAPTCHA verification during registration.
*/
public function __construct() {
// Initialise default values
@@ -69,11 +68,6 @@ class User {
$this->_loggedIn = true;
}
}
// Start session only if needed for CAPTCHA
if (session_status() === PHP_SESSION_NONE && isset($_GET['page']) && $_GET['page'] === 'register') {
session_start();
}
}
/**
@@ -207,7 +201,7 @@ class User {
{
$payload = self::checkAuth(true);
if ($payload && isset($payload['accessLevel']) && $payload['accessLevel'] == 1) {
if ($payload && isset($payload['accessLevel']) && ($payload['accessLevel'] == 1 || $payload['accessLevel'] == 0)) {
return $payload;
}

View File

@@ -27,12 +27,13 @@ require('template/header.phtml')
<!-- Badge showing the number of facilities -->
<span class="badge bg-success rounded-pill ms-2" id="facilityCount"></span>
</div>
<?php if($view->user->getAccessLevel() == 1): ?>
<!-- Add new facility button (admin only) -->
<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createModal">
<i class="bi bi-plus-circle me-1"></i>Add New Facility
</button>
<?php endif; ?>
<!-- Admin-only buttons -->
<div id="adminButtons" style="display: none;">
<!-- Add new facility button (admin only) -->
<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createModal">
<i class="bi bi-plus-circle me-1"></i>Add New Facility
</button>
</div>
</div>
</div>
<!-- Pagination controls -->
@@ -44,20 +45,8 @@ require('template/header.phtml')
<div class="table-responsive">
<table class="table table-hover align-middle mb-0" id="facilityTable">
<thead class="table-light">
<tr>
<?php if($view->user->getAccessLevel() == 1): ?>
<th class="fw-semibold" style="width: 40px;">ID</th>
<?php else: ?>
<th class="d-none">ID</th>
<?php endif; ?>
<th class="fw-semibold" style="width: 15%;">Title</th>
<th class="fw-semibold text-center" style="width: 10%;">Category</th>
<th class="fw-semibold" style="width: 25%;">Description</th>
<th class="fw-semibold" style="width: 20%;">Address</th>
<th class="fw-semibold text-center" style="width: 8%;" hidden>Postcode</th>
<th class="fw-semibold text-center" style="width: 12%;">Coordinates</th>
<th class="fw-semibold text-center" style="width: 8%;">Contributor</th>
<th class="fw-semibold text-center" style="width: 10%;">Actions</th>
<tr id="tableHeaderRow">
<!-- Table headers will be dynamically populated by JavaScript -->
</tr>
</thead>
<tbody class="border-top-0">
@@ -76,6 +65,80 @@ require('template/header.phtml')
<?php require('template/deleteModal.phtml') ?>
<?php require('template/statusModal.phtml') ?>
<!-- Regular user view (no admin buttons) -->
<div id="regularUserView"></div>
<script>
// Function to update UI based on user role
async function updateRoleBasedUI() {
const adminButtons = document.getElementById('adminButtons');
const regularUserView = document.getElementById('regularUserView');
const tableHeaderRow = document.getElementById('tableHeaderRow');
// Validate authentication with server first
let isAdmin = false;
if (simpleAuth.isAuthenticated()) {
try {
// This will validate the token with the server and handle refresh if needed
const isValid = await simpleAuth.validateOnLoad();
if (isValid) {
isAdmin = simpleAuth.isAdmin();
}
} catch (error) {
console.error('Error validating authentication:', error);
isAdmin = false;
}
}
// Show/hide admin buttons
if (adminButtons) {
adminButtons.style.display = isAdmin ? 'block' : 'none';
}
if (regularUserView) {
regularUserView.style.display = isAdmin ? 'none' : 'block';
}
// Update table headers based on user role :DDD (it just shows the ID column for admins...)
if (tableHeaderRow) {
if (isAdmin) {
// Admin view - show all columns and bigger management actions
tableHeaderRow.innerHTML = `
<th class="fw-semibold" style="width: 40px;">ID</th>
<th class="fw-semibold" style="width: 15%;">Title</th>
<th class="fw-semibold text-center" style="width: 10%;">Category</th>
<th class="fw-semibold" style="width: 25%;">Description</th>
<th class="fw-semibold" style="width: 20%;">Address</th>
<th class="fw-semibold text-center" style="width: 12%;">Coordinates</th>
<th class="fw-semibold text-center" style="width: 8%;">Contributor</th>
<th class="fw-semibold text-center" style="width: 10%;">Actions</th>
`;
} else {
// Regular user view - hide ID column and make management actions smaller
tableHeaderRow.innerHTML = `
<th class="fw-semibold" style="width: 17%;">Title</th>
<th class="fw-semibold text-center" style="width: 11%;">Category</th>
<th class="fw-semibold" style="width: 27%;">Description</th>
<th class="fw-semibold" style="width: 20%;">Address</th>
<th class="fw-semibold text-center" style="width: 12%;">Coordinates</th>
<th class="fw-semibold text-center" style="width: 8%;">Contributor</th>
<th class="fw-semibold text-center" style="width: 5%;">Actions</th>
`;
}
}
}
// Update UI when the page loads
document.addEventListener('DOMContentLoaded', updateRoleBasedUI);
// Also update when auth state changes
window.addEventListener('storage', function(e) {
if (e.key === 'token' || e.key === 'user') {
updateRoleBasedUI();
}
});
</script>
<!-- Script to update the facility count badge -->
<script>
document.addEventListener('DOMContentLoaded', function() {
@@ -100,5 +163,4 @@ document.addEventListener('DOMContentLoaded', function() {
});
</script>
<?php require('template/footer.phtml');?>
<?php require('template/footer.phtml');?>

View File

@@ -1,4 +1,3 @@
<?php if($view->user->getAccessLevel() == 1): ?>
<!-- Create Facility Modal -->
<div class="modal fade" id="createModal" tabindex="-1" aria-labelledby="createModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
@@ -10,136 +9,115 @@
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-4">
<form id="createForm">
<input type="hidden" name="action" value="create">
<!-- Create facility form -->
<form id="createFacilityForm">
<!-- Form fields -->
<div class="mb-3">
<label for="titlCreate" class="form-label">Title</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-tag text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="titlCreate" name="titlCreate" placeholder="Enter facility title" required>
</div>
<label for="createTitle" class="form-label">Facility Name</label>
<input type="text" class="form-control" id="createTitle" name="title" required>
</div>
<div class="mb-3">
<label for="cateCreate" class="form-label">Category</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-bookmark text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="cateCreate" name="cateCreate" placeholder="Enter facility category" required>
</div>
<label for="createCategory" class="form-label">Category</label>
<select class="form-select" id="createCategory" name="category" required>
<option value="" selected disabled>Select a category</option>
<option value="recycling">Recycling Center</option>
<option value="compost">Composting Facility</option>
<option value="ewaste">E-Waste Collection</option>
<option value="donation">Donation Center</option>
<option value="refill">Refill Station</option>
<option value="repair">Repair Shop</option>
<option value="garden">Community Garden</option>
<option value="market">Farmers Market</option>
<option value="other">Other</option>
</select>
</div>
<div class="mb-3">
<label for="descCreate" class="form-label">Description</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-card-text text-success"></i>
</span>
<textarea class="form-control border-start-0" id="descCreate" name="descCreate" placeholder="Enter facility description" rows="3" required></textarea>
</div>
<label for="createDescription" class="form-label">Description</label>
<textarea class="form-control" id="createDescription" name="description" rows="3" required></textarea>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="hnumCreate" class="form-label">House/Building Number</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-house text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="hnumCreate" name="hnumCreate" placeholder="Enter number" required>
</div>
<label for="createLatitude" class="form-label">Latitude</label>
<input type="number" step="any" class="form-control" id="createLatitude" name="latitude" required>
</div>
<div class="col-md-6 mb-3">
<label for="strtCreate" class="form-label">Street Name</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-signpost text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="strtCreate" name="strtCreate" placeholder="Enter street name" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="townCreate" class="form-label">Town/City</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-building text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="townCreate" name="townCreate" placeholder="Enter town/city" required>
</div>
</div>
<div class="col-md-6 mb-3">
<label for="cntyCreate" class="form-label">County</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-map text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="cntyCreate" name="cntyCreate" placeholder="Enter county" required>
</div>
<label for="createLongitude" class="form-label">Longitude</label>
<input type="number" step="any" class="form-control" id="createLongitude" name="longitude" required>
</div>
</div>
<div class="mb-3">
<label for="postCreate" class="form-label">Postcode</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-mailbox text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="postCreate" name="postCreate" placeholder="Enter postcode" required>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="latCreate" class="form-label">Latitude</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-geo-alt text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="latCreate" name="latCreate" placeholder="Enter latitude" required>
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lngCreate" class="form-label">Longitude</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-geo-alt text-success"></i>
</span>
<input type="text" class="form-control border-start-0" id="lngCreate" name="lngCreate" placeholder="Enter longitude" required>
</div>
</div>
<label for="createAddress" class="form-label">Address</label>
<input type="text" class="form-control" id="createAddress" name="address" required>
</div>
<div class="mb-3">
<label for="contCreate" class="form-label">Contributor</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-person text-success"></i>
</span>
<input type="text" class="form-control border-start-0 bg-light" id="contCreate" name="contCreate" placeholder="Auto-filled with your username" disabled required>
</div>
<small class="text-muted">This will be automatically filled with your username</small>
<label for="createContact" class="form-label">Contact Information</label>
<input type="text" class="form-control" id="createContact" name="contact">
</div>
<div class="mb-3">
<label for="createWebsite" class="form-label">Website</label>
<input type="url" class="form-control" id="createWebsite" name="website" placeholder="https://">
</div>
<div class="mb-3">
<label for="createHours" class="form-label">Operating Hours</label>
<input type="text" class="form-control" id="createHours" name="hours" placeholder="e.g., Mon-Fri: 9am-5pm">
</div>
<div class="mb-3">
<label for="createStatus" class="form-label">Status</label>
<select class="form-select" id="createStatus" name="status" required>
<option value="operational">Operational</option>
<option value="limited">Limited Service</option>
<option value="closed">Temporarily Closed</option>
<option value="planned">Planned</option>
</select>
</div>
<div id="createError" class="alert alert-danger" style="display: none;"></div>
</form>
</div>
<div class="modal-footer bg-light">
<div class="w-100 d-flex justify-content-between">
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" form="createForm" class="btn btn-success">
<i class="bi bi-plus-circle me-1"></i>Create Facility
</button>
</div>
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success" id="createFacilityButton">
<i class="bi bi-plus-circle me-1"></i>Create Facility
</button>
</div>
</div>
</div>
</div>
<?php endif; ?>
<script>
// Only allow admin users to access this modal
document.addEventListener('DOMContentLoaded', function() {
const createModal = document.getElementById('createModal');
if (createModal) {
createModal.addEventListener('show.bs.modal', async function(event) {
// Validate authentication with server first
let isAdmin = false;
if (simpleAuth.isAuthenticated()) {
try {
// This will validate the token with the server and handle refresh if needed
const isValid = await simpleAuth.validateOnLoad();
if (isValid) {
isAdmin = simpleAuth.isAdmin();
}
} catch (error) {
console.error('Error validating authentication:', error);
isAdmin = false;
}
}
if (!isAdmin) {
event.preventDefault();
alert('You need administrator privileges to add new facilities.');
}
});
}
});
</script>

View File

@@ -63,6 +63,101 @@
if (simpleAuth.needsCaptcha() && captchaContainer) {
captchaContainer.style.display = 'flex';
}
// Add login form handler
loginForm.addEventListener('submit', async function(e) {
e.preventDefault();
// Get form data
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const captchaInput = document.getElementById('captchaInput')?.value;
// Clear previous error
if (loginError) {
loginError.style.display = 'none';
loginError.textContent = '';
}
// Show loading spinner in submit button
const submitButton = this.querySelector('button[type="submit"]');
const originalButtonContent = submitButton.innerHTML;
submitButton.disabled = true;
submitButton.innerHTML = `
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<span class="ms-2">Logging in...</span>
`;
// Record start time for minimum spinner display
const startTime = Date.now();
try {
// Attempt login
const result = await simpleAuth.login({
username: username,
password: password,
captchaInput: captchaInput
});
// Calculate elapsed time and wait if needed to show spinner for at least 500ms
const elapsedTime = Date.now() - startTime;
const minSpinnerTime = 500; // 500ms minimum spinner display time
if (elapsedTime < minSpinnerTime) {
await new Promise(resolve => setTimeout(resolve, minSpinnerTime - elapsedTime));
}
if (result.success) {
// Show success message in button
submitButton.classList.remove('btn-success');
submitButton.classList.add('btn-success');
submitButton.innerHTML = `
<i class="bi bi-check-circle me-2"></i>Login successful
`;
// Wait a moment before closing modal and reloading
setTimeout(() => {
// Close modal
const modal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
if (modal) {
modal.hide();
}
// Reload page to update UI
window.location.reload();
}, 500);
} else {
// Show error
if (loginError) {
loginError.textContent = result.error || 'Login failed';
loginError.style.display = 'block';
}
// Show CAPTCHA if needed
if (simpleAuth.needsCaptcha() && captchaContainer) {
captchaContainer.style.display = 'flex';
// Generate new CAPTCHA if needed
if (result.captcha) {
document.getElementById('captchaCode').value = result.captcha;
}
}
// Reset button
submitButton.disabled = false;
submitButton.innerHTML = originalButtonContent;
}
} catch (error) {
console.error('Login error:', error);
if (loginError) {
loginError.textContent = error.message || 'An error occurred during login';
loginError.style.display = 'block';
}
// Reset button
submitButton.disabled = false;
submitButton.innerHTML = originalButtonContent;
}
});
}
// Handle logout button

View File

@@ -66,11 +66,11 @@
// Add client-side authentication check to update UI
document.addEventListener('DOMContentLoaded', function() {
// Check if user is authenticated on the client side
if (window.auth && window.auth.isAuthenticated()) {
if (simpleAuth && simpleAuth.isAuthenticated()) {
console.log('User is authenticated on client side');
// Get user data
const user = window.auth.getUser();
const user = simpleAuth.getUser();
if (user) {
console.log('User data:', user);
@@ -115,7 +115,7 @@
const logoutButton = document.getElementById('logoutButton');
if (logoutButton) {
logoutButton.addEventListener('click', async function() {
await window.auth.logout();
await simpleAuth.logout();
window.location.reload();
});
}
@@ -174,9 +174,8 @@
<i class="bi bi-sort-alpha-down text-success"></i>
</span>
<select name="sort" class="form-select border-start-0 filter-control" id="sort">
<option value="title">Title</option>
<option selected value="title">Title</option>
<option value="category">Category</option>
<option value="status">Status</option>
<option value="description">Description</option>
<option value="streetName">Street</option>
<option value="county">County</option>
@@ -195,10 +194,8 @@
<i class="bi bi-filter-circle-fill text-success"></i>
</span>
<select name="filterCat" class="form-select border-start-0 filter-control" id="filterCat">
<option value="">All</option>
<option value="title">Title</option>
<option value="category">Category</option>
<option value="status">Status</option>
<option value="description">Description</option>
<option value="streetName">Street</option>
<option value="county">County</option>
@@ -218,36 +215,105 @@
</div>
<!-- User account section -->
<div class="ms-lg-3 mt-3 mt-lg-0">
<?php if(!$view->user->isLoggedIn()): ?>
<button type="button" class="btn btn-success" id="loginButton" data-bs-toggle="modal" data-bs-target="#loginModal">
<i class="bi bi-box-arrow-in-right me-1"></i>Login
</button>
<?php else: ?>
<div class="user-menu">
<div class="user-avatar">
<i class="bi bi-person-fill text-success"></i>
</div>
<div class="dropdown">
<button class="btn btn-light dropdown-toggle" type="button" id="userMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
<?php echo $view->user->getUsername(); ?>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userMenuButton">
<li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>Profile</a></li>
<li><a class="dropdown-item" href="#"><i class="bi bi-gear me-2"></i>Settings</a></li>
<li><hr class="dropdown-divider"></li>
<li><button class="dropdown-item text-danger" id="logoutButton"><i class="bi bi-box-arrow-right me-2"></i>Logout</button></li>
</ul>
</div>
</div>
<?php endif; ?>
<div class="ms-lg-3 mt-3 mt-lg-0" id="userAuthSection">
<!-- This section will be populated by JavaScript based on authentication status -->
<div class="spinner-border spinner-border-sm text-success" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<script>
// Function to update the authentication UI
async function updateAuthUI() {
const authSection = document.getElementById('userAuthSection');
// Show loading spinner (this is unnecessary but I like it :D)
authSection.innerHTML = `
<div class="spinner-border spinner-border-sm text-success" role="status">
<span class="visually-hidden">Loading...</span>
</div>
`;
// Record start time for minimum spinner display
const startTime = Date.now();
// Validate token with server first
let isAuthenticated = false;
if (simpleAuth.isAuthenticated()) {
try {
// This will validate the token with the server and handle refresh if needed
isAuthenticated = await simpleAuth.validateOnLoad();
} catch (error) {
console.error('Error validating authentication:', error);
isAuthenticated = false;
}
}
// Calculate elapsed time and wait if needed to show my very cool spinner for 500ms
const elapsedTime = Date.now() - startTime;
const minSpinnerTime = 500; // 500ms
if (elapsedTime < minSpinnerTime) {
await new Promise(resolve => setTimeout(resolve, minSpinnerTime - elapsedTime));
}
if (isAuthenticated) {
// User is logged in - show user menu
const user = simpleAuth.getUser();
const isAdmin = simpleAuth.isAdmin();
authSection.innerHTML = `
<div class="user-menu">
<div class="user-avatar">
<i class="bi bi-person-fill text-success"></i>
</div>
<div class="dropdown">
<button class="btn btn-link dropdown-toggle text-dark text-decoration-none" type="button" id="userMenuDropdown" data-bs-toggle="dropdown" aria-expanded="false">
${user.username}
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userMenuDropdown">
${isAdmin ? '<li><a class="dropdown-item" href="/admin"><i class="bi bi-gear me-2"></i>Admin Panel</a></li>' : ''}
<li><a class="dropdown-item" href="/profile"><i class="bi bi-person me-2"></i>My Profile</a></li>
<li><hr class="dropdown-divider"></li>
<li><button class="dropdown-item" name="logoutButton"><i class="bi bi-box-arrow-right me-2"></i>Logout</button></li>
</ul>
</div>
</div>
`;
// Add event listener for logout button
const logoutButton = authSection.querySelector('button[name="logoutButton"]');
if (logoutButton) {
logoutButton.addEventListener('click', async () => {
await simpleAuth.logout();
window.location.reload();
});
}
} else {
// User is not logged in - show login button
authSection.innerHTML = `
<button type="button" class="btn btn-success" id="loginButton" data-bs-toggle="modal" data-bs-target="#loginModal">
<i class="bi bi-box-arrow-in-right me-1"></i>Login
</button>
`;
}
}
// Update auth UI when the page loads
document.addEventListener('DOMContentLoaded', updateAuthUI);
// Also update when simpleAuth state changes
window.addEventListener('storage', function(e) {
if (e.key === 'token' || e.key === 'user') {
updateAuthUI();
}
});
</script>
</div>
</div>
</nav>
<!-- Login Modal -->
<?php if(!$view->user->isLoggedIn()): ?>
<div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-0 shadow">
@@ -280,21 +346,27 @@
<div id="loginError" class="alert alert-danger" style="display: none;"></div>
<div class="row captcha-container" style="display: none;">
<!-- CAPTCHA Display -->
<div class="col-md-6 mb-3">
<label for="captchaCode" class="form-label">CAPTCHA Code</label>
<input type="text" class="form-control bg-light" id="captchaCode" name="generatedCaptcha" value="" readonly>
</div>
<!-- CAPTCHA Input -->
<div class="col-md-6 mb-3">
<label for="captchaInput" class="form-label">Enter CAPTCHA</label>
<input type="text" class="form-control" id="captchaInput" name="captchaInput" placeholder="Enter code">
<!-- CAPTCHA container (hidden by default) -->
<div class="captcha-container mb-3" style="display: none;">
<div class="card bg-light">
<div class="card-body">
<h6 class="card-title">Security Check</h6>
<p class="card-text small">Please enter the characters you see below:</p>
<div class="d-flex align-items-center mb-2">
<div class="captcha-code bg-white p-2 border rounded me-2 text-center" style="font-family: monospace; letter-spacing: 3px; font-weight: bold; min-width: 100px;">
<span id="captchaDisplay"></span>
</div>
<input type="text" class="form-control" id="captchaInput" placeholder="Enter code" autocomplete="off">
<input type="hidden" id="captchaCode" name="captchaCode">
</div>
<button type="button" class="btn btn-sm btn-outline-secondary" id="refreshCaptcha">
<i class="bi bi-arrow-clockwise"></i> Refresh
</button>
</div>
</div>
</div>
<div class="d-grid gap-2 mt-4">
<div class="d-grid">
<button type="submit" class="btn btn-success">
<i class="bi bi-box-arrow-in-right me-2"></i>Login
</button>
@@ -302,15 +374,140 @@
</form>
</div>
<div class="modal-footer bg-light">
<div class="w-100 d-flex justify-content-between align-items-center">
<small class="text-muted">Don't have an account? <a href="" onclick="alert('Please contact the administrator to create an account.');" class="text-success">Register</a></small>
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
</div>
<p class="small text-muted mb-0">Don't have an account? <a href="#" class="text-success">Register</a></p>
</div>
</div>
</div>
</div>
<?php endif; ?>
<script>
// Initialize login modal functionality
document.addEventListener('DOMContentLoaded', function() {
const loginModal = document.getElementById('loginModal');
const loginForm = document.getElementById('loginForm');
const loginError = document.getElementById('loginError');
const captchaContainer = document.querySelector('.captcha-container');
const captchaDisplay = document.getElementById('captchaDisplay');
const refreshCaptchaBtn = document.getElementById('refreshCaptcha');
// Function to update CAPTCHA display
async function updateCaptcha() {
try {
const captcha = await simpleAuth.generateCaptcha();
if (captchaDisplay) {
captchaDisplay.textContent = captcha;
}
if (document.getElementById('captchaCode')) {
document.getElementById('captchaCode').value = captcha;
}
} catch (error) {
console.error('Error updating CAPTCHA:', error);
if (loginError) {
loginError.textContent = 'Error generating security check. Please try again.';
loginError.style.display = 'block';
}
}
}
// Handle CAPTCHA refresh button
if (refreshCaptchaBtn) {
refreshCaptchaBtn.addEventListener('click', updateCaptcha);
}
// Show/hide CAPTCHA based on login attempts
if (simpleAuth.needsCaptcha() && captchaContainer) {
captchaContainer.style.display = 'block';
updateCaptcha();
}
// Handle form submission
if (loginForm) {
loginForm.addEventListener('submit', async function(e) {
e.preventDefault();
// Get form data
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const captchaInput = document.getElementById('captchaInput')?.value;
// Show loading state
const submitButton = this.querySelector('button[type="submit"]');
const originalButtonContent = submitButton.innerHTML;
submitButton.disabled = true;
submitButton.innerHTML = `
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<span class="ms-2">Logging in...</span>
`;
try {
// Attempt login
const result = await simpleAuth.login({
username,
password,
captchaInput
});
if (result.success) {
// Show success message
submitButton.classList.remove('btn-success');
submitButton.classList.add('btn-success');
submitButton.innerHTML = `
<i class="bi bi-check-circle me-2"></i>Login successful
`;
// Hide error message if shown
if (loginError) {
loginError.style.display = 'none';
}
// Close modal and reload page after a brief delay
setTimeout(() => {
const modal = bootstrap.Modal.getInstance(loginModal);
if (modal) {
modal.hide();
}
window.location.reload();
}, 500);
} else {
// Show error message
if (loginError) {
loginError.textContent = result.error;
loginError.style.display = 'block';
}
// Show CAPTCHA if needed
if (result.captcha && captchaContainer) {
captchaContainer.style.display = 'block';
updateCaptcha();
}
// Reset button
submitButton.disabled = false;
submitButton.innerHTML = originalButtonContent;
}
} catch (error) {
// Show error message
if (loginError) {
loginError.textContent = error.message || 'An error occurred during login';
loginError.style.display = 'block';
}
// Reset button
submitButton.disabled = false;
submitButton.innerHTML = originalButtonContent;
}
});
}
// Hide modal if user is already authenticated
if (simpleAuth.isAuthenticated() && loginModal) {
const modalInstance = bootstrap.Modal.getInstance(loginModal);
if (modalInstance) {
modalInstance.hide();
}
}
});
</script>
<!-- Main content container -->
<div class="container-fluid py-4 px-3">

View File

@@ -1,18 +0,0 @@
<span class="ms-5 me-5 row alert alert-danger" role="alert"><?= $view->loginError ?></span>
<div class="row captcha-container">
<!-- CAPTCHA Display -->
<div class="form-floating mb-3 col">
<input type="text" class="form-control" id="captchaCode" value="<?php
// Generate a simple 5-character CAPTCHA
$captcha = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 5);
echo $captcha;
?>" readonly>
<label for="captchaCode">CAPTCHA Code</label>
</div>
<!-- CAPTCHA Input -->
<div class="form-floating mb-3 col">
<input type="text" class="form-control" id="captchaInput" name="captchaInput" placeholder="Enter CAPTCHA" required>
<label for="captchaInput">Enter CAPTCHA</label>
</div>
</div>

View File

@@ -31,21 +31,27 @@
<div id="loginError" class="alert alert-danger" style="display: none;"></div>
<div class="row captcha-container" style="display: none;">
<!-- CAPTCHA Display -->
<div class="col-md-6 mb-3">
<label for="captchaCode" class="form-label">CAPTCHA Code</label>
<input type="text" class="form-control bg-light" id="captchaCode" name="generatedCaptcha" value="" readonly>
</div>
<!-- CAPTCHA Input -->
<div class="col-md-6 mb-3">
<label for="captchaInput" class="form-label">Enter CAPTCHA</label>
<input type="text" class="form-control" id="captchaInput" name="captchaInput" placeholder="Enter code">
<!-- CAPTCHA container (hidden by default) -->
<div class="captcha-container mb-3" style="display: none;">
<div class="card bg-light">
<div class="card-body">
<h6 class="card-title">Security Check</h6>
<p class="card-text small">Please enter the characters you see below:</p>
<div class="d-flex align-items-center mb-2">
<div class="captcha-code bg-white p-2 border rounded me-2 text-center" style="font-family: monospace; letter-spacing: 3px; font-weight: bold; min-width: 100px;">
<span id="captchaDisplay"></span>
</div>
<input type="text" class="form-control" id="captchaInput" placeholder="Enter code" autocomplete="off">
<input type="hidden" id="captchaCode" name="captchaCode">
</div>
<button type="button" class="btn btn-sm btn-outline-secondary" id="refreshCaptcha">
<i class="bi bi-arrow-clockwise"></i> Refresh
</button>
</div>
</div>
</div>
<div class="d-grid gap-2 mt-4">
<div class="d-grid">
<button type="submit" class="btn btn-success">
<i class="bi bi-box-arrow-in-right me-2"></i>Login
</button>
@@ -60,4 +66,75 @@
</div>
</div>
</div>
</div>
</div>
<script>
// Handle CAPTCHA functionality
document.addEventListener('DOMContentLoaded', function() {
const captchaContainer = document.querySelector('.captcha-container');
const captchaDisplay = document.getElementById('captchaDisplay');
const refreshCaptchaBtn = document.getElementById('refreshCaptcha');
const loginForm = document.getElementById('loginForm');
// Function to update CAPTCHA display
async function updateCaptcha() {
try {
const captcha = await simpleAuth.generateCaptcha();
captchaDisplay.textContent = captcha;
document.getElementById('captchaCode').value = captcha;
} catch (error) {
console.error('Error updating CAPTCHA:', error);
}
}
// Handle CAPTCHA refresh button
if (refreshCaptchaBtn) {
refreshCaptchaBtn.addEventListener('click', updateCaptcha);
}
// Show/hide CAPTCHA based on login attempts
if (simpleAuth.needsCaptcha()) {
captchaContainer.style.display = 'block';
updateCaptcha();
}
// Handle form submission
if (loginForm) {
loginForm.addEventListener('submit', async function(e) {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const captchaInput = document.getElementById('captchaInput')?.value;
const result = await simpleAuth.login({
username,
password,
captchaInput
});
if (result.success) {
// Close modal and reload page
const modal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
if (modal) {
modal.hide();
}
window.location.reload();
} else {
// Show error
const loginError = document.getElementById('loginError');
if (loginError) {
loginError.textContent = result.error;
loginError.style.display = 'block';
}
// Show CAPTCHA if needed
if (result.captcha) {
captchaContainer.style.display = 'block';
updateCaptcha();
}
}
});
}
});
</script>

View File

@@ -1,2 +0,0 @@
<?php echo "<p class='text-center bg-light border-0 rounded mb-1' style='color: black;'>" . $user->getUsername() . "<span class='bi bi-person-fill'></span></p>"?>
<button class="btn bg-danger btn-outline-danger text-light" type="button" id="logoutButton">Logout</button>

View File

@@ -9,56 +9,13 @@
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-4">
<!-- Add Comment Form (Only shown to logged in users) -->
<?php if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true && $_SESSION['access'] >= 1): ?>
<div class="mb-4 border-bottom pb-4">
<h6 class="fw-bold mb-3">
<i class="bi bi-plus-circle text-success me-2"></i>Add New Comment
</h6>
<form id="commentForm">
<input type="hidden" name="action" value="status">
<input type="hidden" name="facilityId" id="commentFacilityId" value="">
<div class="mb-3">
<label for="commentText" class="form-label">Your Comment</label>
<div class="input-group">
<span class="input-group-text bg-light border-end-0">
<i class="bi bi-pencil text-primary"></i>
</span>
<textarea class="form-control border-start-0" id="commentText" name="commentText" rows="3" placeholder="Share your thoughts about this facility..." required></textarea>
</div>
</div>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-primary">
<i class="bi bi-send me-1"></i>Post Comment
</button>
</div>
</form>
</div>
<?php endif; ?>
<!-- Existing Comments Section -->
<div>
<h6 class="fw-bold mb-3">
<i class="bi bi-chat-square-dots text-primary me-2"></i>Comments
</h6>
<div id="commentsContainer" class="comments-container">
<!-- Comments will be loaded here dynamically -->
<div class="text-center py-4 text-muted" id="noCommentsMessage">
<i class="bi bi-chat-square-text fs-4 d-block mb-2"></i>
<p>No comments yet. Be the first to share your thoughts!</p>
</div>
<!-- Comments container - this will be populated by JavaScript -->
<div id="commentsContainer" class="comments-container">
<!-- Comments will be loaded here dynamically -->
<div class="text-center py-4 text-muted" id="noCommentsMessage">
<i class="bi bi-chat-square-text fs-4 d-block mb-2"></i>
<p>Loading comments...</p>
</div>
<!-- Login Prompt for Non-Authenticated Users -->
<?php if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true): ?>
<div class="alert alert-info mt-3">
<i class="bi bi-info-circle me-2"></i>
<span>Please <a href="#" data-bs-toggle="modal" data-bs-target="#loginModal" data-bs-dismiss="modal">log in</a> to add your comments.</span>
</div>
<?php endif; ?>
</div>
</div>
<div class="modal-footer bg-light">

View File

@@ -1,33 +0,0 @@
<?php
/**
* Admin-only API endpoint example
*
* This endpoint demonstrates how to protect an API route for admin users only
* using our simplified authentication approach.
*/
require_once('../Models/User.php');
// Set content type to JSON
header('Content-Type: application/json');
// Check if user is an admin
$auth = User::checkAdmin();
if (!$auth) {
// The checkAdmin method already sent the error response
exit;
}
// User is an admin, proceed with the admin-only logic
$response = [
'status' => 'success',
'message' => 'You have access to this admin-only endpoint',
'user' => [
'id' => $auth['uid'],
'username' => $auth['username'],
'accessLevel' => $auth['accessLevel']
]
];
// Send response
echo json_encode($response);

View File

@@ -1,51 +0,0 @@
<?php
/**
* Login API endpoint
*
* This endpoint handles user authentication and returns a JWT token
* if the credentials are valid.
*/
require_once('../Models/User.php');
// Set content type to JSON
header('Content-Type: application/json');
// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
// Get JSON request body
$json = file_get_contents('php://input');
$data = json_decode($json, true);
// Validate request data
if (!$data || !isset($data['username']) || !isset($data['password'])) {
http_response_code(400);
echo json_encode(['error' => 'Invalid request data']);
exit;
}
// Authenticate user
$user = new User();
$token = $user->Authenticate($data['username'], $data['password']);
if ($token) {
// Authentication successful
echo json_encode([
'success' => true,
'token' => $token,
'user' => [
'id' => $user->getUserId(),
'username' => $user->getUsername(),
'accessLevel' => $user->getAccessLevel()
]
]);
} else {
// Authentication failed
http_response_code(401);
echo json_encode(['error' => 'Invalid credentials']);
}

View File

@@ -1,33 +0,0 @@
<?php
/**
* Protected API endpoint example
*
* This endpoint demonstrates how to protect an API route using
* our simplified authentication approach.
*/
require_once('../Models/User.php');
// Set content type to JSON
header('Content-Type: application/json');
// Check if user is authenticated
$auth = User::checkAuth();
if (!$auth) {
// The checkAuth method already sent the error response
exit;
}
// User is authenticated, proceed with the endpoint logic
$response = [
'status' => 'success',
'message' => 'You have access to this protected endpoint',
'user' => [
'id' => $auth['uid'],
'username' => $auth['username'],
'accessLevel' => $auth['accessLevel']
]
];
// Send response
echo json_encode($response);

View File

@@ -3,12 +3,19 @@ require_once('Models/AuthService.php');
require_once('Models/UserDataSet.php');
require_once('Models/User.php');
// Enable CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
// Enable CORS with more restrictive settings
header('Access-Control-Allow-Origin: *'); // Would be set to domain. Move to .env file
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');
// Add security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Content-Security-Policy: default-src \'self\'');
// Handle OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
@@ -23,6 +30,22 @@ try {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true);
// Handle CAPTCHA generation
if (isset($data['action']) && $data['action'] === 'generateCaptcha') {
// Generate a random 6-character CAPTCHA
$captcha = substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 6);
// Store CAPTCHA in session with timestamp
session_start();
$_SESSION['captcha'] = [
'code' => $captcha,
'timestamp' => time()
];
echo json_encode(['captcha' => $captcha]);
exit;
}
// Handle token refresh
if (isset($data['action']) && $data['action'] === 'refresh') {
if (!isset($data['refreshToken'])) {
@@ -54,11 +77,46 @@ try {
exit;
}
// Check if CAPTCHA is required
session_start();
$loginAttempts = $_SESSION['login_attempts'] ?? 0;
if ($loginAttempts >= 3) {
// Verify CAPTCHA if required
if (!isset($data['captchaInput']) || !isset($_SESSION['captcha'])) {
http_response_code(400);
echo json_encode(['error' => 'CAPTCHA is required', 'captcha' => true]);
exit;
}
// Check if CAPTCHA is expired (5 minutes)
if (time() - $_SESSION['captcha']['timestamp'] > 300) {
unset($_SESSION['captcha']);
http_response_code(400);
echo json_encode(['error' => 'CAPTCHA expired', 'captcha' => true]);
exit;
}
// Verify CAPTCHA code
if (strtoupper($data['captchaInput']) !== $_SESSION['captcha']['code']) {
unset($_SESSION['captcha']);
http_response_code(400);
echo json_encode(['error' => 'Invalid CAPTCHA', 'captcha' => true]);
exit;
}
// Clear CAPTCHA after successful verification
unset($_SESSION['captcha']);
}
// Authenticate user
$user = new User();
$token = $user->Authenticate($data['username'], $data['password']);
$token = $user->Authenticate($data['username'], hash('sha256', $data['password']));
if ($token) {
// Reset login attempts on successful login
$_SESSION['login_attempts'] = 0;
// Generate refresh token
$refreshToken = $auth->generateRefreshToken([
'id' => $user->getUserId(),
@@ -77,8 +135,14 @@ try {
]
]);
} else {
// Increment login attempts
$_SESSION['login_attempts'] = ($loginAttempts ?? 0) + 1;
http_response_code(401);
echo json_encode(['error' => 'Invalid credentials']);
echo json_encode([
'error' => 'Invalid credentials',
'captcha' => $_SESSION['login_attempts'] >= 3
]);
}
exit;
}

View File

@@ -147,10 +147,32 @@ try {
break;
case 'getStatuses':
$facilityId = $_POST['facilityId'];
$statuses = $facilityDataSet->getFacilityStatuses($facilityId);
if (!isset($_POST['facilityId'])) {
http_response_code(400);
echo json_encode(['error' => 'Facility ID is required']);
break;
}
echo json_encode(['success' => true, 'statuses' => $statuses]);
$facilityId = $_POST['facilityId'];
try {
$statuses = $facilityDataSet->getFacilityStatuses($facilityId);
if ($statuses === false) {
throw new Exception('Failed to fetch facility statuses');
}
echo json_encode([
'success' => true,
'statuses' => $statuses
]);
} catch (Exception $e) {
error_log('Error getting facility statuses: ' . $e->getMessage());
http_response_code(500);
echo json_encode([
'error' => 'Failed to load comments',
'message' => $e->getMessage()
]);
}
break;
case 'editStatus':

View File

@@ -1,6 +1,5 @@
<?php
// load dataset
require_once('Models/UserDataSet.php');
require_once('Models/FacilityDataSet.php');
// make a view class
@@ -16,11 +15,6 @@ if ($view->facilityDataSet === false) {
error_log('Error fetching facility data');
}
// load login controller
require_once("logincontroller.php");
$view->user = new User();
// load main view
require_once('Views/index.phtml');

View File

@@ -1,158 +0,0 @@
<?php
require_once("Models/User.php");
require_once("Models/AuthService.php");
// Enable CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
// Handle OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
// Create service objects
$authService = new AuthService();
// Start session for CAPTCHA handling only
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
header('Content-Type: application/json');
if (isset($_POST["action"])) {
switch ($_POST["action"]) {
case "login":
$username = $_POST["username"];
$password = hash("sha256", $_POST["password"]);
// Check if CAPTCHA is required (after 3 failed attempts)
$loginAttempts = isset($_SESSION['loginAttempts']) ? $_SESSION['loginAttempts'] : 0;
if ($loginAttempts >= 3) {
// Validate CAPTCHA
if (!isset($_POST["captchaInput"]) || !isset($_SESSION['captcha']) ||
$_POST["captchaInput"] !== $_SESSION['captcha']) {
// Generate new CAPTCHA for next attempt
$captcha = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 5);
$_SESSION['captcha'] = $captcha;
echo json_encode([
"error" => "Incorrect CAPTCHA.",
"captcha" => $captcha
]);
exit;
}
// Clear CAPTCHA after successful validation
unset($_SESSION['captcha']);
}
// Authenticate user
$user = new User();
$token = $user->Authenticate($username, $password);
if ($token) {
// Reset login attempts on successful login
$_SESSION['loginAttempts'] = 0;
// Generate refresh token
$refreshToken = $authService->generateRefreshToken([
'id' => $user->getUserId(),
'username' => $user->getUsername(),
'accessLevel' => $user->getAccessLevel()
]);
echo json_encode([
'success' => true,
'token' => $token,
'refreshToken' => $refreshToken,
'user' => [
'id' => $user->getUserId(),
'username' => $user->getUsername(),
'accessLevel' => $user->getAccessLevel()
],
'redirect' => '/'
]);
} else {
// Increment login attempts
$_SESSION['loginAttempts'] = $loginAttempts + 1;
// If this failure triggers CAPTCHA, generate it
if ($_SESSION['loginAttempts'] >= 3) {
$captcha = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 5);
$_SESSION['captcha'] = $captcha;
echo json_encode([
"error" => "Invalid username or password.",
"captcha" => $captcha
]);
} else {
echo json_encode(["error" => "Invalid username or password."]);
}
}
break;
case "logout":
// Clear session (only used for CAPTCHA)
session_unset();
session_destroy();
echo json_encode([
"success" => true,
"redirect" => '/'
]);
break;
case "refresh":
// Validate refresh token
if (!isset($_POST['refreshToken'])) {
echo json_encode([
"valid" => false,
"error" => "No refresh token provided"
]);
exit;
}
$refreshToken = $_POST['refreshToken'];
$newToken = $authService->refreshToken($refreshToken);
if ($newToken) {
echo json_encode([
"valid" => true,
"token" => $newToken
]);
} else {
echo json_encode([
"valid" => false,
"error" => "Invalid or expired refresh token"
]);
}
break;
case "validate":
// Validate JWT token using the simplified approach
$auth = User::checkAuth(false);
if ($auth) {
echo json_encode([
"valid" => true,
"user" => [
"id" => $auth['uid'],
"username" => $auth['username'],
"accessLevel" => $auth['accessLevel']
]
]);
} else {
echo json_encode([
"valid" => false
]);
}
break;
}
exit;
}
}

View File

@@ -5,23 +5,40 @@
* authentication and common request patterns.
*
* The client uses JWT tokens for authentication, which are automatically
* included in requests via the authFetch function provided by the auth service.
* included in requests via the fetchAuth function provided by the simpleAuth service.
*
* NOTE: For authentication (login, logout, token validation), please use the simpleAuth
* service directly instead of this API client.
*/
class ApiClient {
/**
* Constructor
*
* Initialises the API client and sets up the authenticated fetch function.
* Relies on the auth service being available in the global scope.
* Relies on the simpleAuth service being available in the global scope.
*/
constructor() {
// Ensure auth service is available
if (!window.auth) {
if (!simpleAuth) {
console.error('Auth service not available');
}
// Create authenticated fetch function if not already available
this.authFetch = window.authFetch || window.auth?.createAuthFetch() || fetch;
// Use the fetchAuth method from simpleAuth
this.authFetch = async (url, options = {}) => {
try {
// For unauthenticated requests or when authentication is not required
if (!options.requireAuth || !simpleAuth.isAuthenticated()) {
return fetch(url, options);
}
// For authenticated requests
delete options.requireAuth; // Remove the custom property
return simpleAuth.fetchAuth(url, options);
} catch (error) {
console.error('Error in authFetch:', error);
throw error;
}
};
}
/**
@@ -115,7 +132,27 @@ class ApiClient {
formData.append(key, value);
});
return this.post('/facilitycontroller.php', formData);
try {
// Use authenticated fetch for all facility requests
const response = await this.authFetch('/facilitycontroller.php', {
method: 'POST',
body: formData,
requireAuth: true // Explicitly require authentication
});
// Check if response is ok
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse the JSON response
const jsonData = await response.json();
console.log('Facility API response:', { action, data: jsonData });
return jsonData;
} catch (error) {
console.error('Facility API error:', error);
throw error;
}
}
/**
@@ -183,12 +220,15 @@ class ApiClient {
*
* This method adds a new status update to a facility.
*
* @param {number|string} idStatus - The facility ID
* @param {string} updateStatus - The status comment
* @param {number|string} facilityId - The facility ID
* @param {string} statusComment - The status comment
* @returns {Promise<Object>} The response data
*/
async addFacilityStatus(idStatus, updateStatus) {
return this.facility('status', { idStatus, updateStatus });
async addFacilityStatus(facilityId, statusComment) {
return this.facility('status', {
facilityId: facilityId,
statusComment: statusComment
});
}
/**
@@ -217,87 +257,6 @@ class ApiClient {
async deleteFacilityStatus(statusId, facilityId) {
return this.facility('deleteStatus', { statusId, facilityId });
}
/**
* Authenticates a user
*
* This method sends a login request with the provided credentials.
* It uses a direct fetch call rather than authFetch since the user
* isn't authenticated yet.
*
* @param {string} username - The username
* @param {string} password - The password
* @param {string} captchaInput - The CAPTCHA input (optional)
* @returns {Promise<Object>} The response data
*/
async login(username, password, captchaInput = null) {
const formData = new FormData();
formData.append('action', 'login');
formData.append('username', username);
formData.append('password', password);
if (captchaInput) {
formData.append('captchaInput', captchaInput);
}
const response = await fetch('/logincontroller.php', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
body: formData
});
return await response.json();
}
/**
* Refreshes the access token
*
* This method sends a request to refresh an expired JWT token
* using the provided refresh token.
*
* @param {string} refreshToken - The refresh token
* @returns {Promise<Object>} The response data
*/
async refreshToken(refreshToken) {
const formData = new FormData();
formData.append('action', 'refresh');
formData.append('refreshToken', refreshToken);
const response = await fetch('/logincontroller.php', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
body: formData
});
return await response.json();
}
/**
* Logs out the current user
*
* This method sends a logout request to invalidate the session.
* Note that client-side token removal is handled separately.
*
* @returns {Promise<Object>} The response data
*/
async logout() {
const formData = new FormData();
formData.append('action', 'logout');
const response = await fetch('/logincontroller.php', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
body: formData
});
return await response.json();
}
}
// Initialize API client

View File

@@ -1,614 +0,0 @@
/**
* Authentication service for handling user login, logout, and token management
*
* This class provides a complete authentication solution using JWT tokens.
* It handles token storage, validation, automatic refresh, and authenticated
* API requests.
*/
class AuthService {
/**
* Initialises the authentication service
*
* Loads existing token and user data from localStorage and sets up
* automatic token refresh. This ensures the user stays logged in
* across page refreshes and that tokens are refreshed before they expire.
*/
constructor() {
this.token = localStorage.getItem('token');
this.refreshToken = localStorage.getItem('refreshToken');
this.user = JSON.parse(localStorage.getItem('user'));
this.isValidating = false;
this.loginAttempts = parseInt(localStorage.getItem('loginAttempts') || '0');
this.refreshing = false;
// Set up token refresh interval
this.setupTokenRefresh();
}
/**
* Sets up automatic token refresh
*
* Creates an interval that checks token validity every minute and
* refreshes it if needed. This helps prevent the user from being
* logged out due to token expiration during active use of the application.
*/
setupTokenRefresh() {
// Check token every minute
setInterval(() => {
this.checkAndRefreshToken();
}, 60000); // 1 minute
// Also check immediately
this.checkAndRefreshToken();
}
/**
* Checks if token needs refreshing and refreshes if needed
*
* This method examines the current token's expiry time and refreshes
* it if it's about to expire (within 5 minutes). This provides
* seamless authentication
*/
async checkAndRefreshToken() {
// Skip if already refreshing or no token exists
if (this.refreshing || !this.token || !this.refreshToken) return;
try {
this.refreshing = true;
// Check if token is about to expire (within 5 minutes)
const payload = this.parseJwt(this.token);
if (!payload || !payload.exp) return;
const expiryTime = payload.exp * 1000; // Convert to milliseconds
const currentTime = Date.now();
const timeToExpiry = expiryTime - currentTime;
// If token expires in less than 5 minutes, refresh it
if (timeToExpiry < 300000) { // 5 minutes in milliseconds
await this.refreshAccessToken();
}
} catch (error) {
console.error('Token refresh check failed:', error);
} finally {
this.refreshing = false;
}
}
/**
* Parses a JWT token to extract its payload
*
* This utility method decodes the JWT token without verifying
* its signature. It's used internally to check token expiry
* and extract user information.
*
* @param {string} token - The JWT token to parse
* @returns {Object|null} The decoded token payload or null if invalid
*/
parseJwt(token) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
} catch (error) {
return null;
}
}
/**
* Refreshes the access token using the refresh token
*
* This method sends the refresh token to the server to obtain
* a new access token when the current one is about to expire.
* It's a crucial part of maintaining persistent authentication.
*
* @returns {Promise<boolean>} True if refresh was successful, false otherwise
*/
async refreshAccessToken() {
if (!this.refreshToken) return false;
try {
console.log('Attempting to refresh access token...');
const formData = new FormData();
formData.append('action', 'refresh');
formData.append('refreshToken', this.refreshToken);
const response = await fetch('/logincontroller.php', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
body: formData
});
console.log('Token refresh response status:', response.status);
const data = await response.json();
console.log('Token refresh response data:', data);
if (data.valid && data.token) {
console.log('Token refresh successful');
this.token = data.token;
localStorage.setItem('token', data.token);
return true;
}
// If refresh failed, log out
if (!data.valid) {
console.log('Token refresh failed, logging out');
this.logout();
}
return false;
} catch (error) {
console.error('Token refresh error details:', error);
error_log('Token refresh failed:', error);
return false;
}
}
/**
* Authenticates a user with the provided credentials
*
* This method sends the login credentials to the server,
* stores the returned tokens and user data if successful,
* and updates the login attempts counter for CAPTCHA handling.
*
* @param {FormData} formData - The form data containing login credentials
* @returns {Promise<Object>} The login result
*/
async login(formData) {
try {
console.log('Attempting to login with URL:', '/logincontroller.php');
const response = await fetch('/logincontroller.php', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
body: formData
});
console.log('Login response status:', response.status);
const data = await response.json();
console.log('Login response data:', data);
if (data.error) {
// If server sends a new CAPTCHA, update it
if (data.captcha) {
const captchaCode = document.getElementById('captchaCode');
const captchaContainer = document.querySelector('.captcha-container');
if (captchaCode && captchaContainer) {
captchaCode.value = data.captcha;
captchaContainer.style.display = 'flex';
}
}
throw new Error(data.error);
}
if (data.success && data.token) {
this.token = data.token;
this.refreshToken = data.refreshToken;
this.user = data.user;
localStorage.setItem('token', data.token);
localStorage.setItem('refreshToken', data.refreshToken);
localStorage.setItem('user', JSON.stringify(data.user));
// Reset login attempts on successful login
localStorage.removeItem('loginAttempts');
// Handle redirect if provided
if (data.redirect) {
window.location.href = data.redirect;
}
return data.user;
}
throw new Error('Login failed');
} catch (error) {
console.error('Login error details:', error);
error_log('Login error:', error);
throw error;
}
}
/**
* Logs the user out
*
* This method clears all authentication data from localStorage
* and notifies the server about the logout. It also updates the
* UI to reflect the logged-out state.
*
* @returns {Promise<Object>} The logout result
*/
async logout() {
try {
const formData = new FormData();
formData.append('action', 'logout');
const response = await fetch('/logincontroller.php', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
body: formData
});
const data = await response.json();
if (!data.success) {
throw new Error('Logout failed');
}
this.token = null;
this.refreshToken = null;
this.user = null;
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
localStorage.removeItem('user');
// Handle redirect if provided
if (data.redirect) {
window.location.href = data.redirect;
}
} catch (error) {
error_log('Logout error:', error);
throw error;
}
}
/**
* Checks if the user is currently authenticated
*
* This is a simple helper method that returns true if
* the user object exists, indicating an authenticated user.
*
* @returns {boolean} True if authenticated, false otherwise
*/
isAuthenticated() {
return !!this.token;
}
/**
* Checks if the current user has admin privileges
*
* This helper method checks if the user is authenticated
* and has an access level of 1, which indicates admin status.
*
* @returns {boolean} True if the user is an admin, false otherwise
*/
isAdmin() {
return this.user && this.user.accessLevel === 1;
}
/**
* Checks if CAPTCHA is required for login
*
* This method determines if a CAPTCHA should be shown during login
* based on the number of failed login attempts. This helps prevent
* brute force attacks on the login system.
*
* @returns {boolean} True if CAPTCHA is required, false otherwise
*/
needsCaptcha() {
return this.loginAttempts >= 3;
}
/**
* Validates the current token with the server
*
* This method checks if the current token is still valid by
* making a request to the server. It's used to verify authentication
* status when the application loads.
*
* @returns {Promise<boolean>} True if token is valid, false otherwise
*/
async validateToken() {
// Skip validation if no token exists
if (!this.token) return false;
// Prevent multiple simultaneous validations
if (this.isValidating) return true;
try {
console.log('Validating token...');
this.isValidating = true;
const response = await fetch('/auth.php', {
headers: {
'Authorization': `Bearer ${this.token}`
}
});
console.log('Token validation response status:', response.status);
const data = await response.json();
console.log('Token validation response data:', data);
// Handle invalid token
if (!response.ok || !data.valid) {
console.log('Token is invalid, attempting to refresh...');
// Try to refresh the token
if (this.refreshToken) {
console.log('Refresh token exists, attempting to refresh...');
const refreshed = await this.refreshAccessToken();
if (refreshed) {
console.log('Token refreshed successfully');
return true;
}
}
console.log('Token refresh failed, logging out');
this.logout();
return false;
}
console.log('Token is valid');
return true;
} catch (error) {
console.error('Token validation error details:', error);
error_log('Token validation error:', error);
return false;
} finally {
this.isValidating = false;
}
}
/**
* Gets the current user object
*
* This helper method returns the user object containing
* information about the authenticated user.
*
* @returns {Object|null} The user object or null if not authenticated
*/
getUser() {
console.log('Getting user from auth service:', this.user);
if (!this.user) {
// Try to get user from localStorage as a fallback
const localUser = localStorage.getItem('user');
console.log('User not found in auth service, checking localStorage:', localUser);
if (localUser) {
try {
this.user = JSON.parse(localUser);
} catch (e) {
console.error('Error parsing user from localStorage:', e);
}
}
}
return this.user;
}
/**
* Gets the current JWT token
*
* This helper method returns the current JWT token for
* use in authenticated API requests.
*
* @returns {string|null} The JWT token or null if not authenticated
*/
getToken() {
console.log('Getting token from auth service:', this.token);
if (!this.token) {
// Try to get token from localStorage as a fallback
const localToken = localStorage.getItem('token');
console.log('Token not found in auth service, checking localStorage:', localToken);
if (localToken) {
this.token = localToken;
}
}
return this.token;
}
/**
* Creates an authenticated fetch function
*
* This method returns a wrapper around the fetch API that
* automatically includes the JWT token in the Authorization header.
* It also handles token refresh if a request fails due to an expired token.
*
* @returns {Function} The authenticated fetch function
*/
createAuthFetch() {
return async (url, options = {}) => {
// Ensure options.headers exists
options.headers = options.headers || {};
// Add Authorization header if token exists
if (this.token) {
options.headers['Authorization'] = `Bearer ${this.token}`;
}
// Add X-Requested-With header for AJAX requests
options.headers['X-Requested-With'] = 'XMLHttpRequest';
try {
// Make the request
const response = await fetch(url, options);
// If unauthorized (401), try to refresh the token and retry
if (response.status === 401 && this.refreshToken) {
console.log('Received 401 response, attempting to refresh token...');
const refreshed = await this.refreshAccessToken();
if (refreshed) {
console.log('Token refreshed, retrying request...');
// Update Authorization header with new token
options.headers['Authorization'] = `Bearer ${this.token}`;
// Retry the request
return fetch(url, options);
}
console.log('Token refresh failed, returning 401 response');
}
return response;
} catch (error) {
console.error('Auth fetch error details:', error);
error_log('Auth fetch error:', error);
throw error;
}
};
}
/**
* Checks if the token is valid by parsing it
*
* This method checks if the token is valid by parsing it and checking
* if it has expired. It doesn't make a server request, so it's only
* a client-side check.
*
* @returns {boolean} True if the token is valid, false otherwise
*/
isTokenValid() {
const token = this.getToken();
if (!token) {
console.log('No token found');
return false;
}
try {
const payload = this.parseJwt(token);
console.log('Token payload:', payload);
if (!payload || !payload.exp) {
console.log('Token payload is invalid or missing expiry');
return false;
}
const now = Math.floor(Date.now() / 1000);
const isValid = payload.exp > now;
console.log('Token expiry:', new Date(payload.exp * 1000));
console.log('Current time:', new Date(now * 1000));
console.log('Token is valid:', isValid);
return isValid;
} catch (e) {
console.error('Error parsing token:', e);
return false;
}
}
}
// Initialize authentication service
const auth = new AuthService();
// Create authenticated fetch function
const authFetch = auth.createAuthFetch();
// Set up authentication handlers when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
console.log('DOM loaded, setting up authentication handlers');
// Get modal elements
const loginButton = document.querySelector('[data-bs-toggle="modal"]');
const loginModal = document.getElementById('loginModal');
// Set up login form handlers
const loginForm = document.querySelector('#loginModal form');
const loginError = document.querySelector('#loginError');
const captchaContainer = document.querySelector('.captcha-container');
if (loginForm) {
// Handle form submission
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(loginForm);
formData.append('action', 'login');
try {
await auth.login(formData);
// Hide modal before reload
const modal = bootstrap.Modal.getInstance(loginModal);
if (modal) {
modal.hide();
}
// Refresh the page using replace to prevent form resubmission
window.location.replace(window.location.href);
} catch (error) {
if (loginError) {
loginError.textContent = error.message;
loginError.style.display = 'block';
}
// Show CAPTCHA after 3 failed attempts
if (auth.needsCaptcha() && captchaContainer) {
captchaContainer.style.display = 'flex';
}
}
});
}
// Set up logout button handler
const logoutButton = document.getElementById('logoutButton');
if (logoutButton) {
logoutButton.addEventListener('click', async (e) => {
e.preventDefault();
try {
await auth.logout();
window.location.reload();
} catch (error) {
console.error('Logout failed:', error);
}
});
}
// Validate token if authenticated
if (auth.isAuthenticated()) {
console.log('User is authenticated, validating token...');
// Check if we're already in a validation cycle
const validationCycle = sessionStorage.getItem('validationCycle');
if (validationCycle) {
console.log('Already in validation cycle, forcing logout');
// We've already tried to validate in this page load
// Force a proper logout
sessionStorage.removeItem('validationCycle');
auth.logout().finally(() => {
window.location.replace('/');
});
return;
}
// Set validation cycle flag
sessionStorage.setItem('validationCycle', 'true');
auth.validateToken().then(valid => {
console.log('Token validation result:', valid);
if (!valid) {
console.log('Token is invalid, redirecting to login page');
// Token is invalid, redirect to login page
window.location.replace('/');
} else {
console.log('Token is valid, clearing validation cycle flag');
// Clear validation cycle flag
sessionStorage.removeItem('validationCycle');
}
});
} else {
console.log('User is not authenticated');
}
});
// Export auth service and authenticated fetch
window.auth = auth;
window.authFetch = authFetch;
// Make parseJwt accessible from outside
window.auth.parseJwt = auth.parseJwt.bind(auth);
/**
* Custom error logging function
*
* This utility function provides a consistent way to log errors
* throughout the application. It includes both a message and the
* error object for better debugging.
*
* @param {string} message - The error message
* @param {Error} error - The error object
*/
function error_log(message, error) {
console.error(message, error);
}

View File

@@ -1,471 +1,561 @@
/**
* Comments functionality for facility management
*/
document.addEventListener('DOMContentLoaded', function() {
console.log('Comments.js loaded');
// Initialize comment modal handlers
initializeCommentModals();
// Set up form handlers
setupCommentFormHandlers();
});
/**
* Initialize comment modals
*/
function initializeCommentModals() {
// Status modal (comments view)
const statusModal = document.getElementById('statusModal');
if (statusModal) {
statusModal.addEventListener('show.bs.modal', function(event) {
console.log('Comments modal is about to show');
// Get the button that triggered the modal
const button = event.relatedTarget;
// Get the facility ID from the data attribute
const facilityId = button.getAttribute('data-facility-id');
console.log('Facility ID for comments:', facilityId);
// Create a namespace for comments functionality
const CommentsManager = {
// Track initialization states
state: {
isInitializing: false,
isInitialized: false,
isDomReady: false,
isAuthReady: false
},
/**
* Initialize comments functionality
*/
initialize() {
if (this.state.isInitialized) return;
console.log('Initializing comments...');
// Initialize comment modal handlers
this.initializeCommentModals();
// Set up form handlers
this.setupCommentFormHandlers();
console.log('Comments initialized with auth state:', {
isAuthenticated: this.isAuthenticated(),
user: window.simpleAuth.getUser()
});
this.state.isInitialized = true;
},
/**
* Check if we can initialize
*/
checkInitialize() {
if (this.state.isDomReady && this.state.isAuthReady && !this.state.isInitializing) {
this.state.isInitializing = true;
this.initialize();
this.state.isInitializing = false;
}
},
/**
* Check if user is authenticated
*/
isAuthenticated() {
return window.simpleAuth && window.simpleAuth.isAuthenticated();
},
/**
* Initialize comment modals
*/
initializeCommentModals() {
// Status modal (comments view)
const statusModal = document.getElementById('statusModal');
if (statusModal) {
statusModal.addEventListener('show.bs.modal', (event) => {
console.log('Comments modal is about to show');
// Get the button that triggered the modal
const button = event.relatedTarget;
// Get the facility ID from the data attribute
const facilityId = button.getAttribute('data-facility-id');
console.log('Facility ID for comments:', facilityId);
if (!facilityId) {
console.error('No facility ID found for comments');
return;
}
// Set the facility ID in the comment form
const commentForm = document.getElementById('commentForm');
if (commentForm) {
const facilityIdInput = commentForm.querySelector('#commentFacilityId');
if (facilityIdInput) {
facilityIdInput.value = facilityId;
}
}
// Load facility comments
this.loadFacilityComments(facilityId);
});
}
// Edit comment modal
const editCommentModal = document.getElementById('editCommentModal');
if (editCommentModal) {
editCommentModal.addEventListener('show.bs.modal', (event) => {
console.log('Edit comment modal is about to show');
const button = event.relatedTarget;
const commentId = button.getAttribute('data-comment-id');
const commentText = button.getAttribute('data-comment-text');
console.log('Comment ID:', commentId, 'Comment text:', commentText);
// Set the comment ID and text in the form
const editForm = document.getElementById('editCommentForm');
if (editForm) {
const commentIdInput = editForm.querySelector('#editCommentId');
const commentTextArea = editForm.querySelector('#editCommentText');
if (commentIdInput && commentTextArea) {
commentIdInput.value = commentId;
commentTextArea.value = commentText;
}
}
});
}
},
/**
* Set up comment form handlers
*/
setupCommentFormHandlers() {
// Comment form handler
const commentForm = document.getElementById('commentForm');
if (commentForm) {
this.setupCommentFormHandler(commentForm);
}
// Edit comment form handler
const editCommentForm = document.getElementById('editCommentForm');
if (editCommentForm) {
this.setupEditCommentFormHandler(editCommentForm);
}
},
/**
* Set up a single comment form handler
*/
setupCommentFormHandler(commentForm) {
commentForm.addEventListener('submit', async (e) => {
e.preventDefault();
if (!facilityId) {
console.error('No facility ID found for comments');
// Prevent duplicate submissions
if (commentForm.submitting) {
return;
}
commentForm.submitting = true;
// Check if user is authenticated
if (!this.isAuthenticated()) {
alert('You must be logged in to add comments');
commentForm.submitting = false;
return;
}
// Set the facility ID in the comment form
const commentForm = document.getElementById('commentForm');
if (commentForm) {
const facilityIdInput = commentForm.querySelector('#commentFacilityId');
if (facilityIdInput) {
facilityIdInput.value = facilityId;
}
}
// Load facility comments
loadFacilityComments(facilityId);
});
}
// Edit comment modal
const editCommentModal = document.getElementById('editCommentModal');
if (editCommentModal) {
editCommentModal.addEventListener('show.bs.modal', function(event) {
console.log('Edit comment modal is about to show');
// The button that triggered the modal will pass data via dataset
const button = event.relatedTarget;
const commentId = button.getAttribute('data-comment-id');
const commentText = button.getAttribute('data-comment-text');
const formData = new FormData(commentForm);
console.log('Comment ID:', commentId, 'Comment text:', commentText);
// Get form data
const statusComment = formData.get('commentText');
const facilityId = formData.get('facilityId');
// Set the comment ID and text in the form
const editForm = document.getElementById('editCommentForm');
if (editForm) {
const commentIdInput = editForm.querySelector('#editCommentId');
const commentTextArea = editForm.querySelector('#editCommentText');
console.log('Comment form data:', { facilityId, statusComment });
try {
console.log('Sending comment request...');
// Use the API client to add a status comment
const data = await window.api.addFacilityStatus(facilityId, statusComment);
if (commentIdInput && commentTextArea) {
commentIdInput.value = commentId;
commentTextArea.value = commentText;
console.log('Comment response:', data);
if (data.success) {
console.log('Comment added successfully');
// Reset the form
commentForm.reset();
// Reload comments to show the new one
this.loadFacilityComments(facilityId);
} else {
console.error('Comment failed:', data.error);
alert(data.error || 'Failed to add comment');
}
} catch (error) {
console.error('Error adding comment:', error);
alert('Failed to add comment: ' + error.message);
} finally {
commentForm.submitting = false;
}
});
}
}
},
/**
* Set up comment form handlers
*/
function setupCommentFormHandlers() {
// Comment form handler
const commentForm = document.getElementById('commentForm');
if (commentForm) {
setupCommentFormHandler(commentForm);
}
// Edit comment form handler
const editCommentForm = document.getElementById('editCommentForm');
if (editCommentForm) {
setupEditCommentFormHandler(editCommentForm);
}
}
/**
* Set up a single comment form handler
* @param {HTMLFormElement} commentForm - The comment form element
*/
function setupCommentFormHandler(commentForm) {
commentForm.addEventListener('submit', async function(e) {
e.preventDefault();
// Prevent duplicate submissions
if (this.submitting) {
return;
}
this.submitting = true;
// Check if user is authenticated
if (!isAuthenticated()) {
alert('You must be logged in to add comments');
this.submitting = false;
return;
}
const formData = new FormData(this);
// Get form data
const commentText = formData.get('commentText');
const facilityId = formData.get('facilityId');
console.log('Comment form data:', { facilityId, commentText });
try {
console.log('Sending comment request...');
// Use the API client to add a status comment
const data = await window.api.addFacilityStatus(facilityId, commentText);
/**
* Set up a single edit comment form handler
*/
setupEditCommentFormHandler(editCommentForm) {
editCommentForm.addEventListener('submit', async (e) => {
e.preventDefault();
console.log('Comment response:', data);
if (data.success) {
console.log('Comment added successfully');
// Reset the form
this.reset();
// Reload comments to show the new one
loadFacilityComments(facilityId);
} else {
console.error('Comment failed:', data.error);
alert(data.error || 'Failed to add comment');
// Prevent duplicate submissions
if (editCommentForm.submitting) {
return;
}
} catch (error) {
console.error('Error adding comment:', error);
alert('Failed to add comment: ' + error.message);
} finally {
this.submitting = false;
}
});
}
/**
* Set up a single edit comment form handler
* @param {HTMLFormElement} editCommentForm - The edit comment form element
*/
function setupEditCommentFormHandler(editCommentForm) {
editCommentForm.addEventListener('submit', async function(e) {
e.preventDefault();
// Prevent duplicate submissions
if (this.submitting) {
return;
}
this.submitting = true;
// Check if user is authenticated
if (!isAuthenticated()) {
alert('You must be logged in to edit comments');
this.submitting = false;
return;
}
const formData = new FormData(this);
// Get form data
const commentText = formData.get('editCommentText');
const commentId = formData.get('commentId');
const facilityId = document.getElementById('commentFacilityId').value;
console.log('Edit comment form data:', { commentId, facilityId, commentText });
try {
console.log('Sending edit comment request...');
// Use the API client to update a status comment
const data = await window.api.updateFacilityStatus(commentId, commentText, facilityId);
editCommentForm.submitting = true;
console.log('Edit comment response:', data);
// Check if user is authenticated
if (!this.isAuthenticated()) {
alert('You must be logged in to edit comments');
editCommentForm.submitting = false;
return;
}
const formData = new FormData(editCommentForm);
if (data.success) {
console.log('Comment edited successfully');
// Get form data
const commentText = formData.get('editCommentText');
const commentId = formData.get('commentId');
const facilityId = document.getElementById('commentFacilityId').value;
console.log('Edit comment form data:', { commentId, facilityId, commentText });
try {
console.log('Sending edit comment request...');
// Use the API client to update a status comment
const data = await window.api.updateFacilityStatus(commentId, commentText, facilityId);
// Close the edit modal
const editModal = bootstrap.Modal.getInstance(document.getElementById('editCommentModal'));
if (editModal) {
editModal.hide();
console.log('Edit comment response:', data);
if (data.success) {
console.log('Comment edited successfully');
// Close the edit modal
const editModal = bootstrap.Modal.getInstance(document.getElementById('editCommentModal'));
if (editModal) {
editModal.hide();
}
// Reload comments to show the updated one
this.loadFacilityComments(facilityId);
} else {
console.error('Edit comment failed:', data.error);
alert(data.error || 'Failed to edit comment');
}
// Reload comments to show the updated one
loadFacilityComments(facilityId);
} else {
console.error('Edit comment failed:', data.error);
alert(data.error || 'Failed to edit comment');
} catch (error) {
console.error('Error editing comment:', error);
alert('Failed to edit comment: ' + error.message);
} finally {
editCommentForm.submitting = false;
}
} catch (error) {
console.error('Error editing comment:', error);
alert('Failed to edit comment: ' + error.message);
} finally {
this.submitting = false;
}
});
}
});
},
/**
* Creates a comment form dynamically for authenticated users
* @param {string} facilityId - The facility ID
*/
function createCommentFormForAuthenticatedUser(facilityId) {
// Check if user is authenticated
if (!isAuthenticated()) {
return `
<div class="alert alert-info mb-0">
<i class="bi bi-info-circle me-2"></i>
Please <a href="#" data-bs-toggle="modal" data-bs-target="#loginModal">login</a> to add comments.
</div>
`;
}
// Create the comment form
return `
<form id="commentForm" class="mt-3">
<input type="hidden" id="commentFacilityId" name="facilityId" value="${escapeHtml(facilityId)}">
<div class="mb-3">
<label for="commentText" class="form-label">Add a Comment</label>
<textarea class="form-control" id="commentText" name="commentText" rows="3" required></textarea>
</div>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-success">
<i class="bi bi-chat-dots-fill me-1"></i>
Add Comment
</button>
</div>
</form>
`;
}
/**
* Creates a comment form dynamically for authenticated users
*/
createCommentFormForAuthenticatedUser(facilityId) {
// Add detailed logging of auth state
console.log('Creating comment form with auth state:', {
simpleAuthExists: !!window.simpleAuth,
simpleAuthMethods: window.simpleAuth ? Object.keys(window.simpleAuth) : null,
token: window.simpleAuth ? window.simpleAuth.getToken() : null,
user: window.simpleAuth ? window.simpleAuth.getUser() : null,
localStorage: {
token: localStorage.getItem('token'),
user: localStorage.getItem('user')
}
});
/**
* Checks if the current user is authenticated
* @returns {boolean} True if authenticated, false otherwise
*/
function isAuthenticated() {
// Use the auth service to check authentication
return window.auth.isAuthenticated();
}
/**
* Loads facility comments from the server
* @param {string} facilityId - The facility ID
*/
async function loadFacilityComments(facilityId) {
try {
console.log('Loading comments for facility:', facilityId);
// Show loading indicator
const commentsContainer = document.getElementById('commentsContainer');
if (commentsContainer) {
commentsContainer.innerHTML = `
<div class="text-center py-4">
<div class="spinner-border text-success" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2 text-muted">Loading comments...</p>
// First check if simpleAuth is available
if (!window.simpleAuth) {
console.warn('SimpleAuth not initialized yet');
return `
<div class="alert alert-warning mb-0">
<i class="bi bi-hourglass-split me-2"></i>
Loading authentication status...
</div>
`;
}
// Use the API client to get facility statuses
const data = await window.api.getFacilityStatuses(facilityId);
console.log('Comments loaded:', data);
if (data.success) {
// Validate authentication state
try {
const token = window.simpleAuth.getToken();
const user = window.simpleAuth.getUser();
const isAuthenticated = window.simpleAuth.isAuthenticated();
console.log('Authentication validation:', {
hasToken: !!token,
hasUser: !!user,
isAuthenticated: isAuthenticated
});
if (!isAuthenticated || !token || !user) {
console.log('User not authenticated:', { isAuthenticated, token: !!token, user: !!user });
return `
<div class="alert alert-info mb-0">
<i class="bi bi-info-circle me-2"></i>
Please <a href="#" data-bs-toggle="modal" data-bs-target="#loginModal">login</a> to add comments.
</div>
`;
}
// User is authenticated, create the comment form
console.log('User is authenticated, creating comment form');
return `
<form id="commentForm" class="mt-3">
<input type="hidden" id="commentFacilityId" name="facilityId" value="${this.escapeHtml(facilityId)}">
<div class="mb-3">
<label for="commentText" class="form-label">Add a Comment</label>
<textarea class="form-control" id="commentText" name="commentText" rows="3" required></textarea>
</div>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-success">
<i class="bi bi-chat-dots-fill me-1"></i>
Add Comment
</button>
</div>
</form>
`;
} catch (error) {
console.error('Error checking authentication:', error);
return `
<div class="alert alert-danger mb-0">
<i class="bi bi-exclamation-triangle me-2"></i>
Error checking authentication status. Please try refreshing the page.
</div>
`;
}
},
/**
* Loads facility comments from the server
*/
async loadFacilityComments(facilityId) {
try {
console.log('Loading comments for facility:', facilityId);
// Show loading indicator
const commentsContainer = document.getElementById('commentsContainer');
if (commentsContainer) {
commentsContainer.innerHTML = `
<div class="text-center py-4">
<div class="spinner-border text-success" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2 text-muted">Loading comments...</p>
</div>
`;
}
// Use the API client to get facility statuses
const data = await window.api.getFacilityStatuses(facilityId);
console.log('Comments API response:', data);
// Validate the response
if (!data || typeof data !== 'object') {
throw new Error('Invalid response from server');
}
if (!data.success) {
throw new Error(data.error || 'Failed to load comments');
}
if (!Array.isArray(data.statuses)) {
throw new Error('Invalid comments data format');
}
// Render the comments
renderComments(data.statuses, facilityId);
} else {
console.error('Failed to load comments:', data.error);
this.renderComments(data.statuses, facilityId);
} catch (error) {
console.error('Error loading comments:', error);
console.error('Error stack:', error.stack);
const commentsContainer = document.getElementById('commentsContainer');
if (commentsContainer) {
commentsContainer.innerHTML = `
<div class="alert alert-danger">
<i class="bi bi-exclamation-triangle me-2"></i>
Failed to load comments: ${data.error || 'Unknown error'}
${error.message}
</div>
`;
}
}
} catch (error) {
console.error('Error loading comments:', error);
},
/**
* Renders comments in the comments container
*/
renderComments(comments, facilityId) {
const commentsContainer = document.getElementById('commentsContainer');
if (commentsContainer) {
commentsContainer.innerHTML = `
<div class="alert alert-danger">
<i class="bi bi-exclamation-triangle me-2"></i>
Error loading comments: ${error.message}
if (!commentsContainer) return;
// Clear the container
commentsContainer.innerHTML = '';
// Add the comment form for authenticated users
commentsContainer.innerHTML += this.createCommentFormForAuthenticatedUser(facilityId);
// If no comments, show a message
if (!comments || comments.length === 0) {
commentsContainer.innerHTML += `
<div class="alert alert-light mt-3">
<i class="bi bi-chat-dots me-2"></i>
No comments yet. Be the first to add a comment!
</div>
`;
return;
}
}
}
/**
* Renders comments in the comments container
* @param {Array} comments - Array of comment objects
* @param {string} facilityId - The facility ID
*/
function renderComments(comments, facilityId) {
const commentsContainer = document.getElementById('commentsContainer');
if (!commentsContainer) return;
// Clear the container
commentsContainer.innerHTML = '';
// Add the comment form for authenticated users
commentsContainer.innerHTML += createCommentFormForAuthenticatedUser(facilityId);
// If no comments, show a message
if (!comments || comments.length === 0) {
commentsContainer.innerHTML += `
<div class="alert alert-light mt-3">
<i class="bi bi-chat-dots me-2"></i>
No comments yet. Be the first to add a comment!
</div>
`;
return;
}
// Create the comments list
const commentsList = document.createElement('div');
commentsList.className = 'comments-list mt-4';
// Add each comment
comments.forEach(comment => {
const commentElement = document.createElement('div');
commentElement.className = 'comment-item card mb-3 border-0 shadow-sm';
// Format the date
const date = new Date(comment.timestamp);
const formattedDate = date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
// Create the comments list
const commentsList = document.createElement('div');
commentsList.className = 'comments-list mt-4';
// Add each comment
comments.forEach(comment => {
const commentElement = document.createElement('div');
commentElement.className = 'comment-item card mb-3 border-0 shadow-sm';
// Check if the current user is the comment author or an admin
const canEdit = this.isAdmin() || this.isCurrentUser(comment.username);
commentElement.innerHTML = `
<div class="card-body">
<div class="d-flex justify-content-between align-items-start mb-2">
<div class="d-flex align-items-center">
<div class="comment-avatar bg-light rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 32px; height: 32px;">
<i class="bi bi-person-fill text-secondary"></i>
</div>
<div>
<h6 class="mb-0 fw-bold">${this.escapeHtml(comment.username)}</h6>
</div>
</div>
${canEdit ? `
<div class="dropdown">
<button class="btn btn-sm btn-light" type="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-three-dots-vertical"></i>
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li>
<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#editCommentModal" data-comment-id="${comment.id}" data-comment-text="${this.escapeHtml(comment.statusComment)}">
<i class="bi bi-pencil me-2"></i>Edit
</button>
</li>
<li>
<button class="dropdown-item text-danger" type="button" onclick="CommentsManager.deleteComment('${comment.id}', '${facilityId}')">
<i class="bi bi-trash me-2"></i>Delete
</button>
</li>
</ul>
</div>
` : ''}
</div>
<p class="mb-0">${this.escapeHtml(comment.statusComment)}</p>
</div>
`;
commentsList.appendChild(commentElement);
});
// Check if the current user is the comment author or an admin
const canEdit = isAdmin() || isCurrentUser(comment.username);
commentsContainer.appendChild(commentsList);
commentElement.innerHTML = `
<div class="card-body">
<div class="d-flex justify-content-between align-items-start mb-2">
<div class="d-flex align-items-center">
<div class="comment-avatar bg-light rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 32px; height: 32px;">
<i class="bi bi-person-fill text-secondary"></i>
</div>
<div>
<h6 class="mb-0 fw-bold">${escapeHtml(comment.username)}</h6>
<small class="text-muted">${formattedDate}</small>
</div>
</div>
${canEdit ? `
<div class="dropdown">
<button class="btn btn-sm btn-light" type="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-three-dots-vertical"></i>
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li>
<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#editCommentModal" data-comment-id="${comment.id}" data-comment-text="${escapeHtml(comment.comment)}">
<i class="bi bi-pencil me-2"></i>Edit
</button>
</li>
<li>
<button class="dropdown-item text-danger" type="button" onclick="deleteComment('${comment.id}', '${facilityId}')">
<i class="bi bi-trash me-2"></i>Delete
</button>
</li>
</ul>
</div>
` : ''}
</div>
<p class="mb-0">${escapeHtml(comment.comment)}</p>
</div>
`;
// Re-initialize the comment form handler
const commentForm = document.getElementById('commentForm');
if (commentForm) {
this.setupCommentFormHandler(commentForm);
}
},
/**
* Deletes a comment
*/
async deleteComment(commentId, facilityId) {
// Confirm deletion
if (!confirm('Are you sure you want to delete this comment?')) {
return;
}
commentsList.appendChild(commentElement);
try {
console.log('Deleting comment:', commentId, 'for facility:', facilityId);
// Use the API client to delete a status comment
const data = await window.api.deleteFacilityStatus(commentId, facilityId);
console.log('Delete comment response:', data);
if (data.success) {
console.log('Comment deleted successfully');
// Reload comments to reflect the deletion
this.loadFacilityComments(facilityId);
} else {
console.error('Delete comment failed:', data.error);
alert(data.error || 'Failed to delete comment');
}
} catch (error) {
console.error('Error deleting comment:', error);
alert('Failed to delete comment: ' + error.message);
}
},
/**
* Checks if the current user is an admin
*/
isAdmin() {
return window.simpleAuth && window.simpleAuth.isAdmin();
},
/**
* Checks if the given username matches the current user
*/
isCurrentUser(username) {
const user = window.simpleAuth && window.simpleAuth.getUser();
return user && user.username === username;
},
/**
* Safely escapes HTML special characters to prevent XSS attacks
*/
escapeHtml(unsafe) {
if (unsafe === null || unsafe === undefined) {
return '';
}
return unsafe
.toString()
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
};
// Listen for DOM ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
CommentsManager.state.isDomReady = true;
CommentsManager.checkInitialize();
});
} else {
CommentsManager.state.isDomReady = true;
CommentsManager.checkInitialize();
}
// Listen for simpleAuth ready
if (window.simpleAuth) {
CommentsManager.state.isAuthReady = true;
CommentsManager.checkInitialize();
} else {
window.addEventListener('simpleAuthReady', () => {
console.log('SimpleAuth is now ready');
CommentsManager.state.isAuthReady = true;
CommentsManager.checkInitialize();
});
commentsContainer.appendChild(commentsList);
// Re-initialize the comment form handler
const commentForm = document.getElementById('commentForm');
if (commentForm) {
setupCommentFormHandler(commentForm);
}
}
/**
* Deletes a comment
* @param {string} commentId - The comment ID
* @param {string} facilityId - The facility ID
*/
async function deleteComment(commentId, facilityId) {
// Confirm deletion
if (!confirm('Are you sure you want to delete this comment?')) {
return;
}
try {
console.log('Deleting comment:', commentId, 'for facility:', facilityId);
// Use the API client to delete a status comment
const data = await window.api.deleteFacilityStatus(commentId, facilityId);
console.log('Delete comment response:', data);
if (data.success) {
console.log('Comment deleted successfully');
// Reload comments to reflect the deletion
loadFacilityComments(facilityId);
} else {
console.error('Delete comment failed:', data.error);
alert(data.error || 'Failed to delete comment');
// Fallback timeout in case the event doesn't fire
setTimeout(() => {
if (!CommentsManager.state.isAuthReady && window.simpleAuth) {
console.log('SimpleAuth found via timeout check');
CommentsManager.state.isAuthReady = true;
CommentsManager.checkInitialize();
}
} catch (error) {
console.error('Error deleting comment:', error);
alert('Failed to delete comment: ' + error.message);
}
}, 1000);
}
/**
* Checks if the current user is an admin
* @returns {boolean} True if admin, false otherwise
*/
function isAdmin() {
// Use the auth service to check if user is admin
return window.auth.isAdmin();
}
/**
* Checks if the given username matches the current user
* @param {string} username - The username to check
* @returns {boolean} True if current user, false otherwise
*/
function isCurrentUser(username) {
const user = window.auth.getUser();
return user && user.username === username;
}
/**
* Safely escapes HTML special characters to prevent XSS attacks
* @param {*} unsafe - The value to escape
* @returns {string} The escaped string
*/
function escapeHtml(unsafe) {
if (unsafe === null || unsafe === undefined) {
return '';
}
return unsafe
.toString()
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
// Export the CommentsManager to the window object
window.CommentsManager = CommentsManager;

View File

@@ -17,40 +17,49 @@ function initialiseFacilityData(data, force = false) {
}
// Store the data in sessionStorage for persistence
sessionStorage.setItem('facilityData', JSON.stringify(data));
// Ensure table exists
const table = document.querySelector('#facilityTable');
if (!table) {
console.error('Table not found in DOM. Available elements:',
Array.from(document.querySelectorAll('table')).map(t => t.id || 'no-id'));
throw new Error('Facility table not found in DOM');
}
// Clear existing table content
const tbody = table.querySelector('tbody');
if (tbody) {
tbody.innerHTML = '';
} else {
console.warn('No tbody found in table, creating one');
const newTbody = document.createElement('tbody');
table.appendChild(newTbody);
}
// Initialize filteredData with all data
filteredData = data;
// Calculate total pages
totalPages = Math.ceil(filteredData.length / itemsPerPage);
// Set current page to 1
currentPage = 1;
// Update table with paginated data
updateTableWithPagination();
// Check if we're on the map page
const isMapPage = window.location.pathname.includes('map.php');
if (!isMapPage) {
// Only try to initialize table if we're not on the map page
const table = document.querySelector('#facilityTable');
if (!table) {
console.error('Table not found in DOM. Available elements:',
Array.from(document.querySelectorAll('table')).map(t => t.id || 'no-id'));
throw new Error('Facility table not found in DOM');
}
// Clear existing table content
const tbody = table.querySelector('tbody');
if (tbody) {
tbody.innerHTML = '';
} else {
console.warn('No tbody found in table, creating one');
const newTbody = document.createElement('tbody');
table.appendChild(newTbody);
}
// Set up table controls (sorting and filtering)
setupTableControls();
// Initialize filteredData with all data
filteredData = data;
// Calculate total pages
totalPages = Math.ceil(filteredData.length / itemsPerPage);
// Set current page to 1
currentPage = 1;
// Update table with paginated data
updateTable();
// Set up table controls (sorting and filtering)
setupTableControls();
}
// Mark as initialized
isInitialized = true;
} catch (error) {
error_log('Error initialising facility data:', error);
console.error('Error initialising facility data:', error);
// Don't throw error if we're on map page, as table errors are expected
if (!window.location.pathname.includes('map.php')) {
throw error;
}
}
}
@@ -68,6 +77,10 @@ function renderFacilityTable(data) {
// Clear existing table content
tbody.innerHTML = '';
// Check if user is admin
const userIsAdmin = isAdmin();
console.log('renderFacilityTable - userIsAdmin:', userIsAdmin);
// Render each row
data.forEach((facility, index) => {
if (!facility) return;
@@ -82,9 +95,22 @@ function renderFacilityTable(data) {
// Create category badge with color based on category
const categoryClass = getCategoryColorClass(facility.category);
row.innerHTML = `
<td class="d-none">${escapeHtml(facility.id)}</td>
<td class="fw-medium align-middle" style="width: 15%;">
// Start building the row HTML
let rowHtml = '';
// Only show ID column for admins
if (userIsAdmin) {
console.log('Adding ID column for facility:', facility.id);
rowHtml += `
<td class="fw-medium align-middle text-center" style="width: 40px;">
${escapeHtml(facility.id)}
</td>
`;
}
// Add the rest of the columns
rowHtml += `
<td class="fw-medium align-middle" style="${userIsAdmin ? 'width: 15%;' : 'width: 17%;'}">
<div class="d-flex align-items-center h-100">
<div class="facility-icon me-2 rounded-circle bg-light d-flex align-items-center justify-content-center" style="width: 28px; height: 28px; min-width: 28px;">
<i class="${getFacilityIcon(facility.category)} text-${categoryClass}"></i>
@@ -92,14 +118,14 @@ function renderFacilityTable(data) {
<span class="text-truncate" style="max-width: calc(100% - 35px);">${escapeHtml(facility.title)}</span>
</div>
</td>
<td class="text-center align-middle" style="width: 10%;">
<td class="text-center align-middle" style="${userIsAdmin ? 'width: 10%;' : 'width: 11%;'}">
<div class="d-flex align-items-center justify-content-center h-100">
<span class="badge bg-${categoryClass} bg-opacity-10 text-${categoryClass} px-2 py-1 rounded-pill">
${escapeHtml(facility.category)}
</span>
</div>
</td>
<td class="align-middle" style="width: 25%;">
<td class="align-middle" style="${userIsAdmin ? 'width: 25%;' : 'width: 27%;'}">
<div class="description-container d-flex flex-column justify-content-center">
<div class="cell-content" data-full-text="${escapeHtml(facility.description)}">
${escapeHtml(facility.description)}
@@ -118,16 +144,15 @@ function renderFacilityTable(data) {
</div>
</div>
</td>
<td class="small fw-medium text-center align-middle" style="width: 8%;" hidden>${escapeHtml(facility.postcode)}</td>
<td class="small text-nowrap text-center align-middle" style="width: 12%;">
<td class="small text-nowrap text-center align-middle" style="${userIsAdmin ? 'width: 12%;' : 'width: 12%;'}">
<span class="badge bg-light text-dark border">
${escapeHtml(coordinates)}
</span>
</td>
<td class="small text-center align-middle" style="width: 8%;">${escapeHtml(facility.contributor)}</td>
<td class="text-center align-middle" style="width: 10%;">
<td class="text-center align-middle" style="${userIsAdmin ? 'width: 10%;' : 'width: 5%;'}">
<div class="d-flex justify-content-center gap-1">
${isAdmin() ? `
${userIsAdmin ? `
<button type="button" class="btn btn-sm btn-outline-primary update-btn rounded-circle d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;" data-bs-toggle="modal" data-bs-target="#updateModal" data-facility-id="${facility.id}" title="Edit">
<span class="bi bi-pen-fill"></span>
</button>
@@ -141,15 +166,17 @@ function renderFacilityTable(data) {
</div>
</td>
`;
row.innerHTML = rowHtml;
tbody.appendChild(row);
});
// If no data, show a message
if (data.length === 0) {
const emptyRow = document.createElement('tr');
const colSpan = userIsAdmin ? 8 : 7; // Adjust colspan based on number of columns
emptyRow.innerHTML = `
<td colspan="9" class="text-center py-4 text-muted">
<td colspan="${colSpan}" class="text-center py-4 text-muted">
<div class="d-flex flex-column align-items-center">
<span class="bi bi-inbox fs-2 mb-2"></span>
<p class="mb-0">No facilities found</p>
@@ -204,10 +231,15 @@ function formatAddress(facility) {
* @returns {boolean} True if user is admin, false otherwise
*/
function isAdmin() {
console.log('Checking admin status...');
// Check if auth service is available and has user data
if (window.auth && window.auth.getUser()) {
const authUser = window.auth.getUser();
if (simpleAuth && simpleAuth.getUser()) {
const authUser = simpleAuth.getUser();
console.log('Auth service user data:', authUser);
console.log('Auth service accessLevel:', authUser.accessLevel);
console.log('Auth service isAdmin check:', authUser.accessLevel === 1 || authUser.accessLevel === 0);
if (authUser && (authUser.accessLevel === 1 || authUser.accessLevel === 0)) {
console.log('User is admin according to auth service');
return true;
@@ -217,17 +249,26 @@ function isAdmin() {
// Fallback to localStorage
const user = JSON.parse(localStorage.getItem('user') || '{}');
console.log('Checking admin status from localStorage:', user);
const isAdminUser = user && (user.accessLevel === 1 || user.accessLevel === 0);
console.log('Is admin according to localStorage:', isAdminUser);
console.log('localStorage accessLevel:', user.accessLevel);
console.log('localStorage isAdmin check:', user.accessLevel === 1 || user.accessLevel === 0);
const isAdminUser = user && (user.accessLevel === 1 || user.accessLevel === 0);
console.log('Final isAdmin result:', isAdminUser);
return isAdminUser;
}
/**
* Checks if the current user is authenticated
* (helper function) Checks if the current user is authenticated
* @returns {boolean} True if authenticated, false otherwise
*/
function isAuthenticated() {
// Check if auth service is available
if (simpleAuth) {
return simpleAuth.isAuthenticated();
}
// Fallback to localStorage
const token = localStorage.getItem('token');
return !!token;
}
@@ -395,8 +436,8 @@ function setupFormHandlers() {
// Set the contributor to the current user's username
formData.set('contCreate', JSON.parse(localStorage.getItem('user'))?.username);
try {
// Use authFetch instead of regular fetch
const response = await window.authFetch('/facilitycontroller.php', {
// Use simpleAuth.fetchAuth for authenticated requests
const response = await simpleAuth.fetchAuth('/facilitycontroller.php', {
method: 'POST',
body: formData
});
@@ -493,8 +534,8 @@ function setupFormHandlers() {
}
try {
// Use authFetch instead of regular fetch
const response = await window.authFetch('/facilitycontroller.php', {
// Use simpleAuth.fetchAuth for authenticated requests
const response = await simpleAuth.fetchAuth('/facilitycontroller.php', {
method: 'POST',
body: serverFormData
});
@@ -582,19 +623,19 @@ function setupFormHandlers() {
try {
// Check if token is valid
if (!window.auth) {
if (!simpleAuth) {
throw new Error('Auth service not available');
}
// Validate token with server before proceeding
console.log('Validating token with server...');
const isValid = await window.auth.validateToken();
const isValid = await simpleAuth.validateToken();
if (!isValid) {
throw new Error('Authentication token is invalid or expired');
}
// Get token after validation to ensure it's fresh
const token = window.auth.getToken();
const token = simpleAuth.getToken();
console.log('Using token for delete request:', token);
if (!token) {
@@ -602,16 +643,16 @@ function setupFormHandlers() {
}
// Decode token to check payload
if (window.auth.parseJwt) {
const payload = window.auth.parseJwt(token);
if (simpleAuth.parseJwt) {
const payload = simpleAuth.parseJwt(token);
console.log('Token payload:', payload);
console.log('Access level:', payload.accessLevel);
console.log('Is admin check:', payload.accessLevel === 0 || payload.accessLevel === 1);
}
// Use direct fetch with manual token inclusion
// Use simpleAuth.fetchAuth for authenticated requests
console.log('Sending delete request to server...');
const response = await fetch('/facilitycontroller.php', {
const response = await simpleAuth.fetchAuth('/facilitycontroller.php', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
@@ -1112,86 +1153,5 @@ function getCategoryColorClass(category) {
return 'secondary';
}
/**
* Sets up expandable content for a table row
* @param {HTMLElement} row - The table row element
*/
function setupExpandableContent(row) {
// Setup description expansion
const descriptionContent = row.querySelector('.cell-content');
const toggleBtn = row.querySelector('.toggle-content-btn');
if (descriptionContent) {
// Make description expandable on click
descriptionContent.addEventListener('click', function() {
this.classList.toggle('expanded');
// Update button text if it exists
if (toggleBtn) {
toggleBtn.querySelector('small').textContent =
this.classList.contains('expanded') ? 'Show less' : 'Show more';
}
// Ensure proper alignment when expanded
const container = this.closest('.description-container');
if (container) {
if (this.classList.contains('expanded')) {
container.classList.remove('justify-content-center');
container.classList.add('justify-content-start');
} else {
container.classList.remove('justify-content-start');
container.classList.add('justify-content-center');
}
}
});
// Setup toggle button if it exists
if (toggleBtn) {
toggleBtn.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
const content = this.closest('.description-container').querySelector('.cell-content');
content.classList.toggle('expanded');
this.querySelector('small').textContent =
content.classList.contains('expanded') ? 'Show less' : 'Show more';
// Ensure proper alignment when expanded
const container = content.closest('.description-container');
if (container) {
if (content.classList.contains('expanded')) {
container.classList.remove('justify-content-center');
container.classList.add('justify-content-start');
} else {
container.classList.remove('justify-content-start');
container.classList.add('justify-content-center');
}
}
});
}
}
// Setup address expansion
const addressContent = row.querySelector('.address-content');
if (addressContent) {
addressContent.addEventListener('click', function() {
this.classList.toggle('expanded');
// Ensure proper alignment when expanded
const container = this.closest('.d-flex');
if (container) {
if (this.classList.contains('expanded')) {
container.classList.remove('align-items-center');
container.classList.add('align-items-start');
} else {
container.classList.remove('align-items-start');
container.classList.add('align-items-center');
}
}
});
}
}
// Export the initialization function
window.initializeFacilityData = initialiseFacilityData;

View File

@@ -1,8 +1,8 @@
/**
* Simplified Authentication Helper
* Authentication Worker
*
* This provides a streamlined authentication solution that works with
* the simplified server-side authentication approach.
* I admit JWT is unnecessary, but I did it anyway because it was interesting
* and I wanted to try it out.
*/
class SimpleAuth {
/**
@@ -11,6 +11,103 @@ class SimpleAuth {
constructor() {
this.token = localStorage.getItem('token');
this.user = JSON.parse(localStorage.getItem('user') || 'null');
this.loginAttempts = parseInt(localStorage.getItem('loginAttempts') || '0');
this.isValidating = false;
this.validationPromise = null;
// Generate a browser fingerprint
this.browserFingerprint = this._generateFingerprint();
// Check if the stored fingerprint matches the current browser
const storedFingerprint = localStorage.getItem('browserFingerprint');
if (this.token && (!storedFingerprint || storedFingerprint !== this.browserFingerprint)) {
// Fingerprint mismatch - potential token theft
console.warn('Browser fingerprint mismatch - clearing authentication');
this.logout(false); // Silent logout (no redirect)
}
// Log initialization
console.log('SimpleAuth initialized:', {
isAuthenticated: this.isAuthenticated(),
user: this.user
});
}
/**
* Generate a simple browser fingerprint, super unnecessary and out of scope
* but it was simple and hardens the authentication a bit.
* @private
* @returns {string} A fingerprint based on browser properties
*/
_generateFingerprint() {
const components = [
navigator.userAgent,
navigator.language,
screen.colorDepth,
screen.width + 'x' + screen.height,
new Date().getTimezoneOffset()
];
// Create a hash of the components
let hash = 0;
const str = components.join('|');
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return hash.toString(16);
}
/**
* Validate token on page load, this is to prevent XSS attacks. (During testing
* copying the tokens and userdata, and setting the localStorage manually on a
* new browser automatically logged me in.)
* This should be called when the page loads to ensure the token is valid
* @returns {Promise<boolean>} True if token is valid, false otherwise
*/
async validateOnLoad() {
// If already validating, return the existing promise
if (this.isValidating) {
return this.validationPromise;
}
// If no token, no need to validate since not logged in
if (!this.token) {
return false;
}
// Set validating flag and create promise
this.isValidating = true;
this.validationPromise = (async () => {
try {
const isValid = await this.validateToken();
if (!isValid) {
// Token is invalid, try to refresh it
const refreshed = await this.refreshToken();
if (!refreshed) {
// Refresh failed, logout
this.logout(false); // Silent logout (no redirect)
return false;
}
return true;
}
return isValid;
} catch (error) {
console.error('Token validation error:', error);
this.logout(false); // Silent logout (no redirect)
return false;
} finally {
this.isValidating = false;
this.validationPromise = null;
}
})();
return this.validationPromise;
}
/**
@@ -34,13 +131,48 @@ class SimpleAuth {
}
/**
* Login a user
* @param {object} credentials - The user credentials (username, password)
* Generate a new CAPTCHA
* @returns {Promise<string>} The generated CAPTCHA code
*/
async generateCaptcha() {
try {
const response = await fetch('/auth.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'generateCaptcha'
})
});
const data = await response.json();
if (data.captcha) {
return data.captcha;
}
throw new Error('Failed to generate CAPTCHA');
} catch (error) {
console.error('Error generating CAPTCHA:', error);
throw error;
}
}
/**
* Check if CAPTCHA is needed for login
* @returns {boolean} True if CAPTCHA is needed, false otherwise
*/
needsCaptcha() {
return this.loginAttempts >= 3;
}
/**
* Login a user based on credentials.
* @param {object} credentials - The user credentials (username, password, captchaInput)
* @returns {Promise<object>} The login result
*/
async login(credentials) {
try {
const response = await fetch('/api/login', {
const response = await fetch('/auth.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
@@ -51,21 +183,33 @@ class SimpleAuth {
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Login failed');
// If CAPTCHA is required, include it in the error
if (data.captcha) {
throw new Error(data.error || 'Login failed');
} else {
throw new Error(data.error || 'Login failed');
}
}
// Store token and user data
this.token = data.token;
localStorage.setItem('token', data.token);
// Parse user data from token
const payload = this.parseJwt(data.token);
this.user = {
id: payload.uid,
username: payload.username,
accessLevel: payload.accessLevel
};
localStorage.setItem('user', JSON.stringify(this.user));
// Store refresh token if available
if (data.refreshToken) {
localStorage.setItem('refreshToken', data.refreshToken);
}
// Reset login attempts
this.loginAttempts = 0;
localStorage.setItem('loginAttempts', '0');
// Store user data
this.user = data.user;
localStorage.setItem('user', JSON.stringify(data.user));
// Store browser fingerprint
localStorage.setItem('browserFingerprint', this.browserFingerprint);
return {
success: true,
@@ -73,24 +217,35 @@ class SimpleAuth {
};
} catch (error) {
console.error('Login error:', error);
// Increment login attempts
this.loginAttempts++;
localStorage.setItem('loginAttempts', this.loginAttempts.toString());
return {
success: false,
error: error.message
error: error.message,
captcha: error.captcha
};
}
}
/**
* Logout the current user
* @param {boolean} redirect - Whether to redirect to home page after logout (default: true)
*/
logout() {
logout(redirect = true) {
this.token = null;
this.user = null;
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
localStorage.removeItem('user');
localStorage.removeItem('browserFingerprint');
// Redirect to home page
window.location.href = '/';
// Redirect to home page if requested
if (redirect) {
window.location.href = '/';
}
}
/**
@@ -106,7 +261,7 @@ class SimpleAuth {
* @returns {boolean} True if admin, false otherwise
*/
isAdmin() {
return this.isAuthenticated() && this.user.accessLevel === 1;
return this.isAuthenticated() && (this.user.accessLevel === 1 || this.user.accessLevel === 0);
}
/**
@@ -146,7 +301,78 @@ class SimpleAuth {
headers
});
}
/**
* Validate the current token
* @returns {Promise<boolean>} True if token is valid, false otherwise
*/
async validateToken() {
try {
if (!this.token) {
return false;
}
const response = await fetch('/auth.php', {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.token}`
}
});
const data = await response.json();
return data.valid === true;
} catch (error) {
console.error('Token validation error:', error);
return false;
}
}
/**
* Refresh the access token using the refresh token
* @returns {Promise<boolean>} True if token was refreshed, false otherwise
*/
async refreshToken() {
try {
const refreshToken = localStorage.getItem('refreshToken');
if (!refreshToken) {
return false;
}
const response = await fetch('/auth.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'refresh',
refreshToken
})
});
const data = await response.json();
if (data.success && data.token) {
this.token = data.token;
localStorage.setItem('token', data.token);
return true;
}
return false;
} catch (error) {
console.error('Token refresh error:', error);
return false;
}
}
}
// Create a global instance
const auth = new SimpleAuth();
// Create a global instance and expose it
window.simpleAuth = new SimpleAuth();
// Also create an alias for backward compatibility
window.auth = window.simpleAuth;
// Log that simpleAuth is ready
console.log('SimpleAuth is ready and exposed to window');
// Dispatch a custom event to notify other scripts
window.dispatchEvent(new Event('simpleAuthReady'));