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

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'));