@@ -46,4 +46,71 @@ router.get('/me', async (req, res) => {
46
46
}
47
47
} )
48
48
49
- module . exports = router
49
+ router . post ( '/forgot-password' , async ( req , res ) => {
50
+ try {
51
+ const { email } = req . body ;
52
+ const user = await User . findOne ( { email } ) ;
53
+ if ( ! user ) return res . status ( 400 ) . json ( { message : 'User not found' } ) ;
54
+
55
+ // Generate a password reset token (JWT)
56
+ const token = jwt . sign ( { id : user . _id } , process . env . JWT_SECRET , { expiresIn : '1h' } ) ;
57
+
58
+ // Create reset link
59
+ const resetLink = `${ process . env . FRONTEND_URL || 'http://localhost:5000' } /reset-password.html?token=${ token } ` ;
60
+
61
+ // Log the reset link for testing (in production, you would send an email)
62
+ console . log ( 'Password reset link:' , resetLink ) ;
63
+ console . log ( 'For email:' , email ) ;
64
+
65
+ // Basic email sending simulation
66
+ // In a real application, you would use a service like Nodemailer, SendGrid, etc.
67
+ // Example with Nodemailer (commented out):
68
+ /*
69
+ const nodemailer = require('nodemailer');
70
+ const transporter = nodemailer.createTransport({
71
+ service: 'gmail',
72
+ auth: {
73
+ user: process.env.EMAIL_USER,
74
+ pass: process.env.EMAIL_PASS
75
+ }
76
+ });
77
+
78
+ await transporter.sendMail({
79
+ from: process.env.EMAIL_USER,
80
+ to: email,
81
+ subject: 'Password Reset Request',
82
+ html: `<p>Click the link below to reset your password:</p>
83
+ <a href="${resetLink}">${resetLink}</a>
84
+ <p>This link will expire in 1 hour.</p>`
85
+ });
86
+ */
87
+
88
+ res . status ( 200 ) . json ( {
89
+ message : 'Password reset link sent to your email' ,
90
+ // For testing purposes, include the reset link in the response
91
+ resetLink : process . env . NODE_ENV === 'development' ? resetLink : undefined
92
+ } ) ;
93
+ } catch ( err ) {
94
+ console . error ( 'Forgot password error:' , err ) ;
95
+ res . status ( 500 ) . json ( { message : 'Server error' } ) ;
96
+ }
97
+ } ) ;
98
+
99
+ router . post ( '/reset-password' , async ( req , res ) => {
100
+ try {
101
+ const { token, password } = req . body ;
102
+ const payload = jwt . verify ( token , process . env . JWT_SECRET ) ;
103
+ const user = await User . findById ( payload . id ) ;
104
+ if ( ! user ) return res . status ( 400 ) . json ( { message : 'Invalid token' } ) ;
105
+
106
+ const hashed = await bcrypt . hash ( password , 10 ) ;
107
+ user . password = hashed ;
108
+ await user . save ( ) ;
109
+
110
+ res . status ( 200 ) . json ( { message : 'Password has been reset successfully' } ) ;
111
+ } catch ( err ) {
112
+ res . status ( 500 ) . json ( { message : 'Server error' } ) ;
113
+ }
114
+ } ) ;
115
+
116
+ module . exports = router
0 commit comments