-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
241 lines (206 loc) · 6.21 KB
/
index.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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Import required modules
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require('path');
// Initialize the app
const app = express();
// Middleware setup
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
// Session middleware for authentication
app.use(
session({
secret: 'your_secret_key', // Replace with a strong secret in production
resave: false,
saveUninitialized: true,
})
);
// Middleware to pass user session info to views
app.use((req, res, next) => {
res.locals.userType = req.session.userType;
res.locals.userId = req.session.userId;
next();
});
// Connect to MongoDB
mongoose
.connect('mongodb://127.0.0.1:27017/appointmentDB')
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('MongoDB connection error:', err));
// Define Schemas and Models
const userSchema = new mongoose.Schema({
name: String,
email: { type: String, unique: true },
password: String,
userType: { type: String, enum: ['user', 'doctor'], required: true },
});
const appointmentSchema = new mongoose.Schema({
name: String,
email: String,
phone: String,
date: String,
time: String,
status: { type: String, default: 'Pending' },
});
const User = mongoose.model('User', userSchema);
const Appointment = mongoose.model('Appointment', appointmentSchema);
// Routes
// Home Page
app.get('/', (req, res) => {
res.render('home');
});
// Login Page
app.get('/login', (req, res) => {
res.render('login');
});
// Login Handler
app.post('/login', async (req, res) => {
const { email, password, userType } = req.body;
try {
const user = await User.findOne({ email, userType });
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(400).send('Invalid credentials');
}
// Save session data
req.session.userId = user._id;
req.session.userType = user.userType;
// Redirect based on user type
if (user.userType === 'doctor') {
return res.redirect('/dashboard');
}
res.redirect('/');
} catch (err) {
console.error('Login error:', err);
res.status(500).send('Internal Server Error');
}
});
// Sign Up Page
app.get('/signup', (req, res) => {
res.render('signup');
});
// Sign Up Handler
app.post('/signup', async (req, res) => {
const { name, email, password, confirmPassword, userType } = req.body;
if (password !== confirmPassword) {
return res.status(400).send('Passwords do not match');
}
try {
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ name, email, password: hashedPassword, userType });
await newUser.save();
res.redirect('/login');
} catch (err) {
if (err.code === 11000) {
return res.status(400).send('Email is already registered');
}
console.error('Sign Up error:', err);
res.status(500).send('Internal Server Error');
}
});
app.get('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).send('Error logging out');
}
// Render the logout success page
res.render('logout-success');
});
});
// Doctor Dashboard
app.get('/dashboard', async (req, res) => {
if (req.session.userType !== 'doctor') {
return res.status(403).send('Access Denied');
}
try {
const appointments = await Appointment.find();
res.render('dashboard', { appointments });
} catch (err) {
console.error('Dashboard error:', err);
res.status(500).send('Internal Server Error');
}
});
// User Dashboard
app.get('/user-dashboard', async (req, res) => {
if (req.session.userType !== 'user') {
return res.status(403).send('Access Denied');
}
try {
const appointments = await Appointment.find({ email: req.session.userId });
res.render('user-dashboard', { appointments });
} catch (err) {
console.error('User Dashboard error:', err);
res.status(500).send('Internal Server Error');
}
});
// Appointment Booking
app.post('/book', async (req, res) => {
const { name, email, phone, date, time } = req.body;
try {
const newAppointment = new Appointment({ name, email, phone, date, time });
await newAppointment.save();
res.redirect('/success');
} catch (err) {
console.error('Booking error:', err);
res.status(500).send('Internal Server Error');
}
});
// Appointment Status
app.get('/status', (req, res) => {
res.render('status', { appointment: null, message: null });
});
app.post('/status', async (req, res) => {
const { phone } = req.body;
try {
const appointment = await Appointment.findOne({ phone });
if (appointment) {
return res.render('status', { appointment, message: null });
}
res.render('status', { appointment: null, message: 'No appointment found' });
} catch (err) {
console.error('Status error:', err);
res.status(500).send('Internal Server Error');
}
});
// Success Page
app.get('/success', (req, res) => {
res.render('success');
});
// Confirm appointment
app.post('/confirm/:id', async (req, res) => {
const { id } = req.params;
try {
await Appointment.findByIdAndUpdate(id, { status: 'Confirmed' });
res.redirect('/dashboard');
} catch (err) {
console.error('Error confirming appointment:', err);
res.status(500).send('Internal Server Error');
}
});
// Cancel appointment
app.post('/cancel/:id', async (req, res) => {
const { id } = req.params;
try {
await Appointment.findByIdAndUpdate(id, { status: 'Canceled' });
res.redirect('/dashboard');
} catch (err) {
console.error('Error canceling appointment:', err);
res.status(500).send('Internal Server Error');
}
});
// Delete appointment
app.post('/delete/:id', async (req, res) => {
const { id } = req.params;
try {
await Appointment.findByIdAndDelete(id);
res.redirect('/dashboard');
} catch (err) {
console.error('Error deleting appointment:', err);
res.status(500).send('Internal Server Error');
}
});
// Start Server
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));