i finally committed i guess
Signed-off-by: boris <boris@borishub.co.uk>
This commit is contained in:
307
public/js/apiClient.js
Normal file
307
public/js/apiClient.js
Normal file
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* API Client for making authenticated requests to the server
|
||||
*
|
||||
* This class provides a wrapper around the Fetch API to handle
|
||||
* 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.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
constructor() {
|
||||
// Ensure auth service is available
|
||||
if (!window.auth) {
|
||||
console.error('Auth service not available');
|
||||
}
|
||||
|
||||
// Create authenticated fetch function if not already available
|
||||
this.authFetch = window.authFetch || window.auth?.createAuthFetch() || fetch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a GET request to the API
|
||||
*
|
||||
* This method handles GET requests with query parameters.
|
||||
* It automatically converts the params object to a query string
|
||||
* and handles error responses.
|
||||
*
|
||||
* @param {string} endpoint - The API endpoint
|
||||
* @param {Object} params - Query parameters
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async get(endpoint, params = {}) {
|
||||
// Build query string
|
||||
const queryString = Object.keys(params).length > 0
|
||||
? '?' + new URLSearchParams(params).toString()
|
||||
: '';
|
||||
|
||||
try {
|
||||
const response = await this.authFetch(`${endpoint}${queryString}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`GET request to ${endpoint} failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a POST request to the API
|
||||
*
|
||||
* This method handles POST requests with either JSON data or FormData.
|
||||
* It automatically sets the appropriate headers and handles error responses.
|
||||
*
|
||||
* @param {string} endpoint - The API endpoint
|
||||
* @param {Object|FormData} data - The data to send
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async post(endpoint, data = {}) {
|
||||
try {
|
||||
// Prepare request options
|
||||
const options = {
|
||||
method: 'POST'
|
||||
};
|
||||
|
||||
// Handle FormData or JSON
|
||||
if (data instanceof FormData) {
|
||||
options.body = data;
|
||||
} else {
|
||||
options.headers = {
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
options.body = JSON.stringify(data);
|
||||
}
|
||||
|
||||
const response = await this.authFetch(endpoint, options);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`POST request to ${endpoint} failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a facility-related API request
|
||||
*
|
||||
* This is a helper method that simplifies making requests to the facility controller.
|
||||
* It automatically creates a FormData object with the action and data parameters.
|
||||
*
|
||||
* @param {string} action - The action to perform
|
||||
* @param {Object} data - The data to send
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async facility(action, data = {}) {
|
||||
// Create FormData
|
||||
const formData = new FormData();
|
||||
formData.append('action', action);
|
||||
|
||||
// Add all data to FormData
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
formData.append(key, value);
|
||||
});
|
||||
|
||||
return this.post('/facilitycontroller.php', formData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new facility
|
||||
*
|
||||
* This method sends a request to create a new facility with the provided data.
|
||||
*
|
||||
* @param {Object} facilityData - The facility data
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async createFacility(facilityData) {
|
||||
return this.facility('create', facilityData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a facility
|
||||
*
|
||||
* This method sends a request to update an existing facility with the provided data.
|
||||
*
|
||||
* @param {Object} facilityData - The facility data
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async updateFacility(facilityData) {
|
||||
return this.facility('update', facilityData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a facility
|
||||
*
|
||||
* This method sends a request to delete a facility with the specified ID.
|
||||
*
|
||||
* @param {number|string} id - The facility ID
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async deleteFacility(id) {
|
||||
return this.facility('delete', { id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a facility by ID
|
||||
*
|
||||
* This method retrieves a single facility with the specified ID.
|
||||
*
|
||||
* @param {number|string} id - The facility ID
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async getFacility(id) {
|
||||
return this.facility('read', { id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets statuses for a facility
|
||||
*
|
||||
* This method retrieves all status updates for a facility with the specified ID.
|
||||
*
|
||||
* @param {number|string} facilityId - The facility ID
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async getFacilityStatuses(facilityId) {
|
||||
return this.facility('getStatuses', { facilityId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a status to a facility
|
||||
*
|
||||
* This method adds a new status update to a facility.
|
||||
*
|
||||
* @param {number|string} idStatus - The facility ID
|
||||
* @param {string} updateStatus - The status comment
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async addFacilityStatus(idStatus, updateStatus) {
|
||||
return this.facility('status', { idStatus, updateStatus });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a facility status
|
||||
*
|
||||
* This method updates an existing status for a facility.
|
||||
*
|
||||
* @param {number|string} statusId - The status ID
|
||||
* @param {string} editStatus - The updated status comment
|
||||
* @param {number|string} facilityId - The facility ID
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
async updateFacilityStatus(statusId, editStatus, facilityId) {
|
||||
return this.facility('editStatus', { statusId, editStatus, facilityId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a facility status
|
||||
*
|
||||
* This method deletes a status update from a facility.
|
||||
*
|
||||
* @param {number|string} statusId - The status ID
|
||||
* @param {number|string} facilityId - The facility ID
|
||||
* @returns {Promise<Object>} The response data
|
||||
*/
|
||||
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
|
||||
const api = new ApiClient();
|
||||
|
||||
// Export API client
|
||||
window.api = api;
|
614
public/js/auth.js
Normal file
614
public/js/auth.js
Normal file
@@ -0,0 +1,614 @@
|
||||
/**
|
||||
* 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);
|
||||
}
|
6314
public/js/bootstrap.bundle.js
vendored
Normal file
6314
public/js/bootstrap.bundle.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
471
public/js/comments.js
Normal file
471
public/js/comments.js
Normal file
@@ -0,0 +1,471 @@
|
||||
/**
|
||||
* 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);
|
||||
|
||||
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
|
||||
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');
|
||||
|
||||
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
|
||||
*/
|
||||
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);
|
||||
|
||||
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');
|
||||
}
|
||||
} 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);
|
||||
|
||||
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
|
||||
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 {
|
||||
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>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Use the API client to get facility statuses
|
||||
const data = await window.api.getFacilityStatuses(facilityId);
|
||||
|
||||
console.log('Comments loaded:', data);
|
||||
|
||||
if (data.success) {
|
||||
// Render the comments
|
||||
renderComments(data.statuses, facilityId);
|
||||
} else {
|
||||
console.error('Failed to load comments:', data.error);
|
||||
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'}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading comments:', error);
|
||||
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}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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'
|
||||
});
|
||||
|
||||
// Check if the current user is the comment author or an admin
|
||||
const canEdit = isAdmin() || 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">${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>
|
||||
`;
|
||||
|
||||
commentsList.appendChild(commentElement);
|
||||
});
|
||||
|
||||
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');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting comment:', error);
|
||||
alert('Failed to delete comment: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
1197
public/js/facilityData.js
Normal file
1197
public/js/facilityData.js
Normal file
File diff suppressed because it is too large
Load Diff
152
public/js/simpleAuth.js
Normal file
152
public/js/simpleAuth.js
Normal file
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Simplified Authentication Helper
|
||||
*
|
||||
* This provides a streamlined authentication solution that works with
|
||||
* the simplified server-side authentication approach.
|
||||
*/
|
||||
class SimpleAuth {
|
||||
/**
|
||||
* Initialize the authentication helper
|
||||
*/
|
||||
constructor() {
|
||||
this.token = localStorage.getItem('token');
|
||||
this.user = JSON.parse(localStorage.getItem('user') || 'null');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a JWT token to extract its payload
|
||||
* @param {string} token - The JWT token to parse
|
||||
* @returns {object|null} The decoded 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 (e) {
|
||||
console.error('Error parsing JWT token:', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Login a user
|
||||
* @param {object} credentials - The user credentials (username, password)
|
||||
* @returns {Promise<object>} The login result
|
||||
*/
|
||||
async login(credentials) {
|
||||
try {
|
||||
const response = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(credentials)
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
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));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
user: this.user
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error.message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout the current user
|
||||
*/
|
||||
logout() {
|
||||
this.token = null;
|
||||
this.user = null;
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
|
||||
// Redirect to home page
|
||||
window.location.href = '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user is authenticated
|
||||
* @returns {boolean} True if authenticated, false otherwise
|
||||
*/
|
||||
isAuthenticated() {
|
||||
return !!this.token && !!this.user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user is an admin
|
||||
* @returns {boolean} True if admin, false otherwise
|
||||
*/
|
||||
isAdmin() {
|
||||
return this.isAuthenticated() && this.user.accessLevel === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current user
|
||||
* @returns {object|null} The current user or null if not authenticated
|
||||
*/
|
||||
getUser() {
|
||||
return this.user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the authentication token
|
||||
* @returns {string|null} The token or null if not authenticated
|
||||
*/
|
||||
getToken() {
|
||||
return this.token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an authenticated API request
|
||||
* @param {string} url - The URL to fetch
|
||||
* @param {object} options - Fetch options
|
||||
* @returns {Promise<Response>} The fetch response
|
||||
*/
|
||||
async fetchAuth(url, options = {}) {
|
||||
if (!this.token) {
|
||||
throw new Error('Not authenticated');
|
||||
}
|
||||
|
||||
const headers = {
|
||||
...options.headers,
|
||||
'Authorization': `Bearer ${this.token}`
|
||||
};
|
||||
|
||||
return fetch(url, {
|
||||
...options,
|
||||
headers
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Create a global instance
|
||||
const auth = new SimpleAuth();
|
Reference in New Issue
Block a user