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');
|
|
|
|
};
|
|
|
|
|
2021-03-29 19:58:11 +02:00
|
|
|
const apiAccessMiddleware = (
|
2021-04-22 10:07:10 +02:00
|
|
|
{
|
|
|
|
getLogger,
|
|
|
|
authentication,
|
|
|
|
}: Pick<IUnleashConfig, 'getLogger' | 'authentication'>,
|
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);
|
|
|
|
if (apiUser) {
|
2021-09-15 20:28:10 +02:00
|
|
|
if (apiUser.type === ApiTokenType.CLIENT && !isClientApi(req)) {
|
|
|
|
return res.sendStatus(403);
|
|
|
|
}
|
2021-04-22 23:40:52 +02:00
|
|
|
req.user = apiUser;
|
2021-03-29 19:58:11 +02:00
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
logger.error(error);
|
|
|
|
}
|
|
|
|
|
|
|
|
return next();
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = apiAccessMiddleware;
|
|
|
|
export default apiAccessMiddleware;
|