Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
147 lines (122 loc) · 3.72 KB
/
Copy pathapp.js
File metadata and controls
147 lines (122 loc) · 3.72 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const dotenv = require('dotenv');
const authRoutes = require('./routes/authRoutes');
const path = require('path');
// Load environment variables from .env
dotenv.config();
// Initialize Express
const app = express();
// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Static Files
app.use(express.static(path.join(__dirname, 'public')));
// View Engine
app.set('view engine', 'ejs');
// Session Management
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: process.env.MONGO_URI })
})
);
// Routes
app.use(authRoutes);
// Forgot Password Route
app.get('/forgot-password', (req, res) => {
res.render('forgot-password'); // Render the forgot-password.ejs view
});
app.get('/logout', (req, res) => {
req.logout((err) => {
if (err) {
return res.status(500).send("Error logging out");
}
// Redirect to login page after logout
res.redirect('/login'); // Change the URL to your login page
});
});
// Handle sending OTP
app.post('/forgot-password', async (req, res) => {
try {
const { email } = req.body;
const otp = Math.floor(100000 + Math.random() * 900000).toString(); // Generate a 6-digit OTP
const otpExpiry = Date.now() + 3600000; // OTP expires in 1 hour
// Find the user and update OTP and OTP expiry
const user = await User.findOneAndUpdate(
{ email },
{ otp, otpExpiry },
{ new: true }
);
if (!user) {
console.error('User not found:', email);
return res.status(404).send('User not found');
}
// Send OTP via email
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.EMAIL_PASSWORD
}
});
const mailOptions = {
from: process.env.EMAIL,
to: email,
subject: 'Your OTP for Password Reset',
text: `Your OTP is ${otp}`
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending OTP:', error);
return res.status(500).send('Error sending OTP');
}
console.log('OTP sent:', info.response);
res.send('OTP sent to your email');
});
} catch (error) {
console.error('Error in /forgot-password:', error);
res.status(500).send('An error occurred');
}
});
// Handle OTP verification and password reset
app.post('/verify-otp', async (req, res) => {
try {
const { otp, 'new-password': newPassword } = req.body;
const user = await User.findOne({ email: req.session.email });
if (!user || user.otp !== otp || user.otpExpiry < Date.now()) {
return res.status(400).send('Invalid or expired OTP');
}
// Hash the new password before saving
user.password = await bcrypt.hash(newPassword, 10);
// Clear OTP fields
user.otp = undefined;
user.otpExpiry = undefined;
await user.save();
res.redirect('/login'); // Redirect to login page after successful reset
} catch (error) {
console.error('Error in /verify-otp:', error);
res.status(500).send('An error occurred');
}
});
// Connect to MongoDB
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Connected to MongoDB');
})
.catch(err => {
console.error('Error connecting to MongoDB:', err);
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});