2022-11-08 07:35:51 +01:00
|
|
|
import { createMiddleware, unauthorized, badRequest } from 'next-basics';
|
|
|
|
import debug from 'debug';
|
2020-07-18 19:36:46 +02:00
|
|
|
import cors from 'cors';
|
2022-11-08 07:35:51 +01:00
|
|
|
import { findSession } from 'lib/session';
|
|
|
|
import { parseAuthToken, parseShareToken } from 'lib/auth';
|
|
|
|
import redis from 'lib/redis';
|
|
|
|
|
|
|
|
const log = debug('umami:middleware');
|
2020-07-18 19:36:46 +02:00
|
|
|
|
2022-02-27 00:53:45 +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) => {
|
2022-11-08 07:35:51 +01:00
|
|
|
const session = await findSession(req);
|
2020-08-08 02:19:42 +02:00
|
|
|
|
|
|
|
if (!session) {
|
2022-11-08 07:35:51 +01:00
|
|
|
log('useSession:session-not-found');
|
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) => {
|
2022-10-31 19:02:37 +01:00
|
|
|
const token = await parseAuthToken(req);
|
|
|
|
const shareToken = await parseShareToken(req);
|
2020-08-08 02:19:42 +02:00
|
|
|
|
2022-11-08 07:35:51 +01:00
|
|
|
const key = `auth:${token?.authKey}`;
|
|
|
|
const data = redis.enabled ? await redis.get(key) : token;
|
|
|
|
|
|
|
|
if (!data && !shareToken) {
|
|
|
|
log('useAuth:user-not-authorized');
|
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-11-08 07:35:51 +01:00
|
|
|
req.auth = { ...data, shareToken };
|
2020-07-28 08:52:14 +02:00
|
|
|
next();
|
|
|
|
});
|