Skip to content

Commit 4daa526

Browse files
committed
Refactor server startup logic and enhance password reset functionality
- Removed debug endpoints from the server configuration for cleaner code. - Introduced a helper function to attempt starting the server on an available port, improving error handling for port conflicts. - Updated the ResetPasswordModal component to use JWT for authentication, enhancing security and error handling during password reset operations.
1 parent ad9a333 commit 4daa526

2 files changed

Lines changed: 60 additions & 17 deletions

File tree

server/dev.js

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,6 @@ mountServerlessFunction('/api/enumerators-stats', path.join(__dirname, '../api/e
9191
mountServerlessFunction('/api/admin/sync-users', path.join(__dirname, '../api/admin/sync-users.js'));
9292
mountServerlessFunction('/api/admin/refresh-enumerator-stats', path.join(__dirname, '../api/admin/refresh-enumerator-stats.js'));
9393

94-
// Debug endpoints
95-
mountServerlessFunction('/api/debug/survey-collections', path.join(__dirname, '../api/debug/survey-collections.js'));
96-
9794
console.log('\n✅ All endpoints mounted successfully!\n');
9895

9996
// Health check endpoint
@@ -168,6 +165,35 @@ app.use((err, req, res, next) => {
168165
});
169166
});
170167

168+
// Helper function to try starting server on a port
169+
function tryStartServer(port, originalPort = port, maxAttempts = 10) {
170+
return new Promise((resolve, reject) => {
171+
const server = app.listen(port, () => {
172+
console.log(`🚀 Development server running on port ${port}`);
173+
console.log(` http://localhost:${port}`);
174+
console.log(`\nBackend ready! Start the frontend with: npm run dev:frontend\n`);
175+
resolve(server);
176+
});
177+
178+
server.on('error', (error) => {
179+
if (error.code === 'EADDRINUSE') {
180+
server.close();
181+
if (maxAttempts > 0) {
182+
console.log(`Port ${port} is in use, trying port ${port + 1}...`);
183+
tryStartServer(port + 1, originalPort, maxAttempts - 1)
184+
.then(resolve)
185+
.catch(reject);
186+
} else {
187+
reject(new Error(`Could not find an available port starting from ${originalPort}`));
188+
}
189+
} else {
190+
server.close();
191+
reject(error);
192+
}
193+
});
194+
});
195+
}
196+
171197
// Start server with MongoDB connection validation
172198
async function startServer() {
173199
try {
@@ -176,16 +202,15 @@ async function startServer() {
176202
const { db } = await connectToDatabase();
177203
console.log(`✓ MongoDB connected: ${db.databaseName}\n`);
178204

179-
app.listen(PORT, () => {
180-
console.log(`🚀 Development server running on port ${PORT}`);
181-
console.log(` http://localhost:${PORT}`);
182-
console.log(`\nBackend ready! Start the frontend with: npm run dev:frontend\n`);
183-
});
205+
// Try to start server on the specified port, or find an available port
206+
await tryStartServer(PORT);
184207
} catch (error) {
185208
console.error('❌ Failed to start server:', error.message);
186-
console.error('\nPlease check your MongoDB connection settings:');
187-
console.error(' - MONGODB_VALIDATION_URI in .env file');
188-
console.error(' - MONGODB_VALIDATION_DB in .env file');
209+
if (error.message.includes('MongoDB') || error.message.includes('MONGODB')) {
210+
console.error('\nPlease check your MongoDB connection settings:');
211+
console.error(' - MONGODB_VALIDATION_URI in .env file');
212+
console.error(' - MONGODB_VALIDATION_DB in .env file');
213+
}
189214
console.error(`\nError details: ${error.stack}`);
190215
process.exit(1);
191216
}

src/components/Admin/ResetPasswordModal.tsx

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,31 +33,49 @@ const ResetPasswordModal: React.FC<ResetPasswordModalProps> = ({ user, onClose,
3333
setIsSubmitting(true);
3434

3535
try {
36-
// Get auth token from localStorage
37-
const userStr = localStorage.getItem('user');
38-
const currentUser = userStr ? JSON.parse(userStr) : null;
36+
// Get JWT token from localStorage
37+
const token = localStorage.getItem('authToken');
38+
39+
if (!token) {
40+
setError('Authentication token not found. Please log in again.');
41+
setIsSubmitting(false);
42+
return;
43+
}
3944

4045
const API_BASE_URL = getApiBaseUrl();
4146
const response = await fetch(`${API_BASE_URL}/users/${user._id}/reset-password`, {
4247
method: 'PATCH',
4348
headers: {
4449
'Content-Type': 'application/json',
45-
'Authorization': `Bearer ${currentUser?.username || ''}`,
50+
'Authorization': `Bearer ${token}`,
4651
},
4752
body: JSON.stringify({ newPassword }),
4853
});
4954

55+
if (!response.ok) {
56+
const errorData = await response.json().catch(() => ({ message: 'Failed to reset password' }));
57+
if (response.status === 401) {
58+
setError('Authentication failed. Please log in again.');
59+
} else if (response.status === 403) {
60+
setError('You do not have permission to reset passwords.');
61+
} else {
62+
setError(errorData.message || errorData.error || 'Failed to reset password');
63+
}
64+
return;
65+
}
66+
5067
const result = await response.json();
5168

5269
if (result.success) {
5370
alert(`Password reset successfully for ${user.username}`);
5471
onSuccess();
5572
onClose();
5673
} else {
57-
setError(result.message);
74+
setError(result.message || 'Failed to reset password');
5875
}
5976
} catch (err) {
60-
setError('An unexpected error occurred');
77+
console.error('Reset password error:', err);
78+
setError('An unexpected error occurred. Please try again.');
6179
} finally {
6280
setIsSubmitting(false);
6381
}

0 commit comments

Comments
 (0)