-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
95 lines (81 loc) · 2.49 KB
/
auth.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
const express = require("express");
const router = express.Router();
const db = require("./database");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const auth = require("./middleware/auth");
require("dotenv").config({
path: "./.env",
});
const jwtSecret = process.env.JWT_SECRET;
const SALT_ROUNDS = 10;
router.post("/login", (req, res) => {
const { username, password } = req.body;
db.get(
"SELECT * FROM users WHERE username = ?",
[username],
async (err, user) => {
if (err) return res.status(500).send("Server error");
if (!user) return res.status(400).send("User not found");
// Compare the password with the hashed password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
res.status(400).send("Invalid password");
}
// Create and send a JWT token
const payload = { user: { id: user.id } };
jwt.sign(payload, jwtSecret, { expiresIn: "24h" }, (err, token) => {
if (err) throw err;
res.json({ token });
});
}
);
});
router.post("/register", (req, res) => {
const { username, password, repeatPass } = req.body;
db.all(
"SELECT * FROM users WHERE username = ?",
[username],
async (err, user) => {
if (err) {
throw err;
}
if (password !== repeatPass) {
return res.status(409).send("Password doesn't match!");
} else if (user.length === 0) {
const passwordHash = await bcrypt.hash(password, SALT_ROUNDS);
db.all(
`INSERT INTO users (username, password) VALUES (?,?)`,
[username, passwordHash],
(err) => {
if (err) {
throw err;
}
return res.send(`New accound for user ${username} is created!`);
}
);
} else {
res.status(409).send("Username already exists");
}
}
);
});
// Flush users table (except of admin)
router.delete("/deleteusers", (req, res) => {
const query = "DELETE FROM users WHERE id != ?";
const userId = 1;
db.all(query, [userId], function (err) {
if (!!err) {
return res.status(500).send({ error: err.message });
}
res.send("All users were removed!");
});
});
// Protected route to get user data
router.get("/getuser", auth, (req, res) => {
db.get("SELECT * FROM users WHERE id = ?", [req.user.id], (err, user) => {
if (err) return res.status(500).send("Server error");
res.json(user);
});
});
module.exports = router;