minecluster/lib/routes/middlewares/auth-middleware.js

48 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

// Imports
import { Router } from "express";
import bearerTokenMiddleware from "express-bearer-token";
import { ERR, VERB } from "../../util/logging.js";
// Constants
2024-08-24 16:41:52 -06:00
const { MCL_CAIRO_URL, MCL_CAIRO_PROJECT } = process.env;
const cairoAuthMiddleware = Router();
const cairoAuthenticate = async (token) => {
const config = { headers: { Authorization: `Bearer ${token}` } };
2024-08-24 16:41:52 -06:00
return fetch(`${MCL_CAIRO_URL}/api/${MCL_CAIRO_PROJECT}/auth/credentials`, config).then(async (res) => {
2024-03-29 12:39:44 -06:00
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)
2024-03-29 12:39:44 -06:00
.then((authData) => {
console.log(authData);
2024-08-24 16:41:52 -06:00
if (!authData?.user?.id)
throw Error(`Cairo didn't return the expected data! ${authData?.user?.id}`);
req.cairoId = authData?.user?.id;
2024-03-29 12:39:44 -06:00
})
.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;