can some one help me
Published: 2023-04-24 13:57:57

**my javascript code is not working efficiently and is not sending otps**

require("dotenv").config();
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
const ejs = require('ejs');
const path = require("path");
const flash = require('express-flash');
const app = express();
const nodemailer = require("nodemailer");
const router =  express.Router();
const { v4: uuidv4 } = require('uuid');
const bcrypt = require("bcryptjs");
//const json = require('json');
require("./src/db/conn");
const port = process.env.PORT || 5000;
const Register = require("./src/models/registers");
const UserOTPVerification = require("./src/models/UserOTPVerification");
//node mailer
let transporter = nodemailer.createTransport({
    host:"smtp.office365.com",
    port:589,
    secure: false,
    auth:{
        user: process.env.AUTH_EMAIL,
        pass: process.env.AUTH_PASS,
    },
    tls:{
        rejectUnauthorized:false
    }
    //     //  tls: {
    //     ciphers:'SSLv3'
    // }
});
transporter.verify((error, success)=>{
    if(error){
console.log(error);
console.log("error occured at 193");
    }
    else{
        console.log("Ready for message");
        console.log(success);
    }
  
});

/this/
//const publicPath=path.join(__dirname,'../public');
//app.use(express.static(publicPath))
//app.use(express.static(static_path))

/this/ 
//const {json} = require("express");
const {log} = require("console");
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.set('view engine','ejs')
app.use(bodyParser.json())
app.use(express.static('public'))
app.use(bodyParser.urlencoded({
    extended:true
})
   )
     app.get('/',(req,res)=>{
        return res.render('register.ejs');
    })
    app.get('/register',(req,res)=>{
        return res.render('register.ejs');
    })
   app.get('/login',(req,res)=>{
        return res.render('register.ejs');
    })
     app.post("/register",async(req,res)=>{
        try{
        const registerEmployee = new Register({
         name: req.body.name,
         RollNumber: req.body.RollNumber,
         email: req.body.email,
         password: req.body.password,
        })
        // if( name == "" || RollNumber == "" || email=="" || password == "")
        // {
        //     res.json ({
        //         satus:"Failed",
        //         message:"Empty input fields",
        //     });
        // }
        // else{
  //this

    //  .then((result)=>
    // {
    //     sendOTPVerification(result,res)
    // });
    const user = await registerEmployee.save()
     .then((email)=>
     {
         sendOTPVerification(email,res)
     });
         // }
         res.status(201).render("cse.ejs")
    }
         catch(error){
            res.status(400).send(error);
         }
      });
    const sendOTPVerification = async({_id,email},res)=>
    {
    try {
    const otp = `${Math.floor(1000 + Math.random()*9000)}`;
    const mailoptions = {
    from: process.env.AUTH_EMAIL,
    to: email,
    subject: "verify your email",
    html:`<p> Enter <b>${otp}</b> to complete sign up process</p>
    <p>This <b> OTP </b> expirse in 15min`,
    };
    
    const hashedOTP = await bcrypt.hash(otp,10);
    const newOTPVerification = await new UserOTPVerification({
    userId: _id,
    otp: hashedOTP,
    createdAt:Date.now(),
    expiryAt:Date.now() + 12000,
    });
    await newOTPVerification.save();
    transporter.sendMail(mailoptions);
    res.json({
    status:"PENDING",
    message:"Verification otp email sent",
    data:{
       userId: _id,
       email,
    }
    })
    } catch (error) {
    res.json({
       status:"FAILED",
       message:error.message,
    });
    }
    }
app.post("/login", async(req,res)=>{
    try {
        const email=req.body.email;
        const password=req.body.password;
      //  console.log(`${email} and password is ${password}`)
      const useremail= await Register.findOne({email:email});

    const isMatch =await bcrypt.compare(password,useremail.password);
    //console.log(`password is ${password},${useremail.password}`);
    if(isMatch){
        res.status(201).render("cse.ejs");
    }
    else{
        res.send("password not matching");
        }
      }
    catch(error) {
        res.status(400).send(error);
    }
}
)
app.listen(port, ()=>{
console.log(`listening on port ${port}`);
})