update to log when user login (successful and unsuccessful)

This commit is contained in:
BIG2EYEZ 2023-12-26 19:49:48 +08:00
parent 1db32e3c7a
commit 4be58724d2

View File

@ -57,6 +57,32 @@ app.get('/login', (req, res) => {
res.render('login', { error: null });
});
const logActivity = async (username, success) => {
try {
const activity = success ? 'successful login' : 'unsuccessful login due to invalid password or username';
const logSql = 'INSERT INTO user_logs (username, activity, timestamp) VALUES (?, ?, CURRENT_TIMESTAMP)';
const logParams = [username, activity];
const connection = mysql.createConnection(mysqlConfig);
connection.connect();
connection.query(logSql, logParams, (error, results) => {
if (error) {
console.error('Error logging activity:', error);
// Handle error (you may want to log it or take other appropriate actions)
} else {
console.log('Activity logged successfully');
}
connection.end(); // Close the connection after logging activity
});
} catch (error) {
console.error('Error in logActivity function:', error);
// Handle error (you may want to log it or take other appropriate actions)
}
};
app.post('/login', async (req, res) => {
try {
let { username, password } = req.body;
@ -65,9 +91,7 @@ app.post('/login', async (req, res) => {
const loginSql = 'SELECT * FROM users WHERE username = ?';
const updateLastLoginSql = 'UPDATE users SET lastLogin = CURRENT_TIMESTAMP WHERE username = ?';
// Check credentials and retrieve user information
const connection = mysql.createConnection(mysqlConfig);
connection.connect();
console.log('Login Query:', loginSql);
@ -83,15 +107,14 @@ app.post('/login', async (req, res) => {
return;
}
if (results.length === 0) {
// Pass the error to the template
res.render('login', { error: 'Invalid username or password' });
connection.end(); // Close the connection when not needed anymore
} else {
const user = results[0];
const passwordMatch = await bcrypt.compare(password, user.password);
const isLoginSuccessful = results.length > 0 && (await bcrypt.compare(password, results[0].password));
// Log login attempt
await logActivity(username, isLoginSuccessful);
if (isLoginSuccessful) {
const user = results[0];
if (passwordMatch) {
// Update lastLogin field for the user
connection.query(updateLastLoginSql, [username], (updateError, updateResults) => {
if (updateError) {
@ -125,7 +148,6 @@ app.post('/login', async (req, res) => {
res.render('login', { error: 'Invalid username or password' });
connection.end(); // Close the connection when not needed anymore
}
}
});
} catch (error) {
console.error('Error in login route:', error);
@ -135,6 +157,7 @@ app.post('/login', async (req, res) => {
// Update your /home route to retrieve the overall last 10 logins for all users
app.get('/home', isAuthenticated, (req, res) => {
// Retrieve the overall last 10 logins for all users