2021-03-29 19:58:11 +02:00
|
|
|
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
2021-09-15 20:28:10 +02:00
|
|
|
import { ApiTokenType } from '../types/models/api-token';
|
2021-04-22 10:07:10 +02:00
|
|
|
import { IUnleashConfig } from '../types/option';
|
2021-03-29 19:58:11 +02:00
|
|
|
|
2021-09-15 20:28:10 +02:00
|
|
|
const isClientApi = ({ path }) => {
|
|
|
|
return path && path.startsWith('/api/client');
|
|
|
|
};
|
|
|
|
|
2022-08-16 15:33:33 +02:00
|
|
|
const isProxyApi = ({ path }) => {
|
|
|
|
return path && path.startsWith('/api/frontend');
|
|
|
|
};
|
|
|
|
|
2022-06-17 09:00:13 +02:00
|
|
|
export const TOKEN_TYPE_ERROR_MESSAGE =
|
2022-08-16 15:33:33 +02:00
|
|
|
'invalid token: expected a different token type for this endpoint';
|
2022-06-17 09:00:13 +02:00
|
|
|
|
2021-03-29 19:58:11 +02:00
|
|
|
const apiAccessMiddleware = (
|
2021-04-22 10:07:10 +02:00
|
|
|
{
|
|
|
|
getLogger,
|
|
|
|
authentication,
|
2022-08-16 15:33:33 +02:00
|
|
|
experimental,
|
|
|
|
}: Pick<IUnleashConfig, 'getLogger' | 'authentication' | 'experimental'>,
|
2021-03-29 19:58:11 +02:00
|
|
|
{ apiTokenService }: any,
|
|
|
|
): any => {
|
2021-04-22 10:07:10 +02:00
|
|
|
const logger = getLogger('/middleware/api-token.ts');
|
2021-09-15 20:28:10 +02:00
|
|
|
logger.debug('Enabling api-token middleware');
|
2021-03-29 19:58:11 +02:00
|
|
|
|
2021-04-22 10:07:10 +02:00
|
|
|
if (!authentication.enableApiToken) {
|
2021-03-29 19:58:11 +02:00
|
|
|
return (req, res, next) => next();
|
|
|
|
}
|
|
|
|
|
|
|
|
return (req, res, next) => {
|
2021-09-15 20:28:10 +02:00
|
|
|
if (req.user) {
|
2021-03-29 19:58:11 +02:00
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2021-04-22 23:40:52 +02:00
|
|
|
const apiToken = req.header('authorization');
|
|
|
|
const apiUser = apiTokenService.getUserForToken(apiToken);
|
2022-08-18 10:20:51 +02:00
|
|
|
const { CLIENT, FRONTEND } = ApiTokenType;
|
2022-06-17 09:00:13 +02:00
|
|
|
|
2021-04-22 23:40:52 +02:00
|
|
|
if (apiUser) {
|
2022-08-16 15:33:33 +02:00
|
|
|
if (
|
|
|
|
(apiUser.type === CLIENT && !isClientApi(req)) ||
|
2022-08-18 10:20:51 +02:00
|
|
|
(apiUser.type === FRONTEND && !isProxyApi(req)) ||
|
2022-08-26 08:22:42 +02:00
|
|
|
(apiUser.type === FRONTEND &&
|
|
|
|
!experimental.flags.embedProxy)
|
2022-08-16 15:33:33 +02:00
|
|
|
) {
|
2022-06-17 09:00:13 +02:00
|
|
|
res.status(403).send({ message: TOKEN_TYPE_ERROR_MESSAGE });
|
|
|
|
return;
|
2021-09-15 20:28:10 +02:00
|
|
|
}
|
2021-04-22 23:40:52 +02:00
|
|
|
req.user = apiUser;
|
2021-03-29 19:58:11 +02:00
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
logger.error(error);
|
|
|
|
}
|
|
|
|
|
2022-06-17 09:00:13 +02:00
|
|
|
next();
|
2021-03-29 19:58:11 +02:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default apiAccessMiddleware;
|