Thursday, 13 March 2025

OPT section in web site

 import { useState } from "react";

import { useLocation, useNavigate } from "react-router-dom";
import axios from "axios";

const VerifyOtp = () => {
  const [otp, setOtp] = useState("");
  const location = useLocation();
  const navigate = useNavigate();
  const email = location.state?.email; // Get email from state

  const handleVerifyOtp = async (e) => {
    e.preventDefault();
    try {
      await axios.post("http://localhost:5000/api/auth/verify-otp", { email, otp });
      alert("Account verified successfully!");
      navigate("/signin"); // Redirect to Sign-in page
      setTimeout(() => {
        alert("Thank you! Now you can sign in and use your blog.");
      }, 1000);
    // eslint-disable-next-line no-unused-vars
    } catch (error) {
      alert("Invalid OTP");
    }
  };

  return (
    <div className="max-w-md mx-auto mt-10">
      <h2 className="text-2xl font-bold">Verify OTP</h2>
      <form onSubmit={handleVerifyOtp} className="flex flex-col gap-4">
        <input type="text" name="otp" placeholder="Enter OTP" className="border p-2" onChange={(e) => setOtp(e.target.value)} required />
        <button type="submit" className="bg-green-500 text-white p-2">Verify OTP</button>
      </form>
    </div>
  );
};

export default VerifyOtp;



// Generate OTP
const generateOTP = () => Math.floor(100000 + Math.random() * 900000).toString();

// Register User
router.post("/signup", async (req, res) => {
  try {
    const { name, email, password, contact } = req.body;

    const userExists = await User.findOne({ email });
    if (userExists) return res.status(400).json({ message: "User already exists" });

    const hashedPassword = await bcrypt.hash(password, 10);
    const otp = generateOTP();

    const user = new User({ name, email, password: hashedPassword, contact, otp });
    await user.save();

    // Send OTP Email
    await transporter.sendMail({
      from: process.env.EMAIL_USER,
      to: email,
      subject: "Your OTP Code",
      text: `Your OTP is: ${otp}`
    });

    res.status(201).json({ message: "User registered! Verify OTP." });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// Verify OTP
router.post("/verify-otp", async (req, res) => {
  try {
    const { email, otp } = req.body;
    const user = await User.findOne({ email });

    if (!user) return res.status(400).json({ message: "User not found" });
    if (user.otp !== otp) return res.status(400).json({ message: "Invalid OTP" });

    user.verified = true;
    user.otp = "";
    await user.save();

    res.status(200).json({ message: "Account verified! You can now log in." });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

No comments:

Post a Comment

3D card hover

 import { motion } from "framer-motion"; import React from "react"; const Card = ({ title, price, image }) => {   ret...