1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-06 00:07:44 +01:00
unleash.unleash/src/lib/middleware/api-token-middleware.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-03-29 19:58:11 +02:00
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { ApiTokenType } from '../types/models/api-token';
import { IUnleashConfig } from '../types/option';
2021-03-29 19:58:11 +02:00
const isClientApi = ({ path }) => {
return path && path.startsWith('/api/client');
};
export const TOKEN_TYPE_ERROR_MESSAGE =
'invalid token: expected an admin token but got a client token instead';
2021-03-29 19:58:11 +02:00
const apiAccessMiddleware = (
{
getLogger,
authentication,
}: Pick<IUnleashConfig, 'getLogger' | 'authentication'>,
2021-03-29 19:58:11 +02:00
{ apiTokenService }: any,
): any => {
const logger = getLogger('/middleware/api-token.ts');
logger.debug('Enabling api-token middleware');
2021-03-29 19:58:11 +02:00
if (!authentication.enableApiToken) {
2021-03-29 19:58:11 +02:00
return (req, res, next) => next();
}
return (req, res, next) => {
if (req.user) {
2021-03-29 19:58:11 +02:00
return next();
}
try {
const apiToken = req.header('authorization');
const apiUser = apiTokenService.getUserForToken(apiToken);
if (apiUser) {
if (apiUser.type === ApiTokenType.CLIENT && !isClientApi(req)) {
res.status(403).send({ message: TOKEN_TYPE_ERROR_MESSAGE });
return;
}
req.user = apiUser;
2021-03-29 19:58:11 +02:00
}
} catch (error) {
logger.error(error);
}
next();
2021-03-29 19:58:11 +02:00
};
};
export default apiAccessMiddleware;