skip to Main Content

in index.js,

const express = require("express")
const mongoose = require("mongoose")
const cors = require("cors")
const CustomerModel = require('./models/Customer')




const app = express()
app.use(express.json())
app.use(cors())

mongoose.connect("mongodb://localhost:27017/customer")

app.post("/login", (req, res) => {
    const {email, password} = req.body
    CustomerModel.findOne({email: email})
    .then(user => {
        if(user) {
            if(user.password === password) {
                res.json("Success")
            } else {
                res.json("the password is incorrect")
            }
        } else {
            res.json("No record existed")
        }
    })
})


app.post('/register', (req, res) => {
    CustomerModel.create(req.body)
    .then(customers => res.json(customers))
    .catch(err => res.json(err))
})

app.listen(3001, () => {
    console.log("server is running")
}) 

////////////////

in customer.js,

const mongoose = require("mongoose")

const CustomerSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String,

})

const CustomerModel = mongoose.model("customer", CustomerSchema)
module.exports = CustomerModel

/////////////////

Help me modify this code so that i could have email verification,
NOTE: i’ve installed nodemailer, crypto, dotenv and all the necessary things for email verification.

please put it some notes as well to modify my front-end on what should i add? I put lots of code so that you could modify it to make the email verificastion happen. So please answer this bcs im learning react and node. BTW this is the backend so as ui mention please add in details if i need to modify my front-end. You could modify it either email verification using OTP or using links.

2

Answers


  1. Please try below solution…

    First of all you need to Setup Environment Variables using .env file..

    EMAIL_USER = [email protected]
    EMAIL_PASS = your-email-password
    EMAIL_HOST = smtp.your-email-provider.com
    EMAIL_PORT = 587
    JWT_SECRET = your-secret-key
    

    index.js:

    const express = require("express");
    const mongoose = require("mongoose");
    const cors = require("cors");
    const crypto = require("crypto");
    const nodemailer = require("nodemailer");
    const dotenv = require("dotenv");
    const CustomerModel = require('./models/Customer');
    
    dotenv.config();
    
    const app = express();
    app.use(express.json());
    app.use(cors());
    
    mongoose.connect("mongodb://localhost:27017/customer", { useNewUrlParser: true, useUnifiedTopology: true });
    
    const transporter = nodemailer.createTransport({
        host: process.env.EMAIL_HOST,
        port: process.env.EMAIL_PORT,
        secure: false, // true for 465, false for other ports
        auth: {
            user: process.env.EMAIL_USER,
            pass: process.env.EMAIL_PASS
        }
    });
    
    app.post("/register", (req, res) => {
        const { name, email, password } = req.body;
        const verificationToken = crypto.randomBytes(20).toString('hex');
        
        const newCustomer = new CustomerModel({
            name,
            email,
            password,
            verificationToken,
            isVerified: false
        });
        
        newCustomer.save()
            .then(customer => {
                const verificationLink = `http://localhost:3000/verify-email?token=${verificationToken}`;
    
                const mailOptions = {
                    from: process.env.EMAIL_USER,
                    to: customer.email,
                    subject: 'Email Verification',
                    text: `Please verify your email by clicking the following link: ${verificationLink}`
                };
    
                transporter.sendMail(mailOptions, (error, info) => {
                    if (error) {
                        return res.status(500).json({ error: 'Failed to send verification email' });
                    }
                    res.status(200).json({ message: 'Registration successful, please verify your email' });
                });
            })
            .catch(err => res.status(500).json(err));
    });
    
    app.get("/verify-email", (req, res) => {
        const { token } = req.query;
        
        CustomerModel.findOne({ verificationToken: token })
            .then(user => {
                if (!user) {
                    return res.status(400).json({ error: 'Invalid or expired token' });
                }
                
                user.isVerified = true;
                user.verificationToken = null;
                user.save()
                    .then(() => res.status(200).json({ message: 'Email verified successfully' }))
                    .catch(err => res.status(500).json(err));
            })
            .catch(err => res.status(500).json(err));
    });
    
    app.post("/login", (req, res) => {
        const { email, password } = req.body;
        CustomerModel.findOne({ email: email })
            .then(user => {
                if (user) {
                    if (user.password === password) {
                        if (user.isVerified) {
                            res.json("Success");
                        } else {
                            res.json("Please verify your email first");
                        }
                    } else {
                        res.json("The password is incorrect");
                    }
                } else {
                    res.json("No record existed");
                }
            })
            .catch(err => res.status(500).json(err));
    });
    
    app.listen(3001, () => {
        console.log("Server is running on port 3001");
    });
    

    models/Customer.js:

    const mongoose = require("mongoose");
    
    const CustomerSchema = new mongoose.Schema({
        name: String,
        email: String,
        password: String,
        verificationToken: String,
        isVerified: { type: Boolean, default: false }
    });
    
    const CustomerModel = mongoose.model("Customer", CustomerSchema);
    module.exports = CustomerModel;
    

    So, You also need to change front-end part code.

    Login or Signup to reply.
  2. use async function to get response from models

    app.post("/login", async (req, res) => {
        const {email, password} = req.body
       await CustomerModel.findOne({email: email})
        .then(user => {
            if(user) {
                if(user.password === password) {
                    res.json("Success")
                } else {
                    res.json("the password is incorrect")
                }
            } else {
                res.json("No record existed")
            }
        })
    })
    
    
    
    app.post('/register',async (req, res) => {
       await CustomerModel.create(req.body)
        .then(customers => res.json(customers))
        .catch(err => res.json(err))
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search