2021-06-07 01:26:12 +08:00
|
|
|
const MonkeyError = require("../handlers/error");
|
2021-06-07 00:32:37 +08:00
|
|
|
const { verifyIdToken } = require("../handlers/auth");
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
async authenticateRequest(req, res, next) {
|
|
|
|
try {
|
2021-09-07 22:04:50 +08:00
|
|
|
if (process.env.MODE === "dev" && !req.headers.authorization) {
|
|
|
|
if (req.body.uid) {
|
|
|
|
req.decodedToken = {
|
|
|
|
uid: req.body.uid,
|
|
|
|
};
|
|
|
|
console.log("Running authorization in dev mode");
|
|
|
|
return next();
|
|
|
|
} else {
|
|
|
|
throw new MonkeyError(
|
|
|
|
400,
|
|
|
|
"Running authorization in dev mode but still no uid was provided"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2021-06-07 00:32:37 +08:00
|
|
|
const { authorization } = req.headers;
|
2021-08-18 08:41:29 +08:00
|
|
|
if (!authorization)
|
|
|
|
throw new MonkeyError(
|
|
|
|
401,
|
|
|
|
"Unauthorized",
|
|
|
|
`endpoint: ${req.baseUrl} no authrizaion header found`
|
|
|
|
);
|
2021-06-07 00:32:37 +08:00
|
|
|
const token = authorization.split(" ");
|
2021-06-17 03:56:00 +08:00
|
|
|
if (token[0].trim() !== "Bearer")
|
2021-08-18 08:41:29 +08:00
|
|
|
return next(
|
|
|
|
new MonkeyError(400, "Invalid Token", "Incorrect token type")
|
|
|
|
);
|
2021-06-07 00:32:37 +08:00
|
|
|
req.decodedToken = await verifyIdToken(token[1]);
|
|
|
|
return next();
|
|
|
|
} catch (e) {
|
|
|
|
return next(e);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
};
|