1
0
mirror of https://github.com/kremalicious/umami.git synced 2024-12-24 18:26:20 +01:00
umami/lib/middleware.js

53 lines
1023 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';
2020-08-12 05:05:40 +02:00
import { unauthorized, badRequest, serverError } from './response';
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) => {
2020-08-24 04:21:39 +02:00
let session;
try {
session = await verifySession(req);
} catch (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();
});
export const useAuth = use(async (req, res, next) => {
2020-08-24 04:21:39 +02:00
let token;
try {
token = await verifyAuthToken(req);
} catch (e) {
2020-08-12 05:05:40 +02:00
return serverError(res, e.message);
2020-08-24 04:21:39 +02:00
}
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();
});