-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsendOtpEmail.js
66 lines (54 loc) · 1.49 KB
/
sendOtpEmail.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const fs = require("fs");
const crypto = require("crypto");
const sgMail = require("@sendgrid/mail");
require("dotenv").config();
const MAX_RESETS = 5;
const sendOtpEmail = async (email) => {
// generate otp
const otp = Math.floor(100000 + Math.random() * 900000);
const users = JSON.parse(fs.readFileSync("./data.json", "utf8"));
const user = users.find((user) => user.email === email);
if (user && user.resets >= MAX_RESETS) {
throw new Error("Maximum resets reached");
}
if (!user) {
// generate token
const token = crypto.randomBytes(20).toString("hex");
const newUser = {
id: crypto.randomBytes(20).toString("hex"),
email,
otp,
createdDate: new Date(),
resetDate: new Date(),
token,
ip: "",
port: "",
resets: 0,
};
users.push(newUser);
fs.writeFileSync("./data.json", JSON.stringify(users));
} else {
user.otp = otp;
user.resetDate = new Date();
user.resets = user.resets + 1;
fs.writeFileSync("./data.json", JSON.stringify(users));
}
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: email,
from: process.env.SENDER_EMAIL,
subject: "OTP for login",
text: `Your OTP is ${otp}`,
html: `<strong>Your OTP is ${otp}</strong>`,
};
try {
if (process.env.NODE_ENV === "development") {
console.log(msg);
} else {
await sgMail.send(msg);
}
} catch (e) {
throw new Error("Error sending email");
}
};
module.exports = sendOtpEmail;