-
Notifications
You must be signed in to change notification settings - Fork 0
/
middlewares.js
26 lines (25 loc) · 968 Bytes
/
middlewares.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
import jwt from "./modules/jwt.js";
import { catchErrorToken } from "./controller/authController.js";
export const publicOnlyMiddleware = (req, res, next) => {
let token = req.headers["x-access-token"];
console.log("[PUB ONLY MID] token: ", token);
if (token && token !== "undefined")
res.status(400).send("User already logged in.");
else next();
};
const MASTER_TOKEN = "q1w2e3r4";
const isTokenUser = async (token, user) => {
if (token === MASTER_TOKEN) return true;
// if(token[0] === "\"")
const decode = await jwt.verify(token);
if (catchErrorToken(decode)) return false;
const { username } = decode;
return user === username;
};
export const protectorMiddleWare = async (req, res, next) => {
const token = req.headers["x-access-token"];
const { user } = req.params;
console.log("[PROTECT MID] USER : ", user);
if (!user || (await isTokenUser(token, user))) next();
else res.status(400).send("User's token is not correct.");
};