-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
104 lines (81 loc) · 3.79 KB
/
Copy pathserver.js
File metadata and controls
104 lines (81 loc) · 3.79 KB
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
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const initializeDB = require('./database'); // Import MySQL connection logic
const app = express();
const PORT = 3000;
// Middleware setup
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Serve the static frontend file (index.html)
app.use(express.static(__dirname));
let dbPool; // Use a connection pool for MySQL
/**
* Function to initialize the database and start the Express server.
*/
async function startServer() {
try {
// STEP 1: Initialize the database connection (using MySQL)
dbPool = await initializeDB();
// --- API ROUTES ---
// 1. Registration Route: Handles new user creation
app.post('/api/register', async (req, res) => {
const { name: full_name, email, password } = req.body;
if (!full_name || !email || !password) {
return res.status(400).json({ success: false, message: 'All fields are required.' });
}
try {
// Check for existing user: Using dbPool.execute()
const [rows] = await dbPool.execute('SELECT id FROM users WHERE email = ?', [email]);
if (rows.length > 0) {
return res.status(409).json({ success: false, message: 'Email already registered.' });
}
// Securely hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Insert new user into the MySQL database: Using dbPool.execute()
const [result] = await dbPool.execute(
'INSERT INTO users (full_name, email, password) VALUES (?, ?, ?)',
[full_name, email, hashedPassword]
);
console.log(`New user registered with ID: ${result.insertId}`);
res.status(201).json({ success: true, message: 'Registration successful! You can now log in.' });
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({ success: false, message: 'Server error during registration.' });
}
});
// 2. Login Route: Handles user sign-in
app.post('/api/login', async (req, res) => {
const { email, password } = req.body;
try {
// Find user by email: Using dbPool.execute()
const [rows] = await dbPool.execute('SELECT * FROM users WHERE email = ?', [email]);
const user = rows[0];
if (!user) {
return res.status(401).json({ success: false, message: 'Invalid credentials.' });
}
// Compare submitted password with stored hash
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ success: false, message: 'Invalid credentials.' });
}
// Login successful!
res.status(200).json({
success: true,
message: `Welcome back, ${user.full_name}! Login successful.`
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ success: false, message: 'Server error during login.' });
}
});
// STEP 2: Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
} catch (error) {
console.error('Failed to start server due to database error. Please resolve the connection error above.');
process.exit(1);
}
}
startServer();