Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Implemented Account verification , Email validation. issue:#152 #155

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions client/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Login from "./pages/Login/login";
import ResetPassword from "./components/Reset-Password";
import ForgotPassword from "./components/Forgot-Password";
import Signup from "./pages/Signup/signup";
import VerifyEmail from "./pages/Verify-email";
import Layout_retailer from "./components/layout-retailer";
import Designer_home from "./pages/Designers";
import About from "./pages/About";
Expand Down Expand Up @@ -38,6 +39,7 @@ function App() {
<Route path="/forgot-password" element={<ForgotPassword />} />
<Route path="/reset-password/:token/:id" element={<ResetPassword />} />
<Route path="signup" element={<Signup />} />
<Route path="/verify-email" element={<VerifyEmail/>} />
<Route path="designers" element={<Designer_home />} />
<Route path="about" element={<About />} />
<Route path="product" element={<Product />} />
Expand Down
4 changes: 2 additions & 2 deletions client/src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import {persistStore} from 'redux-persist';
const persistor = persistStore(store)
ReactDOM.createRoot(document.getElementById("root")).render(
<Provider store={store}>
<React.StrictMode>

<PersistGate persistor={persistor}>
<App />
<Toaster />
</PersistGate>
</React.StrictMode>

</Provider>
);
415 changes: 204 additions & 211 deletions client/src/pages/Signup/signup.jsx

Large diffs are not rendered by default.

68 changes: 68 additions & 0 deletions client/src/pages/Verify-email/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import axios from 'axios';
import toast from 'react-hot-toast';

const VerifyEmail = () => {
const location = useLocation();
const navigate = useNavigate();
const query = new URLSearchParams(location.search);
const token = query.get('token');
const email = query.get('email');
const status = query.get('status');
const [isVerified, setIsVerified] = useState(false);

useEffect(() => {
const verifyAccount = async () => {
if (status === 'success') {
toast.success('Account verified successfully!');
setIsVerified(true);
return;
}

if (token && email && !isVerified) {
try {
const response = await axios.get(`http://localhost:3000/api/users/verify-email?token=${token}&email=${email}`);
if (response.data.success) {
toast.success('Account verified successfully!');
setIsVerified(true);

} else {
toast.error('Verification failed. Please try again.');
}
} catch (error) {
toast.error('Verification failed. Please try again.');
}
}
};

verifyAccount();
}, [token, email, status, isVerified]);

const handleLoginRedirect = () => {
navigate('/login');
};

return (
<div className="flex justify-center items-center h-screen bg-gray-100">
<div className="bg-white p-10 rounded shadow-md">
{isVerified ? (
<div className="text-center">
<h2 className="text-2xl font-bold mb-4">Verification Successful</h2>
<p>Your account has been verified successfully!</p>

<button className="text-white py-2 px-4 mt-6 uppercase rounded bg-indigo-500 hover:bg-indigo-600 shadow hover:shadow-lg font-medium transition transform hover:-translate-y-0.5"
onClick={handleLoginRedirect} >Login</button>
</div>
) : (
<div className="text-center ">
<h2 className="text-2xl font-bold mb-4">Verification failed</h2>
<p>Try after some time.</p>
</div>
)}
</div>
</div>
);
};

export default VerifyEmail;
38 changes: 30 additions & 8 deletions server/controllers/user.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import bcrypt from "bcryptjs";
import { sendCookie } from "../utils/features.js";
import { PrismaClient } from "@prisma/client";
import { sendVerifyEmail } from "../utils/verify-email.js";
import { v4 as uuidv4 } from "uuid";

const prisma = new PrismaClient();

Expand All @@ -18,22 +20,42 @@ const signup = async (req, res) => {
message: "User already exists."
});
}

const hpasswd = await bcrypt.hash(passwd, 10);
const newUser = await prisma.mainuser.create({
data: {

const token = uuidv4();
const hashedToken = await bcrypt.hash(token, 10);
const hashedPassword = await bcrypt.hash(passwd, 10);


await prisma.tempUser.upsert({
where: { email },
update: {
name,
profilepic:ppic,
passwd: hashedPassword,
street,
city,
state,
pincode: parseInt(pincode),
token: hashedToken,
},
create: {
name,
email,
profilepic: ppic,
passwd: hpasswd,
profilepic:ppic,
passwd: hashedPassword,
street,
city,
state,
pincode: parseInt(pincode), // making pincode as an integer because it's get a string from 'req'
pincode: parseInt(pincode),
token: hashedToken,
},
});

sendCookie(newUser.email, res, "Registered Successfully", 201);

const verificationLink = `http://localhost:5173/verify-email?token=${token}&email=${email}`;
await sendVerifyEmail(email, verificationLink);
res.status(200).json({ message: 'Verification email sent' });

} catch (err) {
console.error(err);
res.status(500).json({
Expand Down
51 changes: 51 additions & 0 deletions server/controllers/verifyEmail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';


const prisma = new PrismaClient();

export const verifyEmail = async (req, res) => {
const { token, email } = req.query;

try {

const tempUser = await prisma.tempUser.findUnique({
where: { email },
});

if (!tempUser) {
return res.status(400).json({ message: 'Invalid or expired token' });
}

const isValid = await bcrypt.compare(token, tempUser.token);

if (!isValid) {
return res.status(400).json({ message: 'Invalid or expired token' });
}

await prisma.mainuser.create({
data: {
name: tempUser.name,
email: tempUser.email,
profilepic: tempUser.profilepic,
passwd: tempUser.passwd,
street: tempUser.street,
city: tempUser.city,
state: tempUser.state,
pincode: tempUser.pincode,
},
});

await prisma.tempUser.delete({
where: { email },
});

res.status(200).json({ success: true, message: 'Account verified successfully!' });

} catch (error) {
console.error('Error verifying email:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
};

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- CreateTable
CREATE TABLE `TempUser` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL,
`email` VARCHAR(191) NOT NULL,
`profilepic` VARCHAR(191) NULL,
`passwd` VARCHAR(191) NOT NULL,
`street` VARCHAR(191) NOT NULL,
`city` VARCHAR(191) NOT NULL,
`state` VARCHAR(191) NOT NULL,
`pincode` INTEGER NOT NULL,
`token` VARCHAR(191) NOT NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

UNIQUE INDEX `TempUser_email_key`(`email`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
14 changes: 14 additions & 0 deletions server/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,20 @@ model Designer {
mainuser Mainuser @relation(fields: [email], references: [email])
}

model TempUser {
id Int @id @default(autoincrement())
name String
email String @unique
profilepic String?
passwd String
street String
city String
state String
pincode Int
token String
createdAt DateTime @default(now())
}

model Mainuser {
name String
email String @id
Expand Down
4 changes: 3 additions & 1 deletion server/routes/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import express from "express";
import { login, signup, getMyProfile,updateUserProfile, registerdesigner, registerretailer } from "../controllers/user.js";
import { requestPasswordReset, resetPassword } from "../controllers/forgotPassword.js";
import { isAuthenticated } from "../middlewares/auth.js";

import { verifyEmail } from "../controllers/verifyEmail.js";
const router = express.Router();


router.post("/login", login);

router.post("/signup", signup);

router.get('/verify-email', verifyEmail);

router.post("/forgot-password", requestPasswordReset);

router.post("/reset-password/:token/:id", resetPassword);
Expand Down
28 changes: 28 additions & 0 deletions server/utils/verify-email.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import nodemailer from "nodemailer";

export const sendVerifyEmail = async (email, verificationLink) => {
const transporter = nodemailer.createTransport({
service: "Gmail",
port: 465,

secureConnection:false,

auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
},

tls: {
rejectunAuthorized:true
}
});

const mailOptions = {
from: process.env.EMAIL,
to: email,
subject: 'Email Verification',
text:`Click the following link to verify your email: ${verificationLink}`,
};

await transporter.sendMail(mailOptions);
};
Loading