Files
forgetmenot-nextjs/web/lib/jsonapi.js
2022-08-27 08:14:10 -05:00

43 lines
838 B
JavaScript

import auth0 from "./auth0";
async function jsonApi(handler) {
var unauthenticationHandler = async (req, res) => {
try {
await handler(req, res);
} catch (error) {
handleError(res, error);
}
res.end();
};
return unauthenticationHandler;
}
function authenticatedJsonApi(handler) {
var authenticatedHandler = async (req, res) => {
try {
const session = await auth0.getSession(req, res);
if (!session || !session.user) {
res.status(401);
} else {
await handler(req, res, session);
}
} catch (error) {
handleError(res, error);
}
res.end();
};
return authenticatedHandler;
}
function handleError(res, error) {
console.error(error);
res.status(error.status || 500).end(error.message);
}
export { jsonApi, authenticatedJsonApi };