umami/lib/middleware.js

48 lines
1007 B
JavaScript
Raw Normal View History

import cors from 'cors';
import { getSession } from './session';
import { getAuthToken } from './auth';
2020-08-12 05:05:40 +02:00
import { unauthorized, badRequest, serverError } from './response';
2022-02-27 00:53:45 +01:00
export function createMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, result => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
2022-03-11 04:01:33 +01:00
export const useCors = createMiddleware(cors());
2020-07-28 08:52:14 +02:00
2022-02-27 00:53:45 +01:00
export const useSession = createMiddleware(async (req, res, next) => {
2020-08-24 04:21:39 +02:00
let session;
try {
session = await getSession(req);
2020-08-24 04:21:39 +02:00
} catch (e) {
console.error(e);
2020-08-12 05:05:40 +02:00
return serverError(res, e.message);
2020-08-24 04:21:39 +02:00
}
if (!session) {
2020-08-12 05:05:40 +02:00
return badRequest(res);
2020-07-28 08:52:14 +02:00
}
req.session = session;
2020-07-28 08:52:14 +02:00
next();
});
2022-02-27 00:53:45 +01:00
export const useAuth = createMiddleware(async (req, res, next) => {
const token = await getAuthToken(req);
if (!token) {
2020-08-12 05:05:40 +02:00
return unauthorized(res);
2020-07-28 08:52:14 +02:00
}
req.auth = token;
2020-07-28 08:52:14 +02:00
next();
});