diff --git a/Sean/server.js b/Sean/server.js
index 38f9b31..fe49ff8 100644
--- a/Sean/server.js
+++ b/Sean/server.js
@@ -9,8 +9,9 @@ const nodemailer = require("nodemailer");
const otpGenerator = require('otp-generator');
const { body, validationResult } = require('express-validator');
const validator = require('validator');
-const { format } = require('date-fns');
+const axios = require('axios');
+const { format } = require('date-fns');
const { Sequelize } = require('sequelize');
const { transporter } = require("./modules/nodeMailer");
const { sequelize, User } = require("./modules/mysql");
@@ -801,22 +802,139 @@ app.get('/api/getLogs', async (req, res) => {
app.get("/locations", isAuthenticated, async (req, res) => {
try {
- // Render the inusers page with JSON data
- res.render("locations");
+ // Fetch data using Axios
+ const response = await axios.get(process.env.API_ALLLOCATION);
+ const locationsData = response.data;
+
+ // Render the "locations" page with the fetched JSON data
+ res.render("locations", { locationsData, csrfToken: csrfTokenSession});
} catch (error) {
- console.error("Error fetching all users:", error);
- res.status(500).send("Internal Server Error");
+ console.error("Error fetching locations:", error);
+ res.status(500).send("Internal Server Error");
}
-});
+ });
+
+ const locationValidation = [
+ body('name').trim().isLength({ min: 1 }).withMessage('Name must not be empty').escape(),
+ body('added_by').trim().isLength({ min: 1 }).withMessage('Added by must not be empty').escape(),
+ body('description').trim().escape(),
+ ];
+ app.post('/location/new', locationValidation, async (req, res) => {
+ try {
+ const errors = validationResult(req);
+ if (!errors.isEmpty()) {
+ return res.status(400).json({ errors: errors.array() });
+ }
+ const sessionTokencookie = req.cookies['sessionToken'];
+ const user = await User.findOne({ where: { sessionid: sessionTokencookie } });
+ if (!user) {
+ return res.status(403).json({ error: 'Invalid sessionToken' });
+ }
+ const submittedCSRFToken = req.body.csrf_token;
+ if (!csrfTokenSession || submittedCSRFToken !== csrfTokenSession) {
+ return res.status(403).json({ error: 'CSRF token mismatch' });
+ }
+ const { name, added_by, description } = req.body;
+ const preparedData = {name, added_by, description};
+ // Make a POST request with the sanitized data using Axios
+ const axiosResponse = await axios.post(process.env.API_NEWLOCATION, preparedData);
+ // Send the Axios response back to the client
+ res.status(axiosResponse.status).json(axiosResponse.data);
+ } catch (error) {
+ console.error('Error handling new location submission:', error);
+ res.status(500).json({ message: 'Internal Server Error' });
+ }
+ });
+
+ const locationValidationUpdate = [
+ body('id').trim().escape(),
+ body('name').trim().isLength({ min: 1 }).withMessage('Name must not be empty').escape(),
+ body('added_by').trim().isLength({ min: 1 }).withMessage('Added by must not be empty').escape(),
+ body('description').trim().escape(),
+ ];
+ app.post('/location/update', locationValidationUpdate, async (req, res) => {
+ try {
+ const errors = validationResult(req);
+ if (!errors.isEmpty()) {
+ return res.status(400).json({ errors: errors.array() });
+ }
+ const sessionTokencookie = req.cookies['sessionToken'];
+ const user = await User.findOne({ where: { sessionid: sessionTokencookie } });
+ if (!user) {
+ return res.status(403).json({ error: 'Invalid sessionToken' });
+ }
+ const submittedCSRFToken = req.body.csrf_token;
+ if (!csrfTokenSession || submittedCSRFToken !== csrfTokenSession) {
+ return res.status(403).json({ error: 'CSRF token mismatch' });
+ }
+ const { id, name, added_by, description } = req.body;
+ const preparedData = {id, name, added_by, description};
+ // Make a POST request with the sanitized data using Axios
+ const axiosResponse = await axios.post(process.env.API_UPDATELOCATION, preparedData);
+ // Send the Axios response back to the client
+ res.status(axiosResponse.status).json(axiosResponse.data);
+ } catch (error) {
+ console.error('Error handling new location submission:', error);
+ res.status(500).json({ message: 'Internal Server Error' });
+ }
+ });
+
+
app.get("/sensors", isAuthenticated, async (req, res) => {
try {
// Render the inusers page with JSON data
- res.render("sensors");
+ const response = await axios.get(process.env.API_ALLLOCATION);
+ const locationsData = response.data;
+ const response2 = await axios.get(process.env.API_ALLSENSOR);
+ const sensorData = response2.data;
+ res.render("sensors",{locationsData, sensorData, csrfToken: csrfTokenSession});
} catch (error) {
- console.error("Error fetching all users:", error);
+ console.error("Error:", error);
res.status(500).send("Internal Server Error");
}
});
+
+const sensorValidation = [
+ body('id').trim().escape(),
+ body('sensorname').trim().isLength({ min: 1 }).withMessage('Sensor Name must not be empty').escape(),
+ body('added_by').trim().isLength({ min: 1 }).withMessage('Added by must not be empty').escape(),
+ body('macAddress').custom(value => {
+ const macAddressRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
+ if (!macAddressRegex.test(value)) {
+ throw new Error('Invalid MAC address format');
+ }
+ return true;
+ }).withMessage('Invalid MAC address format').escape(),
+ body('description').trim().escape(),
+ body('location').trim().escape()
+ ];
+ app.post('sensor/new',sensorValidation, async (req, res) => {
+ try {
+ const errors = validationResult(req);
+ if (!errors.isEmpty()) {
+ return res.status(400).json({ errors: errors.array() });
+ }
+ const sessionTokencookie = req.cookies['sessionToken'];
+ const user = await User.findOne({ where: { sessionid: sessionTokencookie } });
+ if (!user) {
+ return res.status(403).json({ error: 'Invalid sessionToken' });
+ }
+ const submittedCSRFToken = req.body.csrf_token;
+ if (!csrfTokenSession || submittedCSRFToken !== csrfTokenSession) {
+ return res.status(403).json({ error: 'CSRF token mismatch' });
+ }
+ const { id, sensorname, added_by, macAddress, description, location} = req.body;
+ const preparedData = {id, sensorname, added_by, macAddress, description, location};
+ // Make a POST request with the sanitized data using Axios
+ const axiosResponse = await axios.post(process.env.API_NEWSENSOR, preparedData);
+ // Send the Axios response back to the client
+ res.status(axiosResponse.status).json(axiosResponse.data);
+ } catch (error) {
+ console.error('Error handling new sensor submission:', error);
+ res.status(500).json({ message: 'Internal Server Error' });
+ }
+ });
+
app.use(express.static("views"));
app.listen(PORT, () => {
diff --git a/Sean/views/location.js b/Sean/views/location.js
index dea75ec..adcffc2 100644
--- a/Sean/views/location.js
+++ b/Sean/views/location.js
@@ -20,78 +20,48 @@ $(document).ready(function () {
let locationArray = [];
-$(document).ready(function () {
- // Function to fetch and display locations
- function fetchLocations() {
- // Make a GET request to retrieve all locations
- fetch('/api/v0/location', {
- method: 'GET',
-
- })
- .then(response => {
- if (response.ok) {
- return response.json();
- } else {
- throw new Error(`HTTP error! Status: ${response.status}`);
- }
- })
- .then(locations => {
- // Clear existing table rows
- $('#locationTableBody').empty();
- locationArray = [];
+ function populateTableAndArray(data) {
+ const tableBody = document.getElementById("locationTableBody");
- // Populate the table with location information
- locations.forEach(location => {
- locationArray.push({
- id: location.id,
- name: location.name,
- description: location.description
- });
+ // Clear existing rows and array
+ tableBody.innerHTML = "";
+ locationArray.length = 0;
- $('#locationTableBody').append(`
-
- | ${location.id} |
- ${location.name} |
- ${location.description} |
-
- `);
- });
- })
- .catch(error => {
- console.error('Error fetching locations:', error);
- // Handle error as needed
- });
- }
- // Call the fetchLocations function when the page loads
- fetchLocations();
-});
+ // Loop through the data and create table rows
+ data.forEach(location => {
+ const row = document.createElement("tr");
+ row.innerHTML = `
+ ${location.id} |
+ ${location.location} |
+ ${location.description} |
+ `;
+ tableBody.appendChild(row);
+
+ // Push location data to the array
+ locationArray.push(location);
+ });
+ }
+ populateTableAndArray(locationsData);
+ console.log(locationArray);
$('#locationForm').on('submit', function (e) {
e.preventDefault();
- const location= DOMPurify.sanitize($('#location').val().trim());
- // Validate if the sanitized value is empty
- if (location === '') {
- alert('Location name cannot be empty');
- return;
- }
+ const location= $('#location').val();
const user = req.session.jobTitle
- const description= DOMPurify.sanitize($('#description').val().trim());
- // Validate if the sanitized value is empty
- if (description === '') {
- alert('description name cannot be empty');
- return;
- }
- fetch('/api/v0/location/new', {
+ const description= $('#description').val();
+ const csrf_token = $('#userForm input[name="csrf_token"]').val();
+
+ fetch('/location/new', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
- 'Authorization': '2-eb0c08b0-250a-4249-8a87-11141e2ff8fb'
},
body: JSON.stringify({
name: location,
added_by: user,
- description: description
+ description: description,
+ csrf_token: csrf_token
}),
})
.then(response => {
@@ -127,37 +97,23 @@ $('#locationForm').on('submit', function (e) {
$('#updateForm').on('submit', function (e) {
e.preventDefault();
- const selectedLocationId = DOMPurify.sanitize($('#locationDropdown').val().trim());
-
- // Validate if the selected location ID is empty
- if (selectedLocationId === '') {
- alert('Please select a location to update');
- return;
- }
- const location= DOMPurify.sanitize($('#location').val().trim());
- // Validate if the sanitized value is empty
- if (location === '') {
- alert('Location name cannot be empty');
- return;
- }
+ const selectedLocationId = $('#locationDropdown').val();
+ const location= $('#location').val();
const user = req.session.jobTitle
- const description= DOMPurify.sanitize($('#description').val().trim());
- // Validate if the sanitized value is empty
- if (description === '') {
- alert('description name cannot be empty');
- return;
- }
- fetch('/api/v0/location/update', {
+ const description=$('#description').val();
+ const csrf_token = $('#userForm input[name="csrf_token"]').val();
+
+ fetch('/location/update', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json',
- 'Authorization': '1-1ec4ce9d-bcff-46c4-a023-c34171b9ca51'
+ 'Content-Type': 'application/json'
},
body: JSON.stringify({
id:selectedLocationId,
name: location,
added_by: user,
- description: description
+ description: description,
+ csrf_token: csrf_token
}),
})
.then(response => {
diff --git a/Sean/views/locations.ejs b/Sean/views/locations.ejs
index c562c6b..b0aaa5e 100644
--- a/Sean/views/locations.ejs
+++ b/Sean/views/locations.ejs
@@ -42,7 +42,7 @@
+
@@ -88,6 +90,9 @@
+
diff --git a/Sean/views/sensor.js b/Sean/views/sensor.js
index 77b33c9..3577713 100644
--- a/Sean/views/sensor.js
+++ b/Sean/views/sensor.js
@@ -10,126 +10,67 @@ $(document).ready(function () {
$('#additional-text4').show();
});
});
- let locationsArray = [];
+ function populateTableAndArray(data, locationsArray) {
+ const tableBody = document.getElementById("sensorTableBody");
+ // Clear existing rows and array
+ tableBody.innerHTML = "";
+ sensorArray.length = 0;
+ // Loop through the data and create table rows
+ data.forEach(sensor => {
+ const location = locationsArray.find(loc => loc.id === sensor.location);
+
+ const row = document.createElement("tr");
+ row.innerHTML = `
+ ${sensor.id} |
+ ${sensor.sensorname} |
+ ${sensor.added_by} |
+ ${sensor.description} |
+ ${location ? location.name : 'Unknown Location'} |
+ `;
+ tableBody.appendChild(row);
+ // Push sensor data to the array
+ sensorArray.push(sensor);
+ });
+ }
+ // Assuming locationsArray is defined elsewhere in your code
+ populateTableAndArray(sensorData);
+ console.log(sensorArray);
- // Function to fetch and store locations in the array
- function fetchLocations() {
- // Make a GET request to retrieve all locations
- fetch('/api/v0/location', {
- method: 'GET',
- })
- .then(response => {
- if (response.ok) {
- return response.json();
- } else {
- throw new Error(`HTTP error! Status: ${response.status}`);
- }
- })
- .then(locations => {
- // Reset the array
- locationsArray = [];
+ function populateLocationDropdown() {
+ const locationDropdown = document.getElementById('locationDropdown');
- // Populate the array with location information
- locations.forEach(location => {
- // Store in the array
- locationsArray.push({
- id: location.id,
- location: location.name,
- });
- });
- })
- .catch(error => {
- console.error('Error fetching locations:', error);
- // Handle error as needed
- });
- }
- // Call the fetchLocations function when the page loads
- fetchLocations();
+ // Clear existing options
+ locationDropdown.innerHTML = '';
- // Function to fetch sensor data and populate the table
- function fetchAndPopulateSensorTable() {
- // Fetch sensor data from the API
- fetch('/api/v0/sensor', {
- method: 'GET',
- headers: {
- 'Authorization': '1-1ec4ce9d-bcff-46c4-a023-c34171b9ca51'
- },
- })
- .then(response => response.json())
- .then(sensorData => {
- // Get the table body
- const tableBody = document.getElementById('sensorTableBody');
+ // Add a default option
+ const defaultOption = document.createElement('option');
+ defaultOption.text = 'Select a Location';
+ defaultOption.value = '';
+ locationDropdown.add(defaultOption);
- // Clear existing rows
- tableBody.innerHTML = '';
-
- // Iterate through each sensor data
- sensorData.forEach(sensor => {
- // Find the corresponding location object
- const location = locationsArray.find(loc => loc.id === sensor.location);
-
- // Create a new row
- const row = tableBody.insertRow();
-
- // Insert cells with sensor data
- row.insertCell(0).textContent = sensor.id;
- row.insertCell(1).textContent = sensor.sensorname;
- row.insertCell(2).textContent = sensor.added_by;
- row.insertCell(3).textContent = sensor.mac_address;
- row.insertCell(4).textContent = sensor.description;
-
- // Insert location cell with corresponding location name
- const locationCell = row.insertCell(5);
- locationCell.textContent = location ? location.location : 'Unknown';
- });
- })
- .catch(error => {
- console.error('Error fetching sensor data:', error);
- });
- }
-
- // Call the function to fetch and populate the table
- fetchAndPopulateSensorTable();
+ // Add locations as options
+ locationsArray.forEach(location => {
+ const option = document.createElement('option');
+ option.text = location.location;
+ option.value = location.id;
+ locationDropdown.add(option);
+ });
+}
+populateLocationDropdown();
$('#sensorForm').on('submit', function (e) {
e.preventDefault();
- // Sanitize sensor input
- const sensor = DOMPurify.sanitize($('#sensor').val().trim());
- // Validate if the sanitized value is empty
- if (sensor === '') {
- alert('Sensor name cannot be empty');
- return;
- }
- // Sanitize user input (assuming req.session is available)
- const user = DOMPurify.sanitize(req.session.jobTitle);
-
- // Validate if the sanitized value is missing
- if (!user) {
- alert('User information is missing');
- return;
- }
- // Sanitize macAddress input
- const macAddress = DOMPurify.sanitize($('#macAddress').val().trim());
- // Validate macAddress format
- const macAddressRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
- if (!macAddressRegex.test(macAddress)) {
- alert('Invalid MAC Address format');
- return;
- }
- // Sanitize description input
- const description = DOMPurify.sanitize($('#description').val().trim());
- // Validate if the sanitized value is empty
- if (description === '') {
- alert('Description cannot be empty');
- return;
- }
- const location = $('#location').val();
+ const sensor = $('#sensor').val();
+ const user = req.session.jobTitle;
+ const macAddress = $('#macAddress').val();
+ const description = $('#description').val();
+ const location = $('#location').val();
+ const csrf_token = $('#userForm input[name="csrf_token"]').val();
- fetch('/api/v0/sensor/new', {
+ fetch('sensor/new', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json',
- 'Authorization': '2-eb0c08b0-250a-4249-8a87-11141e2ff8fb'
+ 'Content-Type': 'application/json'
},
body: JSON.stringify({
id: id,
@@ -137,7 +78,8 @@ $('#sensorForm').on('submit', function (e) {
added_by: user,
mac_address: macAddress,
description: description,
- location: location
+ location: location,
+ csrf_token: csrf_token
}),
})
.then(response => {
@@ -160,27 +102,3 @@ $('#sensorForm').on('submit', function (e) {
// Handle error as needed
});
});
-
- function populateLocationDropdown() {
- const locationDropdown = document.getElementById('locationDropdown');
-
- // Clear existing options
- locationDropdown.innerHTML = '';
-
- // Add a default option
- const defaultOption = document.createElement('option');
- defaultOption.text = 'Select a Location';
- defaultOption.value = '';
- locationDropdown.add(defaultOption);
-
- // Add locations as options
- locationsArray.forEach(location => {
- const option = document.createElement('option');
- option.text = location.location;
- option.value = location.id;
- locationDropdown.add(option);
- });
-}
-
-// Call the function to populate the dropdown when the page loads
-populateLocationDropdown();
\ No newline at end of file
diff --git a/Sean/views/sensors.ejs b/Sean/views/sensors.ejs
index 66941b7..d4ed745 100644
--- a/Sean/views/sensors.ejs
+++ b/Sean/views/sensors.ejs
@@ -64,10 +64,10 @@
Location
+
@@ -88,6 +88,10 @@
Any Issue faced, Please contact the administrator at 11111111 or ecosaverAdmin@gmail.com