Creating the Server
Create a file name it as server.js and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OTP Verification</title>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="text"], input[type="password"], button {
width: 100%;
padding: 10px;
margin-bottom: 10px;
box-sizing: border-box;
}
button {
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.message {
margin-top: 10px;
text-align: center;
color: red;
}
</style>
</head>
<body>
<div class="container">
<h2>OTP Verification</h2>
<input type="email" id="email" placeholder="Enter your email">
<button onclick="generateOTP()">Generate OTP</button>
<input type="text" id="otp" placeholder="Enter OTP">
<button onclick="verifyOTP()">Verify OTP</button>
<p class="message" id="response"></p>
</div>
<script>
async function generateOTP() {
const email = document.getElementById('email').value;
const response = await fetch('http://localhost:3000/generate-otp', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email })
});
const result = await response.text();
document.getElementById('response').innerText = result;
}
async function verifyOTP() {
const email = document.getElementById('email').value;
const otp = document.getElementById('otp').value;
const response = await fetch('http://localhost:3000/verify-otp', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, otp })
});
const result = await response.text();
document.getElementById('response').innerText = result;
}
</script>
</body>
</html>
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const otpGenerator = require('otp-generator');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(cors());
// MongoDB connection
mongoose.connect('mongodb+srv://<username>:<password>@cluster0.d6t5od6.mongodb.net/', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
db.once('open', () => {
console.log('Connected to MongoDB');
});
// Define schema and model for OTP
const otpSchema = new mongoose.Schema({
email: String,
otp: String,
createdAt: { type: Date, expires: '5m', default: Date.now }
});
const OTP = mongoose.model('OTP', otpSchema);
// Generate OTP and send email
app.post('/generate-otp', async (req, res) => {
const { email } = req.body;
const otp = otpGenerator.generate(6, { digits: true, alphabets: false, upperCase: false, specialChars: false });
try {
await OTP.create({ email, otp });
// Send OTP via email (replace with your email sending logic)
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-mail@gmail.com',
pass: 'your-app-password'
}
});
await transporter.sendMail({
from: 'your-mail@gmail.com',
to: email,
subject: 'OTP Verification',
text: `Your OTP for verification is: ${otp}`
});
res.status(200).send('OTP sent successfully');
} catch (error) {
console.error(error);
res.status(500).send('Error sending OTP');
}
});
// Verify OTP
app.post('/verify-otp', async (req, res) => {
const { email, otp } = req.body;
try {
const otpRecord = await OTP.findOne({ email, otp }).exec();
if (otpRecord) {
res.status(200).send('OTP verified successfully');
} else {
res.status(400).send('Invalid OTP');
}
} catch (error) {
console.error(error);
res.status(500).send('Error verifying OTP');
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Building an OTP Verification System with Node.js and MongoDB
In the present digital world, Securing your website or internet could be very crucial. One manner to increase protection is by using One Time Password (OTP) for the verification system. This will help you to steady your software and defend your website from unauthorized get entry. This article will help you create an OTP verification device, which you can use in your upcoming initiatives. This venture was created using Nodejs and MongoDB, which is a completely famous technology in net improvement.