otp and logging done
This commit is contained in:
parent
6342d5a4cb
commit
61b279f9e5
221
Sean/server.js
221
Sean/server.js
@ -5,6 +5,8 @@ const bodyParser = require("body-parser");
|
|||||||
const bcrypt = require("bcrypt");
|
const bcrypt = require("bcrypt");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const nodemailer = require("nodemailer");
|
const nodemailer = require("nodemailer");
|
||||||
|
const otpGenerator = require('otp-generator');
|
||||||
|
|
||||||
|
|
||||||
const { transporter } = require("./modules/nodeMailer");
|
const { transporter } = require("./modules/nodeMailer");
|
||||||
const { connection } = require("./modules/mysql");
|
const { connection } = require("./modules/mysql");
|
||||||
@ -32,108 +34,165 @@ function isAuthenticated(req, res, next) {
|
|||||||
res.redirect("/login");
|
res.redirect("/login");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const generateOTP = () => {
|
||||||
|
const otp = otpGenerator.generate(6, { upperCase: false, specialChars: false });
|
||||||
|
const expirationTime = Date.now() + 5 * 60 * 1000; // 5 minutes expiration
|
||||||
|
return { otp, expirationTime };
|
||||||
|
};
|
||||||
|
|
||||||
|
const sendOTPByEmail = async (email, otp) => {
|
||||||
|
try {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
service: 'gmail',
|
||||||
|
auth: {
|
||||||
|
user: process.env.euser, // replace with your email
|
||||||
|
pass: process.env.epass // replace with your email password
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const mailOptions = {
|
||||||
|
from: process.env.euser,
|
||||||
|
to: email,
|
||||||
|
subject: 'Login OTP',
|
||||||
|
text: `Your OTP for login is: ${otp}`
|
||||||
|
};
|
||||||
|
|
||||||
|
await transporter.sendMail(mailOptions);
|
||||||
|
console.log('OTP sent successfully to', email);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error sending OTP:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
app.get("/login", (req, res) => {
|
app.get("/login", (req, res) => {
|
||||||
// Pass an initial value for the error variable
|
// Pass an initial value for the error variable
|
||||||
res.render("login", { error: null });
|
res.render("login", { error: null });
|
||||||
});
|
});
|
||||||
|
|
||||||
const logActivity = async (username, success) => {
|
const logActivity = async (username, success, message) => {
|
||||||
try {
|
try {
|
||||||
const activity = success
|
if (!username) {
|
||||||
? "successful login"
|
console.error("Error logging activity: Username is null or undefined");
|
||||||
: "unsuccessful login due to invalid password or username";
|
return;
|
||||||
const logSql =
|
}
|
||||||
"INSERT INTO user_logs (username, activity, timestamp) VALUES (?, ?, CURRENT_TIMESTAMP)";
|
|
||||||
const logParams = [username, activity];
|
|
||||||
|
|
||||||
connection.query(logSql, logParams, (error, results) => {
|
const activity = success ? `successful login: ${message}` : `unsuccessful login: ${message}`;
|
||||||
if (error) {
|
const logSql =
|
||||||
console.error("Error logging activity:", error);
|
"INSERT INTO user_logs (username, activity, timestamp) VALUES (?, ?, CURRENT_TIMESTAMP)";
|
||||||
// Handle error (you may want to log it or take other appropriate actions)
|
const logParams = [username, activity];
|
||||||
} else {
|
|
||||||
console.log("Activity logged successfully");
|
|
||||||
}
|
|
||||||
|
|
||||||
});
|
connection.query(logSql, logParams, (error, results) => {
|
||||||
|
if (error) {
|
||||||
|
console.error("Error executing logSql:", error);
|
||||||
|
// Handle error (you may want to log it or take other appropriate actions)
|
||||||
|
} else {
|
||||||
|
console.log("Activity logged successfully");
|
||||||
|
}
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error in logActivity function:", error);
|
console.error("Error in logActivity function:", error);
|
||||||
// Handle error (you may want to log it or take other appropriate actions)
|
// Handle error (you may want to log it or take other appropriate actions)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
app.post("/login", async (req, res) => {
|
|
||||||
|
|
||||||
|
// Login route
|
||||||
|
app.post("/login", async (req, res) => {
|
||||||
try {
|
try {
|
||||||
let { username, password } = req.body;
|
let { username, password } = req.body;
|
||||||
username = username.trim();
|
username = username.trim();
|
||||||
|
|
||||||
const loginSql = "SELECT * FROM users WHERE username = ?";
|
const loginSql = "SELECT * FROM users WHERE username = ?";
|
||||||
const updateLastLoginSql =
|
const updateLastLoginSql = "UPDATE users SET lastLogin = CURRENT_TIMESTAMP WHERE username = ?";
|
||||||
"UPDATE users SET lastLogin = CURRENT_TIMESTAMP WHERE username = ?";
|
|
||||||
|
|
||||||
console.log("Login Query:", loginSql);
|
connection.query(loginSql, [username], async (error, results) => {
|
||||||
console.log("Query Parameters:", [username]);
|
if (error) {
|
||||||
|
console.error("Error executing login query:", error);
|
||||||
|
res.status(500).send("Internal Server Error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
connection.query(loginSql, [username], async (error, results) => {
|
if (results.length > 0) {
|
||||||
console.log("Login Results:", results);
|
const isLoginSuccessful = await bcrypt.compare(password, results[0].password);
|
||||||
|
|
||||||
if (error) {
|
if (isLoginSuccessful) {
|
||||||
console.error("Error executing login query:", error);
|
// Log successful login attempt
|
||||||
res.status(500).send("Internal Server Error");
|
await logActivity(username, true, "Credentials entered correctly");
|
||||||
return;
|
|
||||||
|
const user = results[0];
|
||||||
|
const { otp, expirationTime } = generateOTP();
|
||||||
|
|
||||||
|
// Store the OTP and expiration time in the session for verification
|
||||||
|
req.session.otp = otp;
|
||||||
|
req.session.otpExpiration = expirationTime;
|
||||||
|
req.session.save();
|
||||||
|
|
||||||
|
// Send OTP via email
|
||||||
|
try {
|
||||||
|
await sendOTPByEmail(user.email, otp);
|
||||||
|
// Log successful OTP sending
|
||||||
|
await logActivity(username, true, "OTP successfully sent to user");
|
||||||
|
} catch (sendOTPError) {
|
||||||
|
// Log unsuccessful OTP sending
|
||||||
|
await logActivity(username, false, "OTP failed to send to user");
|
||||||
|
console.error("Error sending OTP:", sendOTPError);
|
||||||
|
res.status(500).send("Internal Server Error");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isLoginSuccessful =
|
// Render OTP input page
|
||||||
results.length > 0 &&
|
res.render("otp", { error: null, username: user.username });
|
||||||
(await bcrypt.compare(password, results[0].password));
|
} else {
|
||||||
|
// Log unsuccessful login attempt
|
||||||
// Log login attempt
|
await logActivity(username, false, "Incorrect password");
|
||||||
await logActivity(username, isLoginSuccessful);
|
res.render("login", { error: "Invalid username or password" });
|
||||||
|
}
|
||||||
if (isLoginSuccessful) {
|
} else {
|
||||||
const user = results[0];
|
// Log unsuccessful login attempt
|
||||||
|
await logActivity(username, false, "User not found");
|
||||||
// Update lastLogin field for the user
|
res.render("login", { error: "Invalid username or password" });
|
||||||
connection.query(
|
}
|
||||||
updateLastLoginSql,
|
});
|
||||||
[username],
|
|
||||||
(updateError, updateResults) => {
|
|
||||||
if (updateError) {
|
|
||||||
console.error("Error updating lastLogin:", updateError);
|
|
||||||
res.status(500).send("Internal Server Error");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the update affected any rows
|
|
||||||
if (updateResults.affectedRows > 0) {
|
|
||||||
// Set session data for authentication
|
|
||||||
req.session.regenerate((err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Error regenerating session:", err);
|
|
||||||
}
|
|
||||||
console.log("Session regenerated successfully");
|
|
||||||
req.session.authenticated = true;
|
|
||||||
req.session.username = username;
|
|
||||||
res.redirect("/home");
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// Pass the error to the template
|
|
||||||
res.render("login", {
|
|
||||||
error: "Error updating lastLogin. No rows affected.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// Pass the error to the template
|
|
||||||
res.render("login", { error: "Invalid username or password" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error in login route:", error);
|
console.error("Error in login route:", error);
|
||||||
res.status(500).send("Internal Server Error");
|
res.status(500).send("Internal Server Error");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
app.post("/verify-otp", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const enteredOTP = req.body.otp;
|
||||||
|
|
||||||
|
if (enteredOTP === req.session.otp) {
|
||||||
|
// Log successful OTP entry and login
|
||||||
|
if (req.body.username) {
|
||||||
|
await logActivity(req.body.username, true, "OTP entered correctly. Successful login");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct OTP, redirect to home page
|
||||||
|
req.session.authenticated = true;
|
||||||
|
req.session.username = req.body.username;
|
||||||
|
res.redirect("/home");
|
||||||
|
} else {
|
||||||
|
// Log unsuccessful OTP entry
|
||||||
|
if (req.body.username) {
|
||||||
|
await logActivity(req.body.username, false, "Incorrect OTP entered");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Incorrect OTP, render login page with error
|
||||||
|
res.render("login", { error: "Incorrect OTP. Please try again." });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error in OTP verification route:", error);
|
||||||
|
res.status(500).send("Internal Server Error");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Update your /home route to retrieve the overall last 10 logins for all users
|
// Update your /home route to retrieve the overall last 10 logins for all users
|
||||||
app.get("/home", isAuthenticated, (req, res) => {
|
app.get("/home", isAuthenticated, (req, res) => {
|
||||||
|
@ -2,13 +2,74 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>OTP QR Code</title>
|
<title>Enter OTP</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
background-color: #f4f4f4;
|
||||||
|
text-align: center;
|
||||||
|
margin: 50px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
form {
|
||||||
|
max-width: 300px;
|
||||||
|
margin: 20px auto;
|
||||||
|
padding: 20px;
|
||||||
|
background-color: #fff;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
background-color: #4caf50;
|
||||||
|
color: #fff;
|
||||||
|
padding: 10px 15px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background-color: #45a049;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: red;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Scan the QR Code to Enable OTP</h1>
|
<h2>Enter OTP</h2>
|
||||||
<p>Hello <%= username %>,</p>
|
|
||||||
<img src="<%= qrCodeDataUrl %>" alt="OTP QR Code">
|
<% if (error) { %>
|
||||||
|
<p class="error"><%= error %></p>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<form action="/verify-otp" method="post">
|
||||||
|
<input type="hidden" name="username" value="<%= username %>">
|
||||||
|
<label for="otp">OTP:</label>
|
||||||
|
<input type="text" id="otp" name="otp" required>
|
||||||
|
<br>
|
||||||
|
<button type="submit">Submit OTP</button>
|
||||||
|
</form>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
5
package-lock.json
generated
5
package-lock.json
generated
@ -1069,6 +1069,11 @@
|
|||||||
"wrappy": "1"
|
"wrappy": "1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"otp-generator": {
|
||||||
|
"version": "4.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/otp-generator/-/otp-generator-4.0.1.tgz",
|
||||||
|
"integrity": "sha512-2TJ52vUftA0+J3eque4wwVtpaL4/NdIXDL0gFWFJFVUAZwAN7+9tltMhL7GCNYaHJtuONoier8Hayyj4HLbSag=="
|
||||||
|
},
|
||||||
"otplib": {
|
"otplib": {
|
||||||
"version": "12.0.1",
|
"version": "12.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/otplib/-/otplib-12.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/otplib/-/otplib-12.0.1.tgz",
|
||||||
|
@ -27,6 +27,7 @@
|
|||||||
"mqtt": "^5.3.3",
|
"mqtt": "^5.3.3",
|
||||||
"mysql2": "^3.6.5",
|
"mysql2": "^3.6.5",
|
||||||
"nodemailer": "^6.9.7",
|
"nodemailer": "^6.9.7",
|
||||||
|
"otp-generator": "^4.0.1",
|
||||||
"otplib": "^12.0.1",
|
"otplib": "^12.0.1",
|
||||||
"qrcode": "^1.5.3",
|
"qrcode": "^1.5.3",
|
||||||
"sequelize": "^6.35.2",
|
"sequelize": "^6.35.2",
|
||||||
|
Loading…
x
Reference in New Issue
Block a user