-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathuser_auth_jwt.js
470 lines (404 loc) · 16.5 KB
/
user_auth_jwt.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
const http = require('http');
const mysql = require('mysql2');
const url = require('url');
const fs = require('fs');
const jwt = require('jsonwebtoken');
// Create a MySQL database connection
// const db = mysql.createConnection({
// // ... [database configuration]
// host: 'localhost',
// user: 'admin',
// password: 'password',
// database: 'mybookpal',
// });
let user_id = 0;
// // Connect to the database
// connection.connect((err) => {
// if (err) {
// console.error('MySQL Connection Error: ' + err.stack);
// return;
// }
// console.log('Connected to MySQL database');
// });
// JWT Secret Key
const JWT_SECRET_KEY = 'TRaKtr75iER4atLU'; // Replace with your actual secret key
// Function to verify JWT Token
// function verifyToken(req, res, next) {
// const bearerHeader = req.headers['authorization'];
// console.log('token :', bearerHeader)
// if (typeof bearerHeader !== 'undefined') {
// const token = bearerHeader.split(' ')[1];
// jwt.verify(token, JWT_SECRET_KEY, (err, decoded) => {
// if (err) {
// console.log("Error :", err);
// res.writeHead(403);
// res.end('Invalid or expired token');
// return;
// }
// // const check_decoded = jwt.decode(token);
// console.log("Decode token :", decoded);
// const userID = getUserIDFromDatabase(decoded.emailid);
// console.log("Global variable user_id:", userID);
// req.emailid = decoded.emailid;
// next(req, res);
// });
// } else {
// res.writeHead(401);
// res.end('Unauthorized');
// }
// }
async function verifyToken(req, res, next) {
const bearerHeader = req.headers['authorization'];
console.log('token:', bearerHeader);
if (typeof bearerHeader !== 'undefined') {
const token = bearerHeader.split(' ')[1];
try {
const decoded = await jwt.verify(token, JWT_SECRET_KEY);
console.log("Decode token:", decoded);
const userID = await getUserIDFromDatabase(decoded.emailid);
console.log("User ID:", userID);
req.emailid = decoded.emailid;
next();
} catch (err) {
console.log("Error:", err);
res.writeHead(err.name === 'JsonWebTokenError' ? 403 : 401);
res.end('Invalid or expired token');
}
} else {
res.writeHead(401);
res.end('Unauthorized');
}
}
function next(req, res) {
// Example protected endpoint logic
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Access granted', user: req.user }));
}
function serveFile(filePath, contentType, res) {
fs.readFile(filePath, (err, data) => {
if (err) {
console.error('Error reading file:', err);
res.writeHead(500);
res.end('Server Error');
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
}
});
}
// Create an HTTP server
// const server = http.createServer((req, res) => {
// const reqUrl = url.parse(req.url, true);
// const { pathname } = reqUrl;
// console.log('Pathname:', pathname);
// console.log('Method:',req.method);
// switch (true) {
// case (pathname === '/login' && req.method === 'POST'):
// console.log('Inside login POST');
// handleLogin(req, res);
// break;
// case ((pathname === '/login' || pathname === '/') && req.method === 'GET'):
// console.log('Inside login GET');
// serveFile('login.html', 'text/html', res);
// break;
// case ((pathname === '/register') && req.method === 'GET'):
// console.log('Inside register GET');
// serveFile('createacc.html', 'text/html', res);
// break;
// case (pathname === '/register' && req.method === 'POST'):
// console.log('Inside register');
// handleRegister(req, res);
// break;
// case (req.method === 'PUT' && pathname.startsWith('/customers/')):
// verifyToken(req, res, () => handleUpdateCustomer(req, res, pathname));
// break;
// case (req.method === 'GET' && pathname === '/customers'):
// console.log('/customers true');
// verifyToken(req, res, () => handleGetAllCustomers(req, res));
// break;
// case (req.method === 'GET' && pathname.startsWith('/customers/')):
// console.log("Pathname before verifyToken:", pathname);
// verifyToken(req, res, () => {
// console.log("Inside verifyToken. Pathname:", pathname);
// handleGetCustomer(req, res, pathname);
// });
// break;
// case (req.method === 'GET' && pathname.startsWith('/get-books/')):
// verifyToken(req, res, () => handleGetBooks(req, res, pathname));
// break;
// default:
// // Handle other cases or invalid requests
// res.writeHead(404);
// res.end('Not Found');
// }
// // if ( (pathname === '/login') && req.method === 'POST') {
// // console.log('Inside login POST');
// // handleLogin(req, res);
// // } else if ( (pathname === '/login' || pathname === '/' ) && req.method === 'GET') {
// // console.log('Inside login GET');
// // // console.log('res:', res);
// // serveFile('login.html', 'text/html', res);
// // } else if (pathname === '/register' && req.method === 'POST') {
// // console.log('Inside register');
// // handleRegister(req, res);
// // } else if (req.method === 'PUT' && pathname.startsWith('/customers/')) {
// // verifyToken(req, res, () => handleUpdateCustomer(req, res, pathname));
// // } else if (req.method === 'GET' && pathname === '/customers') {
// // console.log('/customers true');
// // verifyToken(req, res, () => handleGetAllCustomers(req, res));
// // } else if (req.method === 'GET' && pathname.startsWith('/customers/')) {
// // console.log("Pathname before verifyToken:", pathname);
// // verifyToken(req, res, () => {
// // console.log("Inside verifyToken. Pathname:", pathname);
// // handleGetCustomer(req, res, pathname);
// // });
// // } else if (req.method === 'GET' && pathname.startsWith('/get-books/')) {
// // verifyToken(req, res, () => handleGetBooks(req, res, pathname));}
// // // } else {
// // handleDefaultGet(req, res);
// // }
// });
function handleLogin(req, res, db) {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const { emailid, password } = JSON.parse(body);
console.log(emailid, password);
const query = 'SELECT * FROM CUSTOMER WHERE Email = ? AND UserPassword = ?';
db.query(query, [emailid, password], (err, results) => {
if (err || results.length === 0) {
console.log("Error",err);
res.writeHead(401);
res.end('Login failed');
return;
}
// console.log("CHECK::",err);
const token = jwt.sign({ emailid }, JWT_SECRET_KEY, { expiresIn: '24h' });
console.log("token :", token);
res.writeHead(302, { 'Location': 'http://localhost:3000/books' });
res.end(JSON.stringify({ token }));
});
});
}
function parseUrlEncodedData(data) {
var pairs = data.split('&');
var result = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
result[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
});
return JSON.stringify(result, null, 2);
}
function handleRegister(req, res, db) {
// ... [registration logic]
let data = '';
req.on('data', (chunk) => {
data += chunk;
});
// console.log('entries :', req, res);
req.on('end', () => {
// console.log("CHECK:",data);
const formData_temp = parseUrlEncodedData(data);
// console.log('--------------------------------');
// const formData = JSON.parse(data);
// console.log("Form Data :",typeof formData_temp);
formData = JSON.parse(formData_temp);
// console.log("Form Type :",typeof formData);
// console.log("Form Data :",formData);
// formData = JSON.parse(formData);
// const username = formData.userid;
const password = formData.password;
const firstName = formData.firstName;
const lastName = formData.lastName;
const usertype = 'customer';
const email = formData.email;
const address = formData.address;
const phone = formData.phone;
// console.log("phone datatype: ",phone);
// Validate phone number length
// const maxPhoneLength = 20; // This should match the length defined in your DB
// if (phone.length > maxPhoneLength) {
// res.writeHead(400, { 'Content-Type': 'text/plain' });
// res.end('Phone number is too long');
// return;
// }
// Check if the username already exists in the database
const usernameCheckQuery = 'SELECT Email FROM CUSTOMER WHERE Email = ?';
db.query(usernameCheckQuery, [email], (err, results) => {
if (err) {
console.log("Error checking username", err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Registration Failed');
} else if (results.length > 0) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('User already exists');
} else {
// Insert the new user into the database
const insertQuery = 'INSERT INTO CUSTOMER (FirstName, LastName, PhoneNumber, Email, UserAddress, UserPassword, UserType,UserCreatedAt,LastLogin,LastUpdated) VALUES (?, ?, ?, ?, ?, ?, ?,NOW(),NOW(),NOW())';
// console.log("check query :", [firstName, lastName, phone, email, address, password, usertype]);
db.query(insertQuery, [firstName, lastName, phone, email, address, password, usertype], (err) => {
if (err) {
console.log("Error inserting new user", err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Registration Failed');
} else {
res.writeHead(302, { 'Location': 'http://localhost:3000/' });
res.end('Registration Successful');
// res.end("window.location.href = './login.html';")
// window.location.href = './login.html';
}
});
}
});
});
}
function getUserIDFromDatabase(userIdentifier) {
return new Promise((resolve, reject) => {
const query = 'SELECT UserID FROM Customer WHERE Email = ?'; // Adjust the SQL query based on your schema
db.query(query, [userIdentifier], (error, results) => {
if (error) {
reject(error);
} else if (results.length > 0) {
const userID = results[0].UserID; // Adjust according to your result structure
user_id = userID;
console.log("User ID::", userID);
resolve(userID);
} else {
reject(new Error('User not found'));
}
});
});
}
// Function to handle updating a customer
function handleUpdateCustomer(req, res, pathname, db) {
// ... [update customer logic]
const Username = pathname.split('/')[2];
let data = '';
req.on('data', (chunk) => {
data += chunk;
});
req.on('end', () => {
try {
const customer = JSON.parse(data);
let update_customer = customer;
db.query('UPDATE Customer SET FirstName = ?, LastName = ?, PhoneNumber = ?, Email = ?, UserAddress = ?, UserPassword = ?, UserType = ? WHERE UserID = ?',
[update_customer.first_name, update_customer.last_name, update_customer.phone, update_customer.email, update_customer.address, update_customer.password, update_customer.user_type, Username],
(err) => {
if (err) {
res.statusCode = 500;
res.end('Internal Server Error');
} else {
res.statusCode = 200;
res.end('Customer updated');
}
});
} catch (err) {
res.statusCode = 400;
res.end('Invalid request');
}
});
}
// Function to handle getting all customers
function handleGetAllCustomers(req, res, db) {
// ... [get all customers logic]
db.query('SELECT UserID, FirstName, LastName, PhoneNumber, Email, UserAddress, UserType FROM CUSTOMER', (err, rows) => {
if (err) {
console.log("Error:",err);
res.statusCode = 500;
res.end('Internal Server Error');
} else {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(rows));
}
});
}
// Function to handle getting a specific customer
function handleGetCustomer(req, res, pathname, db) {
// ... [get specific customer logic]
console.log("Print all:",res);
console.log("username check:", pathname);
const Username = pathname.split('/')[2];
db.query('SELECT UserID, FirstName, LastName, PhoneNumber, Email, UserAddress, UserType FROM Customer WHERE UserID = ?', [Username], (err, row) => {
if (err) {
res.statusCode = 500;
res.end('Internal Server Error');
} else if (!row) {
res.statusCode = 404;
res.end('Customer not found');
} else {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(row));
}
});
}
// Function to handle getting books based on filter criteria
function handleGetBooks(req, res, pathname, db) {
// ... [get books logic]
const queryParams = pathname.split('/')[2];
try {
const filterCriteria = JSON.parse(queryParams.filter);
if (Object.keys(filterCriteria).length === 0) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Filter criteria cannot be empty');
return;
}
const conditions = [];
for (const key in filterCriteria) {
if (filterCriteria.hasOwnProperty(key)) {
const value = filterCriteria[key];
conditions.push(`${key} = ${db.escape(value)}`);
}
}
const whereClause = conditions.join(' AND ');
const query = `SELECT * FROM BookListing WHERE ${whereClause}`;
db.query(query, (err, results) => {
if (err) {
console.error('Database error: ' + err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
if (results.length > 0) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(results));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('No books found with the specified criteria');
}
}
});
} catch (error) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Invalid JSON request');
}
}
// Function to check password strength (if needed)
function isStrongPassword(password) {
const regex = /^(?=.*[A-Z])(?=.*\d)(?=.*[a-zA-Z0-9]).{8,}$/;
return regex.test(password);
}
// Function to send SMS notification
function sendSMSNotification(phoneNumber, message) {
twilioClient.messages.create({
body: message,
from: twilioPhoneNumber,
to: phoneNumber,
});
}
module.exports ={
handleLogin,
handleRegister,
handleUpdateCustomer,
handleGetAllCustomers,
handleGetCustomer,
handleGetBooks,
getUserIDFromDatabase,
verifyToken
// handleDefaultGet
}
// // Start the server
// const port = 3000;
// server.listen(port, () => {
// console.log(`Server is running on http://localhost:${port}`);
// });