-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.js
More file actions
32 lines (23 loc) · 720 Bytes
/
auth.js
File metadata and controls
32 lines (23 loc) · 720 Bytes
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
// auth.js
const jwt = require("jsonwebtoken");
const User = require("./models/userSchema");
require("dotenv").config();
const secretKey = process.env.JWT_SECRET_KEY;
const verifyToken = async (req, res, next) => {
try {
const token = req.headers["authorization"];
if (!token) {
return res.status(401).json({ error: "無權訪問" });
}
const decoded = jwt.verify(token, secretKey);
const user = await User.findById(decoded.id);
if (!user || user.token !== token) {
return res.status(401).json({ error: "token 不正確" });
}
req.user = user;
next();
} catch (error) {
res.status(500).json({ error: error.message });
}
};
module.exports = verifyToken;