fixed centering issue with radius.

Signed-off-by: boris <boris@borishub.co.uk>
This commit is contained in:
boris
2025-04-22 01:17:48 +01:00
parent 183cca3fd3
commit d027e01ccc
12 changed files with 85 additions and 215 deletions

View File

@@ -5,7 +5,7 @@
* authentication and common request patterns.
*
* The client uses JWT tokens for authentication, which are automatically
* included in requests via the fetchAuth function provided by the simpleAuth service.
* included in requests via the fetchAuth function provided by the auth service.
*
* Similar to AuthService.php, great pain and countless tears. And learning woooo!!!!!!!!
*/
@@ -14,25 +14,25 @@ class ApiClient {
* Constructor
*
* Initialises the API client and sets up the authenticated fetch function.
* Relies on the simpleAuth service being available in the global scope.
* Relies on the auth service being available in the global scope.
*/
constructor() {
// Ensure auth service is available
if (!simpleAuth) {
if (!auth) {
console.error('Auth service not available');
}
// Use the fetchAuth method from simpleAuth
// Use the fetchAuth method from auth
this.authFetch = async (url, options = {}) => {
try {
// For unauthenticated requests or when authentication is not required
if (!options.requireAuth || !simpleAuth.isAuthenticated()) {
if (!options.requireAuth || !auth.isAuthenticated()) {
return fetch(url, options);
}
// For authenticated requests
delete options.requireAuth; // Remove the custom property
return simpleAuth.fetchAuth(url, options);
return auth.fetchAuth(url, options);
} catch (error) {
console.error('Error in authFetch:', error);
throw error;

View File

@@ -4,7 +4,7 @@
* I admit JWT is unnecessary, but I did it anyway because it was interesting
* and I wanted to try it out.
*/
class SimpleAuth {
class Auth {
/**
* initialise the authentication helper
*/
@@ -360,13 +360,10 @@ class SimpleAuth {
}
// Create a global instance and expose it
window.simpleAuth = new SimpleAuth();
window.auth = new Auth();
// 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');
// Log that auth is ready
console.log('auth is ready and exposed to window');
// Dispatch a custom event to notify other scripts
window.dispatchEvent(new Event('simpleAuthReady'));
window.dispatchEvent(new Event('authReady'));

View File

@@ -7,7 +7,7 @@ const CommentsManager = {
// Initialization states
state: {
isInitializing: false,
isinitialised: false,
isInitialised: false,
isDomReady: false,
isAuthReady: false
},
@@ -16,7 +16,7 @@ const CommentsManager = {
* initialise status functionality
*/
initialise() {
if (this.state.isinitialised) return;
if (this.state.isInitialised) return;
console.log('Initializing comments...');
@@ -28,10 +28,10 @@ const CommentsManager = {
console.log('Comments initialised with auth state:', {
isAuthenticated: this.isAuthenticated(),
user: window.simpleAuth.getUser()
user: window.auth.getUser()
});
this.state.isinitialised = true;
this.state.isInitialised = true;
},
/**
@@ -49,7 +49,7 @@ const CommentsManager = {
* Check if user is authenticated
*/
isAuthenticated() {
return window.simpleAuth && window.simpleAuth.isAuthenticated();
return window.auth && window.auth.isAuthenticated();
},
/**
@@ -253,8 +253,8 @@ const CommentsManager = {
* Creates a comment form dynamically for authenticated users
*/
createCommentFormForAuthenticatedUser(facilityId) {
// First check if simpleAuth is available
if (!window.simpleAuth) {
// First check if auth is available
if (!window.auth) {
return `
<div class="alert alert-warning mb-0">
<i class="bi bi-hourglass-split me-2"></i>
@@ -265,9 +265,9 @@ const CommentsManager = {
// Validate authentication state
try {
const token = window.simpleAuth.getToken();
const user = window.simpleAuth.getUser();
const isAuthenticated = window.simpleAuth.isAuthenticated();
const token = window.auth.getToken();
const user = window.auth.getUser();
const isAuthenticated = window.auth.isAuthenticated();
if (!isAuthenticated || !token || !user) {
return `
@@ -483,14 +483,14 @@ const CommentsManager = {
* Checks if the current user is an admin
*/
isAdmin() {
return window.simpleAuth && window.simpleAuth.isAdmin();
return window.auth && window.auth.isAdmin();
},
/**
* Checks if the given username matches the current user
*/
isCurrentUser(username) {
const user = window.simpleAuth && window.simpleAuth.getUser();
const user = window.auth && window.auth.getUser();
return user && user.username === username;
},
@@ -522,21 +522,21 @@ if (document.readyState === 'loading') {
CommentsManager.checkinitialise();
}
// Listen for simpleAuth ready
if (window.simpleAuth) {
// Listen for auth ready
if (window.auth) {
CommentsManager.state.isAuthReady = true;
CommentsManager.checkinitialise();
} else {
window.addEventListener('simpleAuthReady', () => {
console.log('SimpleAuth is now ready');
window.addEventListener('authReady', () => {
console.log('auth is now ready');
CommentsManager.state.isAuthReady = true;
CommentsManager.checkinitialise();
});
// Fallback timeout in case the event doesn't fire
setTimeout(() => {
if (!CommentsManager.state.isAuthReady && window.simpleAuth) {
console.log('SimpleAuth found via timeout check');
if (!CommentsManager.state.isAuthReady && window.auth) {
console.log('auth found via timeout check');
CommentsManager.state.isAuthReady = true;
CommentsManager.checkinitialise();
}

View File

@@ -272,8 +272,8 @@ function isAdmin() {
console.log('Checking admin status...');
// Check if auth service is available and has user data
if (simpleAuth && simpleAuth.getUser()) {
const authUser = simpleAuth.getUser();
if (auth && auth.getUser()) {
const authUser = auth.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);
@@ -302,8 +302,8 @@ function isAdmin() {
*/
function isAuthenticated() {
// Check if auth service is available
if (simpleAuth) {
return simpleAuth.isAuthenticated();
if (auth) {
return auth.isAuthenticated();
}
// Fallback to localStorage
@@ -497,8 +497,8 @@ function setupFormHandlers() {
// Set the action to 'create'
formData.set('action', 'create');
try {
// Use simpleAuth.fetchAuth for authenticated requests
const response = await simpleAuth.fetchAuth('/facilitycontroller.php', {
// Use auth.fetchAuth for authenticated requests
const response = await auth.fetchAuth('/facilitycontroller.php', {
method: 'POST',
body: formData
});
@@ -605,8 +605,8 @@ function setupFormHandlers() {
}
try {
// Use simpleAuth.fetchAuth for authenticated requests
const response = await simpleAuth.fetchAuth('/facilitycontroller.php', {
// Use auth.fetchAuth for authenticated requests
const response = await auth.fetchAuth('/facilitycontroller.php', {
method: 'POST',
body: serverFormData
});
@@ -694,19 +694,19 @@ function setupFormHandlers() {
try {
// Check if token is valid
if (!simpleAuth) {
if (!auth) {
throw new Error('Auth service not available');
}
// Validate token with server before proceeding
console.log('Validating token with server...');
const isValid = await simpleAuth.validateToken();
const isValid = await auth.validateToken();
if (!isValid) {
throw new Error('Authentication token is invalid or expired');
}
// Get token after validation to ensure it's fresh
const token = simpleAuth.getToken();
const token = auth.getToken();
console.log('Using token for delete request:', token);
if (!token) {
@@ -714,16 +714,16 @@ function setupFormHandlers() {
}
// Decode token to check payload
if (simpleAuth.parseJwt) {
const payload = simpleAuth.parseJwt(token);
if (auth.parseJwt) {
const payload = auth.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 simpleAuth.fetchAuth for authenticated requests
// Use auth.fetchAuth for authenticated requests
console.log('Sending delete request to server...');
const response = await simpleAuth.fetchAuth('/facilitycontroller.php', {
const response = await auth.fetchAuth('/facilitycontroller.php', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,

View File

@@ -92,84 +92,6 @@ document.addEventListener('DOMContentLoaded', function() {
setupHeaderSearchHandler();
});
/**
* Get postcode from coordinates using postcodes.io API
* @param {number} lat - Latitude
* @param {number} lng - Longitude
* @returns {Promise<string>} The postcode
*/
async function getPostcodeFromCoordinates(lat, lng) {
try {
const response = await fetch(`https://api.postcodes.io/postcodes?lon=${lng}&lat=${lat}`);
if (!response.ok) {
throw new Error('Could not find postcode for coordinates');
}
const data = await response.json();
if (data.status === 200 && data.result && data.result.length > 0) {
return data.result[0].postcode;
}
throw new Error('No postcode found for coordinates');
} catch (error) {
console.error('Error getting postcode from coordinates:', error);
throw error;
}
}
/**
* Handle geolocation success
* @param {GeolocationPosition} position - The position object
*/
async function handleGeolocationSuccess(position) {
try {
const { latitude, longitude } = position.coords;
// Get postcode from coordinates
const postcode = await getPostcodeFromCoordinates(latitude, longitude);
// Update the postcode input
const postcodeInput = document.getElementById('postcode');
if (postcodeInput) {
postcodeInput.value = postcode;
// Submit the form to update the map
const postcodeForm = document.getElementById('postcodeForm');
if (postcodeForm) {
postcodeForm.dispatchEvent(new Event('submit'));
}
}
} catch (error) {
console.error('Error processing geolocation:', error);
alert('Error getting your location: ' + error.message);
}
}
/**
* Handle geolocation error
* @param {GeolocationPositionError} error - The error object
*/
function handleGeolocationError(error) {
console.error('Geolocation error:', error);
let message = 'Error getting your location: ';
switch(error.code) {
case error.PERMISSION_DENIED:
message += 'Please enable location access in your browser settings.';
break;
case error.POSITION_UNAVAILABLE:
message += 'Location information is unavailable.';
break;
case error.TIMEOUT:
message += 'Location request timed out.';
break;
default:
message += 'An unknown error occurred.';
}
alert(message);
}
/**
* Set up form handlers for postcode and radius inputs
*/
@@ -245,11 +167,13 @@ function setupFormHandlers() {
}
if (radiusSelect) {
radiusSelect.addEventListener('change', function() {
radiusSelect.addEventListener('change', async function(e) {
e.preventDefault();
const postcode = document.getElementById('postcode').value;
const coords = await getPostcodeCoordinates(postcode);
const radius = parseFloat(this.value);
if (currentPostcode) {
updateMapLocation(null, radius); // null coords means use existing center
}
updateMapLocation(coords, radius);
});
}
}
@@ -402,7 +326,7 @@ function toRad(degrees) {
* @returns {string} HTML content for popup
*/
function createPopupContent(facility) {
const isAuthenticated = window.simpleAuth && window.simpleAuth.isAuthenticated();
const isAuthenticated = window.auth && window.auth.isAuthenticated();
return `
<div class="facility-popup">
@@ -498,7 +422,7 @@ async function handleCommentSubmit(event, facilityId) {
event.preventDefault();
// Check authentication
if (!window.simpleAuth || !window.simpleAuth.isAuthenticated()) {
if (!window.auth || !window.auth.isAuthenticated()) {
alert('You must be logged in to add comments');
return false;
}