forked from umami-software/umami
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
47 lines (38 loc) · 955 Bytes
/
middleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import cors from 'cors';
import { getSession } from './session';
import { getAuthToken } from './auth';
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);
});
});
}
export const useCors = use(cors());
export const useSession = use(async (req, res, next) => {
let session;
try {
session = await getSession(req);
} catch (e) {
console.error(e);
return serverError(res, e.message);
}
if (!session) {
return badRequest(res);
}
req.session = session;
next();
});
export const useAuth = use(async (req, res, next) => {
const token = await getAuthToken(req);
if (!token) {
return unauthorized(res);
}
req.auth = token;
next();
});