/
userControllers.js
93 lines (83 loc) · 2.72 KB
/
userControllers.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const User = require('../models/user.model');
const nodemailer = require('nodemailer');
//you can use the registerUser controller and getUsers controller to test the API endpoints in Postman since they are not connected to the client
exports.registerUser = async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.create({ email, password });
res.status(201).send({ message: 'User registered successfully' });
} catch (error) {
console.log(error);
res.status(500).send({ message: 'An error occurred while registering the user' });
}
};
exports.getUsers = async (req, res) => {
try {
const users = await User.find({});
res.json(users);
} catch (error) {
console.log(error);
res.status(500).send({ message: 'An error occurred while fetching users' });
}
};
// verify the email exist
exports.checkEmail = async (req, res) => {
const email = req.query.email;
try {
const user = await User.findOne({ email });
if (user) {
res.status(200).send({ message: 'Email exists in the database' });
} else {
res.status(404).send({ message: 'Email does not exist in the database' });
}
} catch (error) {
console.error(error);
res.status(500).send({ message: 'An error occurred while checking the email' });
}
};
exports.updatePassword = async (req, res) => {
const { email, newPassword } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
user.password = newPassword;
await user.save();
res.status(200).json({ message: 'Password updated successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'An error occurred while updating the password' });
}
};
exports.sendEmail = (req, res) => {
const transporter = nodemailer.createTransport({
service: 'gmail',
secure: true,
auth: {
user: process.env.MY_EMAIL,
pass: process.env.APP_PASSWORD,
},
});
const { recipient_email, OTP } = req.body;
const mailOptions = {
from: process.env.MY_EMAIL,
to: recipient_email,
subject: 'PASSWORD RESET',
html: `<html>
<body>
<h2>Password Recovery</h2>
<p>Use this OTP to reset your password. OTP is valid for 1 minute</p>
<h3>${OTP}</h3>
</body>
</html>`,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
res.status(500).send({ message: "An error occurred while sending the email" });
} else {
console.log('Email sent: ' + info.response);
res.status(200).send({ message: "Email sent successfully" });
}
});};