-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
84 lines (74 loc) · 2.15 KB
/
index.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
const express = require("express");
const mysql = require("mysql2");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
// MySQL Connection
const db = mysql.createConnection({
host: "34.128.113.176",
user: "root",
password: "Total-UMKM",
database: "capstone_project",
});
db.connect((err) => {
if (err) {
console.error("Error connecting to MySQL:", err);
} else {
console.log("Connected to MySQL");
}
});
// Routes
app.post("/register", async (req, res) => {
try {
const { username, email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
db.query(
"INSERT INTO user (username, email, password) VALUES (?, ?, ?)",
[username, email, hashedPassword],
(error, results) => {
if (error) {
res.status(500).json({ error: error.message });
} else {
res.status(201).json({ message: "User registered successfully" });
}
}
);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post("/login", async (req, res) => {
try {
const { username, password } = req.body;
db.query(
"SELECT * FROM user WHERE username = ?",
[username],
async (error, results) => {
if (error) {
res.status(500).json({ error: error.message });
} else if (results.length > 0) {
const user = results[0];
const passwordMatch = await bcrypt.compare(password, user.password);
if (passwordMatch) {
const token = jwt.sign({ username: user.username }, "secret-key");
res.json({ token });
} else {
res.status(401).json({ message: "Authentication failed" });
}
} else {
res.status(401).json({ message: "Authentication failed" });
}
}
);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start Server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});