I want to add reset password function in authenticate page using SMTP service

I am using HTML, CSS, and JavaScript in the frontend, along with Node.js in the backend. MongoDB serves as the database, while SendGrid handles SMTP. Although the browser indicates that the email has been successfully sent, neither the inbox nor the junk box receives the email.

authRoutes.js

const express = require('express');
const router = express.Router();
const authController = require('../controllers/authController');

// Route for user registration (POST request)
router.post('/register', authController.register);

// Route for user login (POST request)
router.post('/login', authController.login);

// Route for password reset (POST request)
router.post('/reset', authController.resetPassword);

module.exports = router;

quizRoutes.js

const express = require('express');
const router = express.Router();
const QuizResult = require('../models/quizResult');

// Route handler for saving quiz results
router.post('/', async (req, res) => {
    try {
        const { percentage, correctAnswers, totalQuestions } = req.body;
        
        // Create document to insert
        const quizResult = new QuizResult({
            percentage,
            correctAnswers,
            totalQuestions
        });

        // Save quiz result to database
        await quizResult.save();

        res.status(201).json({ message: 'Quiz result saved successfully' });
    } catch (error) {
        console.error('Error saving quiz result:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
});

module.exports = router;

userRoutes.js

const express = require('express');
const router = express.Router();

// Placeholder route handler for user registration
router.post('/register', (req, res) => {
    // Handle user registration logic here
    res.send('User registration endpoint');
});

// Placeholder route handler for user login
router.post('/login', (req, res) => {
    // Handle user login logic here
    res.send('User login endpoint');
});

// Placeholder route handler for user profile
router.get('/:userId/profile', (req, res) => {
    // Fetch user profile based on userId
    const userId = req.params.userId;
    // Fetch user profile logic here
    res.send(`User profile for userId: ${userId}`);
});

module.exports = router;

quizResult.js

const mongoose = require('mongoose');

const quizResultSchema = new mongoose.Schema({
    correctAnswers: {
        type: Number,
        required: true
    },
    totalQuestions: {
        type: Number,
        required: true
    },
    totalScore: {
        type: Number,
        required: true
    }
});

const QuizResult = mongoose.model('QuizResult', quizResultSchema);

module.exports = QuizResult;

user.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    }
});

const User = mongoose.model('User', userSchema);

module.exports = User;

authController.js

const bcrypt = require('bcrypt');
const jwtUtils = require('../utils/jwtUtils');
const User = require('../models/user');
const QuizResult = require('../models/quizResult');

// Function to handle user registration
exports.register = async (req, res) => {
    try {
        const { name, email, password } = req.body;

        // Hash the password before saving
        const hashedPassword = await bcrypt.hash(password, 10);

        // Create a new user instance with hashed password
        const newUser = new User({ name, email, password: hashedPassword });
        
        // Save the user to the database
        await newUser.save();
        
        // Respond with success message
        res.status(201).json({ message: 'User registered successfully' });
    } catch (error) {
        // Handle registration errors
        res.status(400).json({ error: error.message });
    }
};

// Function to handle user login
exports.login = async (req, res) => {
    try {
        const { email, password } = req.body;
        
        // Find the user by email
        const user = await User.findOne({ email });
        
        if (!user) {
            // If user not found, respond with error message
            return res.status(401).json({ error: 'Invalid email or password' });
        }
        
        // Compare passwords
        const isPasswordValid = await bcrypt.compare(password, user.password);
        
        if (!isPasswordValid) {
            // If password is incorrect, respond with error message
            return res.status(401).json({ error: 'Invalid email or password' });
        }
        
        // Generate JWT token
        const token = jwtUtils.generateToken(user._id);

        // Example of fetching quiz results for the user
        const quizResults = await QuizResult.find({ user: user._id });
        
        // Respond with token and quiz results
        res.json({ token, quizResults });
    } catch (error) {
        // Handle login errors
        console.error('Login Error:', error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
};

app.js

const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const path = require('path');
const crypto = require('crypto');
const nodemailer = require('nodemailer');

const User = require('./models/user');
const QuizResult = require('./models/quizResult');
const authRoutes = require('./routes/authRoutes');
const quizRoutes = require('./routes/quizRoutes');
const userRoutes = require('./routes/userRoutes');

const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/stallman', { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));

// Nodemailer Configuration
// Create Nodemailer transporter with SendGrid SMTP settings
const transporter = nodemailer.createTransport({
  host: 'smtp.sendgrid.net', // SendGrid SMTP hostname
  port: 587, // SendGrid SMTP port (587 for TLS)
  secure: false, // true for 465, false for other ports (587 for TLS)
  auth: {
    user: 'API Key', // SendGrid API key (not your email address)
    pass: '*****', // SendGrid API key
  },
});

// Generate a secure random string to use as a session secret
const sessionSecret = crypto.randomBytes(64).toString('hex');

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
  secret: sessionSecret,
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

// Passport Configuration
// Your existing passport configuration...

// Serve static files from the public directory
app.use(express.static(path.join(__dirname, 'public')));

// Routes
app.use('/auth', authRoutes);
app.use('/api/quizResults', quizRoutes);
app.use('/api/users', userRoutes);

// Define route for the login page
app.get('/login', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'login.html'));
});

// Define route for the register page
app.get('/register', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'register.html'));
});

// Password Reset Route
app.post('/reset', async (req, res) => {
  const { email } = req.body;

  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }

    // Generate reset token (Example implementation)
    const resetToken = crypto.randomBytes(20).toString('hex');

    // Send password reset email
    await transporter.sendMail({
      from: '[email protected]', // Replace with your email address
      to: email,
      subject: 'Password Reset Request',
      html: `<p>You've requested a password reset. Click <a href="http://example.com/reset-password/${resetToken}">here</a> to reset your password.</p>`
    });

    res.json({ message: 'Password reset email sent' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// Define route for user login
// Your existing login route...

// Define route for the root path
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
enter image description here

I want to receive emails using the SendGrid SMTP server.

New contributor

Sachin Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật