-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathauth-jwt.js
More file actions
64 lines (52 loc) · 1.66 KB
/
Copy pathauth-jwt.js
File metadata and controls
64 lines (52 loc) · 1.66 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
import express from "express";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET || "development-secret";
// Example in-memory "database" for teaching purposes only
const users = [
{
id: 1,
username: "alice",
// bcrypt.hashSync("password123", 10)
password_hash:
"$2b$10$uXQ26BC378vlfQz80XTlKecUnhlcWFzZdoygngzx5CQhPkZJRZDtO",
},
];
function getUserByUsername(username) {
return users.find((user) => user.username === username) ?? null;
}
const app = express();
app.use(express.json());
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = getUserByUsername(username);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
const isMatch = await bcrypt.compare(password, user.password_hash);
if (!isMatch) {
return res.status(401).json({ error: "Invalid credentials" });
}
const token = jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: "1h" });
res.json({ token });
});
function requireJwtAuth(req, res, next) {
const authHeader = req.headers.authorization;
const token = authHeader?.split(" ")[1];
if (!token) {
return res.status(401).json({ error: "No token provided" });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = { id: decoded.userId };
next();
} catch (err) {
return res.status(401).json({ error: "Invalid or expired token" });
}
}
app.get("/protected", requireJwtAuth, (req, res) => {
res.json({ data: "Top secret snippets", userId: req.user.id });
});
app.listen(3000, () => {
console.log("> Ready on http://localhost:3000 (JWT auth example)");
});