diff --git a/controller/auth.js b/controller/auth.js index a5281a2..d38860f 100644 --- a/controller/auth.js +++ b/controller/auth.js @@ -1,8 +1,7 @@ +import OTPStore from "#models/otpStore"; import util, {logger} from "#util"; import { authenticateUser, userExists, updatePassword } from "#services/user"; -const otpStore = {}; - async function login(req, res) { const { id, password } = req.body; try { @@ -36,7 +35,7 @@ async function sendOTP(req, res) { const { uid, emailId } = req.body; if (await userExists(uid, emailId)) { const otp = Math.floor(1000 + Math.random() * 9000); - otpStore[uid] = otp; + await OTPStore.update({uid: uid}, {otp: otp}); util.sendOTP(emailId, otp); res.json({ res: "otp sent to emailID" }); } else { @@ -46,7 +45,8 @@ async function sendOTP(req, res) { async function resetPassword(req, res) { const { uid, otp, password } = req.body; - if (otpStore[uid] === otp) { + const storedOtp = await OTPStore.read({uid: uid}); + if (storedOtp[0].otp === `${otp}`) { try { await updatePassword(uid, password); res.json({ res: "successfully updated password" }); @@ -60,6 +60,7 @@ async function resetPassword(req, res) { res.json({ err: "incorrect otp" }); } } + export default { validateUser, sendOTP, resetPassword, login, diff --git a/models/otpStore.js b/models/otpStore.js new file mode 100644 index 0000000..45648b8 --- /dev/null +++ b/models/otpStore.js @@ -0,0 +1,38 @@ +import connector from "#models/databaseUtil"; + +const otpStoreSchema = { + uid: { type: String, unique: true, required: true }, + otp: { type: String, unique: true, required: true } +} + +const OTPStore = connector.model("OTPStore", otpStoreSchema) + +async function remove(filter) { + const res = await OTPStore.findOneAndDelete(filter); + return res; +} + +async function create(uid, otp) { + const otpStore = new OTPStore({ + uid, + otp + }); + const otpDoc = await otpStore.save(); + return otpDoc; +} + +async function read(filter, limit = 1) { + const otpData = await OTPStore.find(filter).limit(limit); + return otpData; +} + +async function update(filter, updateObject) { + const otpDoc = await OTPStore.findOneAndUpdate(filter, updateObject, { upsert: true, new: true }); + return otpDoc; +} + + +export default { + create, read, update, remove, +}; +