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

#8 Email Verification #10

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
MONGODB_URI = "mongodb://0.0.0.0:27017/collection"
PORT = 5000
JWT_SECRET = some_secret
JWT_SECRET = some_secret
EMAIL = your_email
PASSWORD = your_password
64 changes: 61 additions & 3 deletions controllers/authControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,34 @@ import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
import { UserModel } from "@models";
import { Types } from "mongoose";
const nodemailer = require('nodemailer');
require('dotenv').config();

//creating nodemailer variables
const transporter = nodemailer.createTransport({
host : 'smtp.gmail.com',
port : 465,
secure : true,
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
var mailOptions = {
from: process.env.EMAIL,
subject: 'Email Verification',
text: '',
to : ''
};


const signup = async (req: Request, res: Response, next: NextFunction) => {
try {
let user;
if(process.env.EMAIL === undefined || process.env.PASSWORD === undefined) {}
else
console.log(process.env.EMAIL + process.env.PASSWORD)
const { email } = req.body;
user = await UserModel.UserSchema.findOne({ email: email });
if (user) {
Expand All @@ -17,6 +41,9 @@ const signup = async (req: Request, res: Response, next: NextFunction) => {
}
user = await UserModel.UserSchema.create(req.body);
const accessToken = jwt.sign(user.toJSON(), <string>process.env.JWT_SECRET);
mailOptions.to = email;
mailOptions.text = `Click on the link below to verify your email http://localhost:${process.env.PORT}/auth/verifyEmail/${email}/${accessToken}`;
transporter.sendMail(mailOptions, ()=>{});
return res.status(httpStatus.CREATED).json({
user: user,
accessToken: accessToken
Expand Down Expand Up @@ -93,17 +120,48 @@ const forgotPassword = async (req: Request, res: Response, next: NextFunction) =
message: "User doesn't exist with this email"
})
}
const secret = <string>process.env.JWT_SECRET + user._id;
const secret = <string>process.env.JWT_SECRET + user.email;
const resetToken = jwt.sign(user.toJSON(), secret, { expiresIn: '10m' })

return res.status(httpStatus.OK).json({
resetToken: resetToken,
link: `http://localhost:${process.env.PORT}/auth/resetPassword/${user._id}/${resetToken}`,
link: `http://localhost:${process.env.PORT}/auth/:${user.email}/resetPassword/:${resetToken}`,
});
}
catch (err) {
return next(err);
}
}

export { signup, login, resetPassword, forgotPassword };
//write a function to verify email
const verifyEmail = async (req: Request, res: Response, next : NextFunction) => {
try {
const { id, verifyToken } = req.params;
console.log(id, verifyToken);
const user = await UserModel.UserSchema.findOne({ email : id });

if (!user) {
return res.status(httpStatus.NOT_FOUND).json({
message: "User not found. Please try again!"
})
}
const secret = <string>process.env.JWT_SECRET;
const payload = jwt.verify(verifyToken, secret);
if (!payload) {
return res.status(httpStatus.FORBIDDEN).json({
message: "Incorrect token received"
})
}
user.verified = true;
await user.save();
return res.status(httpStatus.OK).json({
user: user,
message: "Email verified successfully"
})
}
catch (err) {
return next(err);
}
}

export { signup, login, resetPassword, forgotPassword, verifyEmail};
1 change: 1 addition & 0 deletions models/userModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const userSchema = new Schema({
email: { type: "string", required: true },
password: { type: "string", required: true },
dob: { type: Date},
verified: { type: Boolean, default: false },
});

userSchema.pre('save', async function (next) {
Expand Down
Loading