monkeytype/backend/middlewares/auth.js

26 lines
721 B
JavaScript
Raw Normal View History

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 {
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);
}
},
};