monkeytype/backend/middlewares/auth.js
2021-08-18 01:41:42 +01:00

25 lines
721 B
JavaScript

const MonkeyError = require("../handlers/error");
const { verifyIdToken } = require("../handlers/auth");
module.exports = {
async authenticateRequest(req, res, next) {
try {
const { authorization } = req.headers;
if (!authorization)
throw new MonkeyError(
401,
"Unauthorized",
`endpoint: ${req.baseUrl} no authrizaion header found`
);
const token = authorization.split(" ");
if (token[0].trim() !== "Bearer")
return next(
new MonkeyError(400, "Invalid Token", "Incorrect token type")
);
req.decodedToken = await verifyIdToken(token[1]);
return next();
} catch (e) {
return next(e);
}
},
};