-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
95 lines (82 loc) · 3.23 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
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const connection = require('./dbConfig.js');
const verifyToken = require('./authMiddleware.js');
const app = express();
const port = 3000;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Combined registration and login endpoint
app.post('/auth', (req, res) => {
const { username, email, password, action } = req.body;
// Ensure username, email, and password are provided
if (!username || !email || !password || !action) {
res.status(400).send('Username, email, password, and action are required');
return;
}
if (action === 'register') {
// Hash password
bcrypt.hash(password, 10, (err, hashedPassword) => {
if (err) {
console.error('Error hashing password: ' + err.stack);
res.status(500).send('Error hashing password');
return;
}
const user = { username, email, password: hashedPassword };
// Insert user into the database
connection.query('INSERT INTO users SET ?', user, (error, results, fields) => {
if (error) {
console.error('Error registering user: ' + error.stack);
res.status(500).send('Error registering user');
return;
}
console.log('User registered successfully');
res.status(200).send('User registered successfully');
});
});
} else if (action === 'login') {
// Check user credentials
connection.query('SELECT * FROM users WHERE username = ?', [username], (error, results, fields) => {
if (error) {
console.error('Error retrieving user: ' + error.stack);
res.status(500).send('Error retrieving user');
return;
}
if (results.length === 0) {
res.status(404).send('User not found');
return;
}
const user = results[0];
// Compare hashed password
bcrypt.compare(password, user.password, (err, result) => {
if (err) {
console.error('Error comparing passwords: ' + err.stack);
res.status(500).send('Error comparing passwords');
return;
}
if (result) {
// Generate JWT token
const token = jwt.sign({ username: user.username }, 'your_secret_key_here', { expiresIn: '365d' });
res.status(200).json({ token });
} else {
res.status(401).send('Invalid username or password');
}
});
});
} else {
res.status(400).send('Invalid action');
}
});
// Protected route example
app.get('/protected-route', verifyToken, (req, res) => {
// This route is protected and can only be accessed with a valid token
res.send('This is a protected route');
});
// Start server
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});