node-mongo-demo
node.js and mongodb demo
git clone https://9o.is/git/node-mongo-demo.git
auth.js
(537B)
1 import jwt from "jsonwebtoken";
2
3 const auth = async (req, res, next) => {
4 try {
5 const token = req.headers.authorization.split(" ")[1];
6 const isCustomAuth = token.length < 500;
7
8 let decodedData;
9
10 if (token && isCustomAuth) {
11 decodedData = jwt.verify(token, "test");
12 req.userId = decodedData?._id;
13 } else {
14 decodedData = jwt.decode(token);
15 req.userId = decodedData?.sub;
16 }
17
18 next();
19 } catch (error) {
20 res.status(401).json({ message: "Unauthorized" })
21 }
22 };
23
24 export default auth;