-
Notifications
You must be signed in to change notification settings - Fork 0
/
express.js
204 lines (142 loc) · 5.57 KB
/
express.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
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const winston = require('winston');
const mysql =require('mysql2');
const multer = require('multer');
const bcrypt = require('bcrypt');
const app = express();
const port = 3000;
const upload = multer();
app.use(upload.none());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/styles.css', (req, res) => {
res.sendFile(__dirname + '/StyleSheet.css');
});
app.get('/script.js', (req, res) => {
res.sendFile(__dirname + '/javascript.js');
});
app.get('/register.html', (req, res) => {
res.sendFile(__dirname + '/register.html');
});
app.get('/reg.css', (req, res) => {
res.sendFile(__dirname + '/reg.css');
});
app.get('/reg.js', (req, res) => {
res.sendFile(__dirname + '/reg.js');
});
app.get('/styles_02.css', (req, res) => {
res.sendFile(__dirname + '/styles_02.css');
});
// Create a connection pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'users',
port: 3306,
// connectionLimit: 10,
});
function connectToDatabase() {
return new Promise((resolve, reject) => {
const promiseConnection = pool.promise(); // Using promise version
promiseConnection.getConnection()
.then(connection => {
console.log('Connected to the database');
resolve(connection);
})
.catch(error => {
console.error('Error connecting to the database:', error);
reject(error);
});
});
}
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'audit.log'}),
new winston.transports.File({ filename: 'failed_login_attempts.log', level: 'warn' }),
new winston.transports.File({ filename: 'successful_logins.log', level: 'info' }),
],
});
app.post('/submit_registration', async (req, res) => {
// console.log('Request Body:', req.body)
try {
// Handle form submission logic here
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;
const connection = await connectToDatabase();
const hashedPassword = await bcrypt.hash(password, 10); // 10 is the number of salt rounds
// Insert data into the database using parameterized query
const query = 'INSERT INTO user_info (user_name, email, hashed_password) VALUES (?, ?, ?)';
// -> debugging console.log('SQL Query:', query, [username, email, password]);
const result = await connection.query(query, [username, email, hashedPassword]);
console.log('Data inserted into the database:', result[0].affectedRows);
logger.info(`Registration successful: User ${username}, Email ${email}`);
// Release the connection back to the pool
connection.release();
// Send a response back to the client
res.status(200).send('Registration successful!');
} catch (error) {
console.error('Error inserting data into the database:', error);
logger.error(`Error inserting data into the database: ${error}`);
// Send an error response back to the client
res.status(500).send('Internal Server Error');
}
});
app.post('/login', async (req, res) => {
try {
const email = req.body.email;
const password = req.body.password;
// Check the database for the provided email
const connection = await connectToDatabase();
const [results] = await connection.query('SELECT * FROM user_info WHERE email = ?', [email]);
if (results.length > 0) {
// User found, compare passwords
const storedHashedPassword = results[0].hashed_password;
// Compare the provided password with the stored hashed password
const passwordMatch = await bcrypt.compare(password, storedHashedPassword);
if (passwordMatch) {
logger.info(`Login successful: User with Email ${email}`);
// Redirect to a success page
res.redirect('/success_page.html');
} else {
// res.status(200).send('1Login not successful');
logger.warn(`Login unsuccessful: Invalid password for User with Email ${email}`);
res.redirect('/failure_page.html');
}
} else {
// res.status(200).send('2Login not successful');
logger.warn(`Login unsuccessful: Invalid password for User with Email ${email}`);
// Email not found, redirect to a failure page or display an error message
res.redirect('/failure_page.html');
}
// Release the connection back to the pool
connection.release();
}
catch (error) {
logger.error(`Error during login: ${error}`);
console.error('Error inserting data into the database:', error);
// Send an error response back to the client
res.status(500).send('Internal Server Error');
}
});
// app.get('/th', async (req, res) => {
// try {
// await performHealthCheck();
// res.status(200).send('OK');
// } catch (error) {
// res.status(500).send(error);
// }
// });
// ...
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});