minecluster/lib/routes/middlewares/auth-middleware.js
Dunemask 6eed3fd694
Some checks failed
Deploy Edge Proxy / deploy-edge (push) Failing after 3s
Deploy USW-MC / deploy-edge (push) Failing after 2s
S3 Repo Backup / s3-repo-backup (push) Failing after 4s
[HOTFIX] Auth Credential Failures
2024-03-29 13:40:27 -06:00

47 lines
1.5 KiB
JavaScript

// Imports
import { Router } from "express";
import bearerTokenMiddleware from "express-bearer-token";
import { ERR, VERB } from "../../util/logging.js";
// Constants
const { MCL_CAIRO_URL } = process.env;
const cairoAuthMiddleware = Router();
const cairoAuthenticate = async (token) => {
const config = { headers: { Authorization: `Bearer ${token}` } };
return fetch(`${MCL_CAIRO_URL}/api/user/info`, config).then(async (res) => {
if (res.status >= 300) {
const errorMessage = await res
.json()
.then((data) => JSON.stringify(data))
.catch(() => res.statusText);
throw Error(
`Could not authenticate with user, receieved message: ${errorMessage}`,
);
}
return res.json();
});
};
// Middleware
const cairoAuthHandler = (req, res, next) => {
if (!req.token) return res.status(401).send("Cairo auth required!");
cairoAuthenticate(req.token)
.then((authData) => {
console.log(authData);
if (!authData.id)
throw Error(`Cairo didn't return the expected data! ${authData.id}`);
req.cairoId = authData.id;
})
.then(() => next())
.catch((err) => {
ERR("AUTH", err.response ? err.response.data : err.message);
if (!err.response) return res.status(500).send(`Auth failure ${err}`);
return res.status(err.response.status).send(err.response.data);
});
};
cairoAuthMiddleware.use([bearerTokenMiddleware(), cairoAuthHandler]);
export default cairoAuthMiddleware;