2022-08-29 05:20:54 +02:00
|
|
|
import { createMiddleware, unauthorized, badRequest, serverError } from 'next-basics';
|
2020-07-18 19:36:46 +02:00
|
|
|
import cors from 'cors';
|
2020-09-18 07:52:20 +02:00
|
|
|
import { getSession } from './session';
|
2022-10-12 06:48:33 +02:00
|
|
|
import { getAuthToken, getShareToken } from './auth';
|
2020-07-18 19:36:46 +02:00
|
|
|
|
2023-01-25 17:47:13 +01:00
|
|
|
export const useCors = createMiddleware(
|
|
|
|
cors({
|
|
|
|
// Cache CORS preflight request 24 hours by default
|
|
|
|
maxAge: process.env.CORS_MAX_AGE || 86400,
|
|
|
|
}),
|
|
|
|
);
|
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 {
|
2020-09-18 07:52:20 +02:00
|
|
|
session = await getSession(req);
|
2020-08-24 04:21:39 +02:00
|
|
|
} catch (e) {
|
2022-08-29 05:20:54 +02:00
|
|
|
// eslint-disable-next-line no-console
|
2020-09-18 23:16:57 +02:00
|
|
|
console.error(e);
|
2022-08-29 05:20:54 +02:00
|
|
|
|
2020-08-12 05:05:40 +02:00
|
|
|
return serverError(res, e.message);
|
2020-08-24 04:21:39 +02:00
|
|
|
}
|
2020-08-08 02:19:42 +02:00
|
|
|
|
|
|
|
if (!session) {
|
2020-08-12 05:05:40 +02:00
|
|
|
return badRequest(res);
|
2020-07-28 08:52:14 +02:00
|
|
|
}
|
2020-08-08 02:19:42 +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) => {
|
2020-09-18 07:52:20 +02:00
|
|
|
const token = await getAuthToken(req);
|
2022-10-12 06:48:33 +02:00
|
|
|
const shareToken = await getShareToken(req);
|
2020-08-08 02:19:42 +02:00
|
|
|
|
2022-10-25 04:48:10 +02:00
|
|
|
if (!token && !shareToken) {
|
2020-08-12 05:05:40 +02:00
|
|
|
return unauthorized(res);
|
2020-07-28 08:52:14 +02:00
|
|
|
}
|
2020-08-08 02:19:42 +02:00
|
|
|
|
2022-10-12 06:48:33 +02:00
|
|
|
req.auth = { ...token, shareToken };
|
2020-07-28 08:52:14 +02:00
|
|
|
next();
|
|
|
|
});
|