umami/lib/middleware.js

50 lines
1.2 KiB
JavaScript
Raw Normal View History

import { createMiddleware, unauthorized, badRequest, parseSecureToken } from 'next-basics';
import debug from 'debug';
import cors from 'cors';
2022-11-09 19:15:21 +01:00
import { validate } from 'uuid';
import { findSession } from 'lib/session';
import { parseShareToken, getAuthToken } from 'lib/auth';
2022-11-09 19:15:21 +01:00
import { secret } from 'lib/crypto';
2022-11-09 15:40:36 +01:00
import redis from 'lib/redis';
import { getUser } from '../queries';
const log = debug('umami:middleware');
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) => {
const session = await findSession(req);
if (!session) {
log('useSession:session-not-found');
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 = getAuthToken(req);
2022-11-09 15:40:36 +01:00
const key = parseSecureToken(token, secret());
2022-10-31 19:02:37 +01:00
const shareToken = await parseShareToken(req);
2022-11-09 15:40:36 +01:00
let user;
2022-11-09 19:16:50 +01:00
if (validate(key)) {
2022-11-09 15:40:36 +01:00
user = await getUser({ id: key });
2022-11-09 19:16:50 +01:00
} else if (redis.enabled) {
user = await redis.get(key);
2022-11-09 15:40:36 +01:00
}
if (!user && !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
}
2022-11-09 19:15:21 +01:00
log({ user, token, shareToken, key });
2022-11-09 15:40:36 +01:00
req.auth = { user, token, shareToken, key };
2020-07-28 08:52:14 +02:00
next();
});