Skip to content

Commit b01b0b2

Browse files
author
Shivam Tiwari
committed
created an schema for the otp store and made the required changes to store the otp into the db
1 parent 890c40d commit b01b0b2

File tree

2 files changed

+26
-14
lines changed

2 files changed

+26
-14
lines changed

controller/auth.js

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1+
import OTPStore from "/models/OTPStore";
12
import util, {logger} from "#util";
23
import { authenticateUser, userExists, updatePassword } from "#services/user";
34

4-
const otpStore = {};
5-
65
async function login(req, res) {
76
const { id, password } = req.body;
87
try {
@@ -36,7 +35,7 @@ async function sendOTP(req, res) {
3635
const { uid, emailId } = req.body;
3736
if (await userExists(uid, emailId)) {
3837
const otp = Math.floor(1000 + Math.random() * 9000);
39-
otpStore[uid] = otp;
38+
await OTPStore.findOneAndUpdate({ uid }, { otp: otp }, { upsert: true });
4039
util.sendOTP(emailId, otp);
4140
res.json({ res: "otp sent to emailID" });
4241
} else {
@@ -46,20 +45,23 @@ async function sendOTP(req, res) {
4645

4746
async function resetPassword(req, res) {
4847
const { uid, otp, password } = req.body;
49-
if (otpStore[uid] === otp) {
50-
try {
51-
await updatePassword(uid, password);
52-
res.json({ res: "successfully updated password" });
53-
} catch (error) {
54-
logger.log("Error while updating", error)
55-
res.status(500);
56-
if (error.name === "UpdateError") res.json({ err: "Something went wrong while updating password" });
57-
else res.json({ err: "something went wrong" });
48+
try{
49+
const otpData=await OTPStore.find({uid});
50+
if(otpData.otp ===otp ){
51+
await updatePassword(uid,password)
52+
res.json({res:"successfully updated password"})
5853
}
59-
} else {
60-
res.json({ err: "incorrect otp" });
54+
else {
55+
res.json({ err: "Incorrect OTP" });
56+
}
57+
58+
}
59+
catch(error){
60+
console.log(error)
61+
res.json({res:"Something is wrong"})
6162
}
6263
}
64+
6365

6466
export default {
6567
validateUser, sendOTP, resetPassword, login,

models/otpStore.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import connector from "#models/databaseUtil";
2+
const {Schema}=connector;
3+
4+
const otpStoreSchema=new Schema({
5+
otpID:{type:String,unique:true,required:true},
6+
otp:{type:String,required:true,unique:true}
7+
})
8+
9+
const OTPStore=connector.model("OTPStore",otpStoreSchema)
10+

0 commit comments

Comments
 (0)