-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
267 lines (219 loc) · 8.53 KB
/
server.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
const express = require('express');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const multer = require('multer');
const xlsx = require('xlsx');
const path = require('path');
const bodyParser = require('body-parser'); // Import body-parser
const session = require('express-session');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const bcrypt = require('bcrypt');
// Generate a 256-bit (32-byte) random secret key
const secretKey = crypto.randomBytes(32).toString('hex');
const app = express();
const port = process.env.PORT || 3001;
app.set('view engine', 'ejs'); // Set EJS as the view engine
app.set('views', path.join(__dirname, 'views')); // Set the views directory
// Define storage for the uploaded Excel file
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.use(
session({
secret: secretKey, // Store the secret key as an environment variable
resave: false,
saveUninitialized: true,
cookie: {
secure: true, // Set to true in a production environment with HTTPS
},
})
);
// Serve static files from the "public" folder
app.use(express.static('public'));
// Serve the HTML form
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'landing.html'));
});
// Serve the register.html page
app.get('/register', (req, res) => {
res.sendFile(path.join(__dirname, 'public', '/auth/institution/register.html'));
});
// Serve the login.html page
app.get('/login/learner', (req, res) => {
res.sendFile(path.join(__dirname, 'public', '/auth/learner/index.html'));
});
// Serve CSS files with the correct MIME type
app.get('/login/learner.css', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'login', 'learner.css'), {
headers: {
'Content-Type': 'text/css', // Set the correct MIME type for CSS
},
});
});
app.get('/login/institution', (req, res) => {
res.sendFile(path.join(__dirname, 'public', '/auth/institution/login.html'));
});
// Server-side code
app.get('/search', async (req, res) => {
let learners = []; // Define learners as an empty array
try {
const name = req.query.name; // Get the name from the query parameter
// Query the database for a learner with the provided name
learner = await prisma.userProfile.findMany({
where: {
Name: {
contains: name,
},
},
});
// Render a view or send JSON response with the learners
res.render('learners', { learners });
} catch (error) {
console.error('Error searching for learners:', error.message);
res.status(500).send('An error occurred while searching for learners.');
}
});
app.use(bodyParser.urlencoded({ extended: true }));
// Serve CSS files with the correct MIME type
app.get('/login/styles.css', (req, res) => {
res.sendFile(path.join(__dirname, 'public', '/auth/institution/styles.css'), {
headers: {
'Content-Type': 'text/css', // Set the correct MIME type for CSS
},
});
});
// Add body-parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// Handle file upload
app.post('/upload', upload.single('file'), async (req, res) => {
try {
if (!req.file || !req.file.buffer) {
return res.status(400).send('No file uploaded.');
}
const buffer = req.file.buffer;
const workbook = xlsx.read(buffer, { type: 'buffer' });
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
if (!worksheet) {
return res.status(400).send('No worksheet found in the Excel file.');
}
const rows = xlsx.utils.sheet_to_json(worksheet);
await prisma.$transaction(async (prisma) => {
for (let i = 0; i < rows.length; i++) {
const { Name, learnerEmail, Program } = rows[i];
console.log(`Row ${i + 2} - Name: ${Name}, learnerEmail: ${learnerEmail}, Program: ${Program},`);
if (Name && learnerEmail && Program) {
await prisma.userProfile.create({
data: {
Name,
learnerEmail,
Program,
},
});
} else {
console.log(`Skipping row ${i + 2} due to missing data.`);
}
}
});
console.log('Data imported successfully');
return res.status(200).send('File uploaded and data imported successfully.');
} catch (error) {
console.error('Error uploading and importing data:', error.message);
return res.status(500).send('An error occurred during upload and data import.');
}
});
app.post('/register', async (req, res) => {
try {
const { institutionName, institutionEmail, Programs, Facilitator, Username, Password, confirmPassword } = req.body;
console.log('Request Body:', req.body);
if (!institutionName || !institutionEmail || !Programs || !Facilitator || !Username || !Password || !confirmPassword) {
console.log('Missing fields:', { institutionEmail, Programs, Facilitator, Username, Password }); // Debug statement
return res.status(400).send('Missing data.');
}
// Check if the password and confirmPassword match
if (Password !== confirmPassword) {
return res.status(400).send('Passwords do not match.');
}
// Hash the password using bcrypt
const hashedPassword = await bcrypt.hash(Password, 10);
// Create a new institution profile in the database
try {
const newUser = await prisma.institutionProfile.create({
data: {
institutionName: institutionName,
institutionEmail: institutionEmail,
Programs: [Programs], // Wrap Programs in an array to store it as an array of strings
Facilitator: Facilitator,
Username: Username,
Password: hashedPassword, // You should hash the password before storing it in production
},
});
res.json({ message: 'User registered successfully', user: newUser });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Failed to register user', errorMessage: error.message });
}
} catch (error) {
console.error('Error registering user:', error.message);
return res.status(500).send('An error occurred during user registration.');
}
});
// Handle Learner login
app.post('/login/learner', async (req, res) => {
try {
const { learnerEmail, learnerPassword } = req.body;
// Check if the learnerEmail and learnerPassword are provided
if (!learnerEmail || !learnerPassword) {
return res.status(400).send('Email and password are required.');
}
// Search for a learner in your database by email
const learner = await prisma.learnerProfile.findUnique({
where: {
learnerEmail: learnerEmail,
},
});
// If the learner doesn't exist, or the password is incorrect, return an error
if (!learner || !comparePasswords(learnerPassword, learner.password)) {
return res.status(401).send('Incorrect learner credentials.');
}
// If credentials are valid, you can create a session for the learner
req.session.user = learner; // Store user data in the session
// Redirect to the learner dashboard or send a success response
res.redirect('/learner/dashboard'); // Replace with your actual dashboard URL
} catch (error) {
console.error('Error logging in learner:', error.message);
return res.status(500).send('An error occurred during learner login.');
}
});
// handle login institution
app.post('/login/institution', async (req, res) => {
try {
const { institutionEmail, Password } = req.body;
if (!institutionEmail || !Password) {
return res.status(400).send('Missing data.');
}
// Check if the user exists in the database
const user = await prisma.institutionProfile.findUnique({
where: {
institutionEmail: institutionEmail,
},
});
if (!user) {
return res.status(404).send('User not found.');
}
// Verify the password (you should use a secure password hashing library like bcrypt)
const isPasswordValid = await bcrypt.compare(Password, user.Password);
if (!isPasswordValid) {
return res.status(401).send('Incorrect password.');
}
// Authentication successful, create a user session
req.session.user = user; // Store user data in the session
// Redirect to the institution dashboard
res.redirect('/institution-views/dashboard.html'); // Replace with your actual dashboard URL
} catch (error) {
console.error('Error logging in user:', error.message);
return res.status(500).send('An error occurred during user login.');
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});