Skip to content

Commit

Permalink
Merge pull request #272 from Abhigaba/master
Browse files Browse the repository at this point in the history
Adding LogIn via OTP #151 (Backend Schema and routes)
  • Loading branch information
PRathod27 authored Oct 27, 2024
2 parents 6cc8f28 + 6416f04 commit aa9e798
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 3 deletions.
64 changes: 63 additions & 1 deletion backend/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const {Otpdata} = require("../models/otpModel.js")
const userModel = require("../models/userModel.js");
const JWT = require('jsonwebtoken');
const { comparePassword, hashPassword } = require("../helpers/authHelper.js");
const nodemailer = require("nodemailer")


const registerController = async (req, res) => {
Expand Down Expand Up @@ -115,6 +117,48 @@ const { comparePassword, hashPassword } = require("../helpers/authHelper.js");
};

//test controller

const otpController = async (req,res) => {

const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: process.env.email,
clientId: process.env.OAUTH_CLIENTID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
refreshToken: process.env.OAUTH_REFRESH_TOKEN
}
});
const { email} = req.body;
try {
const user = await userModel.findOne({ email });
const existing_user_otp = await Otpdata.findOne({email})

if (!user) {
return res.status(401).json({ message: 'User not registered' });
}

const otp = Math.floor(100000 + Math.random() * 900000);
const mailOptions = {
from: `"Electrokart" ${process.env.email}`,
to: email, // list of receivers
subject: 'Electrokart Login OTP',
text: `Your OTP to login to Electrokart is: ${otp}`,
};

if (existing_user_otp) {
await Otpdata.deleteOne({ email });
}
let info = await transporter.sendMail(mailOptions);
console.log('Email sent: ' + info.response);
const newotp = await Otpdata.create({otp:otp, email:email})
res.status(201).json({ message: 'Otp successfully sended', newotp });
} catch (error) {
res.status(500).json({ error: error.message });
}
}

const testController = (req, res) => {
try {
res.send("Protected Route");
Expand All @@ -124,6 +168,22 @@ const { comparePassword, hashPassword } = require("../helpers/authHelper.js");
}
};

const otpVerifyController = async (req, res) => {
const { otp, email } = req.body;
try {
const user = await Otpdata.findOne({otp});
const Userid = await userModel.findOne({email});
if (!user || user.email !== email ) {
return res.status(401).json({ message: 'Invalid OTP' });
}

const token = JWT.sign({ id: Userid._id }, `${process.env.JWT_SECRET}`, { expiresIn: '1h' });
await Otpdata.deleteOne({ otp });
res.status(201).json({ message: 'Otp successfully verified', token });
} catch (error) {
res.status(500).json({ error: error.message });
}
}

//forgotPasswordController
const forgotPasswordController = async (req, res) => {
Expand Down Expand Up @@ -200,5 +260,7 @@ const { comparePassword, hashPassword } = require("../helpers/authHelper.js");
loginController,
testController,
forgotPasswordController,
updateProfileController
updateProfileController,
otpController,
otpVerifyController,
};
14 changes: 14 additions & 0 deletions backend/helpers/authHelper.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const nodemailer = require('nodemailer')
const bcrypt = require("bcrypt");

const hashPassword = async (password) => {
Expand All @@ -10,6 +11,18 @@ const hashPassword = async (password) => {
}
};

const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: process.env.email,
pass: process.env.password,
clientId: process.env.OAUTH_CLIENTID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
refreshToken: process.env.OAUTH_REFRESH_TOKEN
}
});

const comparePassword = async (password, hashedPassword) => {
return bcrypt.compare(password, hashedPassword);
};
Expand All @@ -18,4 +31,5 @@ const comparePassword = async (password, hashedPassword) => {
module.exports = {
hashPassword,
comparePassword,
transporter
};
14 changes: 14 additions & 0 deletions backend/models/otpModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose = require('mongoose')

const otpSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
otp: { type: String, required: true },
createdAt: {
type: Date,
default: Date.now,
expires: 600 // 600 seconds = 10 minutes
}
});

const Otpdata = mongoose.model('otp', otpSchema) ;
module.exports = {Otpdata}
11 changes: 10 additions & 1 deletion backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"dotenv": "^16.4.5",
"express": "^4.21.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.7.0"
"mongoose": "^8.7.0",
"nodemailer": "^6.9.15"
},
"devDependencies": {
"nodemon": "^3.1.7"
Expand Down
7 changes: 7 additions & 0 deletions backend/routes/authRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const {
testController,
forgotPasswordController,
updateProfileController,
otpController,
otpVerifyController,
} = require("../controllers/authController.js");

const { requireSignIn, isAdmin } = require("../middlewares/authMiddleware.js");
Expand All @@ -20,6 +22,11 @@ authRouter.post("/auth/register", registerController);
//LOGIN || POST
authRouter.post("/auth/login", loginController);

//LOGIN || OTP || POST
authRouter.post("/auth/login/otp", otpController);

//LOGIN || OTP || Verify || POST
authRouter.post("/auth/login/otp/verify", otpVerifyController);
//test routes
authRouter.get("/test", requireSignIn, isAdmin, testController);

Expand Down

0 comments on commit aa9e798

Please sign in to comment.