fix random connection.end and repeated sql connect
This commit is contained in:
parent
699b8f88df
commit
c38d4eb8bb
@ -20,8 +20,8 @@ const mysqlConfig = {
|
|||||||
timezone: 'Z', // Set the timezone to UTC
|
timezone: 'Z', // Set the timezone to UTC
|
||||||
};
|
};
|
||||||
|
|
||||||
const mysqlConnection = mysql.createConnection(mysqlConfig);
|
const connection = mysql.createConnection(mysqlConfig);
|
||||||
mysqlConnection.connect((err) => {
|
connection.connect((err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error('Error connecting to MySQL:', err);
|
console.error('Error connecting to MySQL:', err);
|
||||||
return;
|
return;
|
||||||
@ -63,8 +63,8 @@ const logActivity = async (username, success) => {
|
|||||||
const logSql = 'INSERT INTO user_logs (username, activity, timestamp) VALUES (?, ?, CURRENT_TIMESTAMP)';
|
const logSql = 'INSERT INTO user_logs (username, activity, timestamp) VALUES (?, ?, CURRENT_TIMESTAMP)';
|
||||||
const logParams = [username, activity];
|
const logParams = [username, activity];
|
||||||
|
|
||||||
const connection = mysql.createConnection(mysqlConfig);
|
//const connection = mysql.createConnection(mysqlConfig);
|
||||||
connection.connect();
|
//connection.connect();
|
||||||
|
|
||||||
connection.query(logSql, logParams, (error, results) => {
|
connection.query(logSql, logParams, (error, results) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
@ -74,7 +74,7 @@ const logActivity = async (username, success) => {
|
|||||||
console.log('Activity logged successfully');
|
console.log('Activity logged successfully');
|
||||||
}
|
}
|
||||||
|
|
||||||
connection.end(); // Close the connection after logging activity
|
//connection.end(); // Close the connection after logging activity
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error in logActivity function:', error);
|
console.error('Error in logActivity function:', error);
|
||||||
@ -91,8 +91,8 @@ app.post('/login', async (req, res) => {
|
|||||||
const loginSql = 'SELECT * FROM users WHERE username = ?';
|
const loginSql = 'SELECT * FROM users WHERE username = ?';
|
||||||
const updateLastLoginSql = 'UPDATE users SET lastLogin = CURRENT_TIMESTAMP WHERE username = ?';
|
const updateLastLoginSql = 'UPDATE users SET lastLogin = CURRENT_TIMESTAMP WHERE username = ?';
|
||||||
|
|
||||||
const connection = mysql.createConnection(mysqlConfig);
|
//const connection = mysql.createConnection(mysqlConfig);
|
||||||
connection.connect();
|
//connection.connect();
|
||||||
|
|
||||||
console.log('Login Query:', loginSql);
|
console.log('Login Query:', loginSql);
|
||||||
console.log('Query Parameters:', [username]);
|
console.log('Query Parameters:', [username]);
|
||||||
@ -103,7 +103,7 @@ app.post('/login', async (req, res) => {
|
|||||||
if (error) {
|
if (error) {
|
||||||
console.error('Error executing login query:', error);
|
console.error('Error executing login query:', error);
|
||||||
res.status(500).send('Internal Server Error');
|
res.status(500).send('Internal Server Error');
|
||||||
connection.end(); // Close the connection in case of an error
|
//connection.end(); // Close the connection in case of an error
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -120,7 +120,7 @@ app.post('/login', async (req, res) => {
|
|||||||
if (updateError) {
|
if (updateError) {
|
||||||
console.error('Error updating lastLogin:', updateError);
|
console.error('Error updating lastLogin:', updateError);
|
||||||
res.status(500).send('Internal Server Error');
|
res.status(500).send('Internal Server Error');
|
||||||
connection.end(); // Close the connection in case of an error
|
//connection.end(); // Close the connection in case of an error
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -135,18 +135,18 @@ app.post('/login', async (req, res) => {
|
|||||||
req.session.authenticated = true;
|
req.session.authenticated = true;
|
||||||
req.session.username = username;
|
req.session.username = username;
|
||||||
res.redirect('/home');
|
res.redirect('/home');
|
||||||
connection.end();
|
//connection.end();
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Pass the error to the template
|
// Pass the error to the template
|
||||||
res.render('login', { error: 'Error updating lastLogin. No rows affected.' });
|
res.render('login', { error: 'Error updating lastLogin. No rows affected.' });
|
||||||
connection.end(); // Close the connection when not needed anymore
|
//connection.end(); // Close the connection when not needed anymore
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Pass the error to the template
|
// Pass the error to the template
|
||||||
res.render('login', { error: 'Invalid username or password' });
|
res.render('login', { error: 'Invalid username or password' });
|
||||||
connection.end(); // Close the connection when not needed anymore
|
//connection.end(); // Close the connection when not needed anymore
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -163,7 +163,7 @@ app.get('/home', isAuthenticated, (req, res) => {
|
|||||||
// Retrieve the overall last 10 logins for all users
|
// Retrieve the overall last 10 logins for all users
|
||||||
const loginsQuery = 'SELECT username, lastLogin FROM users ORDER BY lastLogin DESC LIMIT 10';
|
const loginsQuery = 'SELECT username, lastLogin FROM users ORDER BY lastLogin DESC LIMIT 10';
|
||||||
|
|
||||||
mysqlConnection.query(loginsQuery, (error, loginResults) => {
|
connection.query(loginsQuery, (error, loginResults) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error('Error executing login logs query:', error);
|
console.error('Error executing login logs query:', error);
|
||||||
res.status(500).send('Internal Server Error');
|
res.status(500).send('Internal Server Error');
|
||||||
@ -181,7 +181,7 @@ app.get('/inusers', isAuthenticated, (req, res) => {
|
|||||||
// Fetch all user data from the database
|
// Fetch all user data from the database
|
||||||
const allUsersQuery = 'SELECT * FROM users';
|
const allUsersQuery = 'SELECT * FROM users';
|
||||||
|
|
||||||
mysqlConnection.query(allUsersQuery, (error, allUsers) => {
|
connection.query(allUsersQuery, (error, allUsers) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error('Error fetching all users:', error);
|
console.error('Error fetching all users:', error);
|
||||||
res.status(500).send('Internal Server Error');
|
res.status(500).send('Internal Server Error');
|
||||||
@ -261,7 +261,7 @@ app.post('/createUser', async (req, res) => {
|
|||||||
|
|
||||||
// Check if the username is already taken
|
// Check if the username is already taken
|
||||||
const checkUsernameQuery = 'SELECT * FROM users WHERE username = ?';
|
const checkUsernameQuery = 'SELECT * FROM users WHERE username = ?';
|
||||||
mysqlConnection.query(checkUsernameQuery, [username], (usernameQueryErr, usernameResults) => {
|
connection.query(checkUsernameQuery, [username], (usernameQueryErr, usernameResults) => {
|
||||||
if (usernameQueryErr) {
|
if (usernameQueryErr) {
|
||||||
console.error('Error checking username:', usernameQueryErr);
|
console.error('Error checking username:', usernameQueryErr);
|
||||||
return res.status(500).json({ error: 'Internal Server Error' });
|
return res.status(500).json({ error: 'Internal Server Error' });
|
||||||
@ -275,7 +275,7 @@ app.post('/createUser', async (req, res) => {
|
|||||||
|
|
||||||
// Check if the email is already taken
|
// Check if the email is already taken
|
||||||
const checkEmailQuery = 'SELECT * FROM users WHERE email = ?';
|
const checkEmailQuery = 'SELECT * FROM users WHERE email = ?';
|
||||||
mysqlConnection.query(checkEmailQuery, [email], (emailQueryErr, emailResults) => {
|
connection.query(checkEmailQuery, [email], (emailQueryErr, emailResults) => {
|
||||||
if (emailQueryErr) {
|
if (emailQueryErr) {
|
||||||
console.error('Error checking email:', emailQueryErr);
|
console.error('Error checking email:', emailQueryErr);
|
||||||
return res.status(500).json({ error: 'Internal Server Error' });
|
return res.status(500).json({ error: 'Internal Server Error' });
|
||||||
@ -295,7 +295,7 @@ app.post('/createUser', async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Start a transaction
|
// Start a transaction
|
||||||
mysqlConnection.beginTransaction((transactionErr) => {
|
connection.beginTransaction((transactionErr) => {
|
||||||
if (transactionErr) {
|
if (transactionErr) {
|
||||||
console.error('Error starting transaction:', transactionErr);
|
console.error('Error starting transaction:', transactionErr);
|
||||||
return res.status(500).json({ error: 'Internal Server Error' });
|
return res.status(500).json({ error: 'Internal Server Error' });
|
||||||
@ -309,12 +309,12 @@ app.post('/createUser', async (req, res) => {
|
|||||||
console.log('Query Parameters:', [name, username, email, hashedPassword, jobTitle]);
|
console.log('Query Parameters:', [name, username, email, hashedPassword, jobTitle]);
|
||||||
|
|
||||||
// Execute the query with user data
|
// Execute the query with user data
|
||||||
mysqlConnection.query(insertUserQuery, [name, username, email, hashedPassword, jobTitle], (queryErr, results) => {
|
connection.query(insertUserQuery, [name, username, email, hashedPassword, jobTitle], (queryErr, results) => {
|
||||||
if (queryErr) {
|
if (queryErr) {
|
||||||
console.error('Error executing query:', queryErr);
|
console.error('Error executing query:', queryErr);
|
||||||
|
|
||||||
// Rollback the transaction in case of an error
|
// Rollback the transaction in case of an error
|
||||||
mysqlConnection.rollback((rollbackErr) => {
|
connection.rollback((rollbackErr) => {
|
||||||
if (rollbackErr) {
|
if (rollbackErr) {
|
||||||
console.error('Error rolling back transaction:', rollbackErr);
|
console.error('Error rolling back transaction:', rollbackErr);
|
||||||
}
|
}
|
||||||
@ -326,7 +326,7 @@ app.post('/createUser', async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Commit the transaction
|
// Commit the transaction
|
||||||
mysqlConnection.commit((commitErr) => {
|
connection.commit((commitErr) => {
|
||||||
if (commitErr) {
|
if (commitErr) {
|
||||||
console.error('Error committing transaction:', commitErr);
|
console.error('Error committing transaction:', commitErr);
|
||||||
// Log unsuccessful user creation due to an error
|
// Log unsuccessful user creation due to an error
|
||||||
@ -375,7 +375,7 @@ app.post('/forgot-password', (req, res) => {
|
|||||||
|
|
||||||
// Check if the username or email exists in the database
|
// Check if the username or email exists in the database
|
||||||
const checkUserQuery = 'SELECT * FROM users WHERE username = ? OR email = ?';
|
const checkUserQuery = 'SELECT * FROM users WHERE username = ? OR email = ?';
|
||||||
mysqlConnection.query(checkUserQuery, [usernameOrEmail, usernameOrEmail], (checkError, checkResults) => {
|
connection.query(checkUserQuery, [usernameOrEmail, usernameOrEmail], (checkError, checkResults) => {
|
||||||
if (checkError) {
|
if (checkError) {
|
||||||
console.error('Error checking user:', checkError);
|
console.error('Error checking user:', checkError);
|
||||||
const error = 'An error occurred during the password reset process.';
|
const error = 'An error occurred during the password reset process.';
|
||||||
@ -391,7 +391,7 @@ app.post('/forgot-password', (req, res) => {
|
|||||||
|
|
||||||
// Update user with reset token and expiry
|
// Update user with reset token and expiry
|
||||||
const updateQuery = 'UPDATE users SET reset_token = ?, reset_token_expiry = ? WHERE id = ?';
|
const updateQuery = 'UPDATE users SET reset_token = ?, reset_token_expiry = ? WHERE id = ?';
|
||||||
mysqlConnection.query(updateQuery, [resetToken, resetTokenExpiry, user.id], (updateError) => {
|
connection.query(updateQuery, [resetToken, resetTokenExpiry, user.id], (updateError) => {
|
||||||
if (updateError) {
|
if (updateError) {
|
||||||
console.error('Error updating reset token:', updateError);
|
console.error('Error updating reset token:', updateError);
|
||||||
const error = 'An error occurred during the password reset process.';
|
const error = 'An error occurred during the password reset process.';
|
||||||
@ -444,7 +444,7 @@ app.post('/reset-password/:token', async (req, res) => {
|
|||||||
|
|
||||||
// Find user with matching reset token and not expired
|
// Find user with matching reset token and not expired
|
||||||
const selectQuery = 'SELECT * FROM users WHERE reset_token = ? AND reset_token_expiry > NOW()';
|
const selectQuery = 'SELECT * FROM users WHERE reset_token = ? AND reset_token_expiry > NOW()';
|
||||||
mysqlConnection.query(selectQuery, [token], async (selectErr, selectResults) => {
|
connection.query(selectQuery, [token], async (selectErr, selectResults) => {
|
||||||
if (selectErr) {
|
if (selectErr) {
|
||||||
console.error('Error querying reset token:', selectErr);
|
console.error('Error querying reset token:', selectErr);
|
||||||
return res.status(500).json({ error: 'Error querying reset token' });
|
return res.status(500).json({ error: 'Error querying reset token' });
|
||||||
@ -472,7 +472,7 @@ app.post('/reset-password/:token', async (req, res) => {
|
|||||||
|
|
||||||
// Update user's password and clear reset token
|
// Update user's password and clear reset token
|
||||||
const updateQuery = 'UPDATE users SET password = ?, reset_token = NULL, reset_token_expiry = NULL WHERE reset_token = ?';
|
const updateQuery = 'UPDATE users SET password = ?, reset_token = NULL, reset_token_expiry = NULL WHERE reset_token = ?';
|
||||||
mysqlConnection.query(updateQuery, [hashedPassword, token], (updateErr) => {
|
connection.query(updateQuery, [hashedPassword, token], (updateErr) => {
|
||||||
if (updateErr) {
|
if (updateErr) {
|
||||||
console.error('Error updating password:', updateErr);
|
console.error('Error updating password:', updateErr);
|
||||||
// Pass the error to the template when rendering the reset-password page
|
// Pass the error to the template when rendering the reset-password page
|
||||||
@ -524,7 +524,7 @@ app.post('/reset-password', async (req, res) => {
|
|||||||
|
|
||||||
// Update user's password based on the username
|
// Update user's password based on the username
|
||||||
const updateQuery = 'UPDATE users SET password = ? WHERE username = ?';
|
const updateQuery = 'UPDATE users SET password = ? WHERE username = ?';
|
||||||
mysqlConnection.query(updateQuery, [hashedPassword, username], (updateErr, updateResults) => {
|
connection.query(updateQuery, [hashedPassword, username], (updateErr, updateResults) => {
|
||||||
if (updateErr) {
|
if (updateErr) {
|
||||||
console.error('Error updating password:', updateErr);
|
console.error('Error updating password:', updateErr);
|
||||||
return res.status(500).json({ error: 'Error updating password' });
|
return res.status(500).json({ error: 'Error updating password' });
|
||||||
@ -546,7 +546,7 @@ async function checkIfUserExists(username) {
|
|||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const query = 'SELECT * FROM users WHERE username = ?';
|
const query = 'SELECT * FROM users WHERE username = ?';
|
||||||
mysqlConnection.query(query, [username], (err, results) => {
|
connection.query(query, [username], (err, results) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
} else {
|
} else {
|
||||||
|
17
Web-Server/functions/getAPIKey.js
Normal file
17
Web-Server/functions/getAPIKey.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
//model for getting API key from database
|
||||||
|
|
||||||
|
async function getAPIKey() {
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
module.exports = { getAPIKey }
|
@ -1,3 +1,5 @@
|
|||||||
|
const { getAPIKey } = require('../db/ApiKeys');
|
||||||
|
|
||||||
function apiKeyMiddleware(req, res, next) {
|
function apiKeyMiddleware(req, res, next) {
|
||||||
const apiKey = req.headers['x-api-key'];
|
const apiKey = req.headers['x-api-key'];
|
||||||
|
|
||||||
@ -14,4 +16,4 @@ function apiKeyMiddleware(req, res, next) {
|
|||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = apiKeyMiddleware;
|
module.exports = { apiKeyMiddleware }
|
||||||
|
@ -19,4 +19,4 @@ const APIlogger = (req, res, next) => {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = { }
|
module.exports = { APIlogger }
|
@ -12,12 +12,21 @@ const port = 80;
|
|||||||
app.disable('x-powered-by')
|
app.disable('x-powered-by')
|
||||||
|
|
||||||
|
|
||||||
|
//middleware logic
|
||||||
|
//app.use('/api/v1', require('../middleware/ApiKey.js'));
|
||||||
|
//app.use('/api/v1', require('../middleware/ApiLogger.js'));
|
||||||
|
|
||||||
|
//route logic
|
||||||
|
app.use('/api/', require('../routes/api_route.js'));
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
const testRoute = require("../routes/test.js")
|
const testRoute = require("../routes/test.js")
|
||||||
const latestDataroute = require("../routes/latest-Data.js")
|
const latestDataroute = require("../routes/latest-Data.js")
|
||||||
|
|
||||||
app.use('/test', testRoute);
|
app.use('/test', testRoute);
|
||||||
app.use('/api/latest-data', latestDataroute);
|
app.use('/api/latest-data', latestDataroute);
|
||||||
|
*/
|
||||||
|
|
||||||
app.listen(port, () => {
|
app.listen(port, () => {
|
||||||
console.log(`app listening on port ${port}`);
|
console.log(`app listening on port ${port}`);
|
||||||
|
23
Web-Server/routes/api_route.js
Normal file
23
Web-Server/routes/api_route.js
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
/*
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const router = require('express').Router();
|
||||||
|
const middleware = require('../middleware/auth');
|
||||||
|
|
||||||
|
router.use('/runner', require('./runner'));
|
||||||
|
router.use('/worker', require('./worker'));
|
||||||
|
router.use('/auth', require('./auth'));
|
||||||
|
router.use('/user', middleware.auth, require('./user'));
|
||||||
|
router.use('/token',middleware.auth, require('./token'));
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
const router = require('express').Router();
|
||||||
|
|
||||||
|
router.use('/test' , require('./test'));
|
||||||
|
router.use('/latest-data', require('./latest-data'));
|
||||||
|
|
||||||
|
module.exports = router;
|
Loading…
x
Reference in New Issue
Block a user