umami/lib/middleware.js

36 lines
763 B
JavaScript
Raw Normal View History

import cors from 'cors';
2020-08-05 07:45:05 +02:00
import { verifySession } from './session';
import { verifyAuthToken } from './auth';
export function use(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, result => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
2020-07-26 01:31:07 +02:00
export const useCors = use(cors());
2020-07-28 08:52:14 +02:00
export const useSession = use(async (req, res, next) => {
try {
2020-08-05 07:45:05 +02:00
req.session = await verifySession(req);
2020-07-28 08:52:14 +02:00
} catch {
return res.status(400).end();
}
next();
});
export const useAuth = use(async (req, res, next) => {
try {
2020-08-05 07:45:05 +02:00
req.auth = await verifyAuthToken(req);
2020-07-28 08:52:14 +02:00
} catch {
return res.status(401).end();
}
next();
});