2023-06-09 20:27:27 +02:00
|
|
|
const { decodeJWT } = require("../http");
|
|
|
|
|
2023-06-04 04:28:07 +02:00
|
|
|
function validatedRequest(request, response, next) {
|
|
|
|
// When in development passthrough auth token for ease of development.
|
2023-06-09 20:27:27 +02:00
|
|
|
// Or if the user simply did not set an Auth token or JWT Secret
|
|
|
|
if (
|
|
|
|
process.env.NODE_ENV === "development" ||
|
|
|
|
!process.env.AUTH_TOKEN ||
|
|
|
|
!process.env.JWT_SECRET
|
|
|
|
) {
|
2023-06-04 04:28:07 +02:00
|
|
|
next();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!process.env.AUTH_TOKEN) {
|
|
|
|
response.status(403).json({
|
2023-06-08 06:31:35 +02:00
|
|
|
error: "You need to set an AUTH_TOKEN environment variable.",
|
2023-06-04 04:28:07 +02:00
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-06-08 06:31:35 +02:00
|
|
|
const auth = request.header("Authorization");
|
|
|
|
const token = auth ? auth.split(" ")[1] : null;
|
2023-06-04 04:28:07 +02:00
|
|
|
|
|
|
|
if (!token) {
|
|
|
|
response.status(403).json({
|
2023-06-08 06:31:35 +02:00
|
|
|
error: "No auth token found.",
|
2023-06-04 04:28:07 +02:00
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-06-09 20:27:27 +02:00
|
|
|
const { p } = decodeJWT(token);
|
|
|
|
if (p !== process.env.AUTH_TOKEN) {
|
2023-06-04 04:28:07 +02:00
|
|
|
response.status(403).json({
|
2023-06-08 06:31:35 +02:00
|
|
|
error: "Invalid auth token found.",
|
2023-06-04 04:28:07 +02:00
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
validatedRequest,
|
2023-06-08 06:31:35 +02:00
|
|
|
};
|