-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuser.js
64 lines (53 loc) · 1.62 KB
/
user.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
import client from '../../src/db';
import {generateOTP} from '../../src/myFunctions';
import sendEmail from '../../src/sendEmail';
async function user(req, res) {
if (req.method === 'POST') {
const {name, email} = req.body;
if (!name || !email) {
return res.status(400).json({message: 'Name and email are required.'});
}
try {
await client.connect();
const usersCollection = client.db('ivrStudio').collection('users');
const existingUser = await usersCollection.findOne({
email,
isEmailVerified: true,
});
if (existingUser) {
return res.status(409).json({message: 'Email already registered.'});
}
const OTP = generateOTP();
const filter = {email};
const update = {
$set: {
name,
email,
timestamp: Date.now(),
otp: OTP,
isEmailVerified: false,
},
};
const options = {upsert: true};
const result = await usersCollection.updateOne(filter, update, options);
const success = await sendEmail(
email,
'Email Verification OTP',
`Your OTP is: ${OTP}`
);
if (success) {
return res.status(200).json({message: 'OTP successfully sent.'});
} else {
return res.status(500).json({message: 'Error, OTP could not be sent.'});
}
} catch (error) {
console.error(error);
return res.status(500).json({message: 'Internal Server Error.'});
} finally {
await client.close();
}
} else {
return res.status(405).json({message: 'Method not allowed.'});
}
}
export default user;