monkeytype/backend/middlewares/auth.js

84 lines
1.8 KiB
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");
const DEFAULT_OPTIONS = {
isPublic: false,
};
function authenticateRequest(options = DEFAULT_OPTIONS) {
return async (req, _res, next) => {
2021-06-07 00:32:37 +08:00
try {
const { authorization: authHeader } = req.headers;
let token = null;
if (authHeader) {
token = await authenticateWithAuthHeader(authHeader);
} else if (options.isPublic) {
return next();
} else if (process.env.MODE === "dev") {
token = authenticateWithBody(req.body);
} else {
2021-08-18 08:41:29 +08:00
throw new MonkeyError(
401,
"Unauthorized",
2022-01-14 23:20:04 +08:00
`endpoint: ${req.baseUrl} no authorization header found`
2021-08-18 08:41:29 +08:00
);
2022-02-04 20:06:09 +08:00
}
req.ctx.decodedToken = token;
} catch (error) {
return next(error);
2021-06-07 00:32:37 +08:00
}
next();
};
}
function authenticateWithBody(body) {
const { uid } = body;
if (!uid) {
throw new MonkeyError(
400,
"Running authorization in dev mode but still no uid was provided"
);
}
return {
uid,
};
}
async function authenticateWithAuthHeader(authHeader) {
const token = authHeader.split(" ");
const authScheme = token[0].trim();
const credentials = token[1];
if (authScheme === "Bearer") {
return await authenticateWithBearerToken(credentials);
}
throw new MonkeyError(
400,
"Unknown authentication scheme",
`The authentication scheme "${authScheme}" is not implemented.`
);
}
async function authenticateWithBearerToken(token) {
try {
return await verifyIdToken(token);
} catch (error) {
if (error.message.includes("auth/id-token-expired")) {
throw new MonkeyError(401, "Unauthorized", "Token expired");
} else {
throw error;
}
}
}
module.exports = {
authenticateRequest,
2021-06-07 00:32:37 +08:00
};