Skip to content

Commit 044cc1a

Browse files
authored
Merge pull request #98 from tcet-opensource/29_Otp_Store
29 otp store
2 parents ae11309 + 112bdf7 commit 044cc1a

File tree

2 files changed

+43
-4
lines changed

2 files changed

+43
-4
lines changed

controller/auth.js

Lines changed: 5 additions & 4 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.update({uid: uid}, {otp: otp});
4039
util.sendOTP(emailId, otp);
4140
res.json({ res: "otp sent to emailID" });
4241
} else {
@@ -46,7 +45,8 @@ async function sendOTP(req, res) {
4645

4746
async function resetPassword(req, res) {
4847
const { uid, otp, password } = req.body;
49-
if (otpStore[uid] === otp) {
48+
const storedOtp = await OTPStore.read({uid: uid});
49+
if (storedOtp[0].otp === `${otp}`) {
5050
try {
5151
await updatePassword(uid, password);
5252
res.json({ res: "successfully updated password" });
@@ -60,6 +60,7 @@ async function resetPassword(req, res) {
6060
res.json({ err: "incorrect otp" });
6161
}
6262
}
63+
6364

6465
export default {
6566
validateUser, sendOTP, resetPassword, login,

models/otpStore.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import connector from "#models/databaseUtil";
2+
3+
const otpStoreSchema = {
4+
uid: { type: String, unique: true, required: true },
5+
otp: { type: String, unique: true, required: true }
6+
}
7+
8+
const OTPStore = connector.model("OTPStore", otpStoreSchema)
9+
10+
async function remove(filter) {
11+
const res = await OTPStore.findOneAndDelete(filter);
12+
return res;
13+
}
14+
15+
async function create(uid, otp) {
16+
const otpStore = new OTPStore({
17+
uid,
18+
otp
19+
});
20+
const otpDoc = await otpStore.save();
21+
return otpDoc;
22+
}
23+
24+
async function read(filter, limit = 1) {
25+
const otpData = await OTPStore.find(filter).limit(limit);
26+
return otpData;
27+
}
28+
29+
async function update(filter, updateObject) {
30+
const otpDoc = await OTPStore.findOneAndUpdate(filter, updateObject, { upsert: true, new: true });
31+
return otpDoc;
32+
}
33+
34+
35+
export default {
36+
create, read, update, remove,
37+
};
38+

0 commit comments

Comments
 (0)