All files / src/lib/middleware api-token-middleware.ts

95.65% Statements 22/23
87.5% Branches 7/8
100% Functions 4/4
95.45% Lines 21/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47  62x     62x 11x     62x             27x 27x   27x 1x     26x 51x       51x 51x 51x 49x 11x 1x   10x     2x     50x       62x 62x  
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { ApiTokenType } from '../types/models/api-token';
import { IUnleashConfig } from '../types/option';
 
const isClientApi = ({ path }) => {
    return path && path.startsWith('/api/client');
};
 
const apiAccessMiddleware = (
    {
        getLogger,
        authentication,
    }: Pick<IUnleashConfig, 'getLogger' | 'authentication'>,
    { apiTokenService }: any,
): any => {
    const logger = getLogger('/middleware/api-token.ts');
    logger.debug('Enabling api-token middleware');
 
    if (!authentication.enableApiToken) {
        return (req, res, next) => next();
    }
 
    return (req, res, next) => {
        Iif (req.user) {
            return next();
        }
 
        try {
            const apiToken = req.header('authorization');
            const apiUser = apiTokenService.getUserForToken(apiToken);
            if (apiUser) {
                if (apiUser.type === ApiTokenType.CLIENT && !isClientApi(req)) {
                    return res.sendStatus(403);
                }
                req.user = apiUser;
            }
        } catch (error) {
            logger.error(error);
        }
 
        return next();
    };
};
 
module.exports = apiAccessMiddleware;
export default apiAccessMiddleware;