2022-09-28 15:53:56 +02:00
|
|
|
import { IUnleashConfig } from '../types';
|
|
|
|
import { IAuthRequest } from '../routes/unleash-types';
|
2023-05-10 13:31:42 +02:00
|
|
|
import NotFoundError from '../error/notfound-error';
|
2022-09-28 15:53:56 +02:00
|
|
|
|
|
|
|
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
|
|
|
|
const patMiddleware = (
|
2022-10-31 10:38:30 +01:00
|
|
|
{ getLogger }: Pick<IUnleashConfig, 'getLogger'>,
|
2023-01-18 17:08:07 +01:00
|
|
|
{ accountService }: any,
|
2022-09-28 15:53:56 +02:00
|
|
|
): any => {
|
|
|
|
const logger = getLogger('/middleware/pat-middleware.ts');
|
|
|
|
logger.debug('Enabling PAT middleware');
|
|
|
|
|
|
|
|
return async (req: IAuthRequest, res, next) => {
|
|
|
|
try {
|
|
|
|
const apiToken = req.header('authorization');
|
|
|
|
if (apiToken?.startsWith('user:')) {
|
2023-01-18 17:08:07 +01:00
|
|
|
const user =
|
|
|
|
await accountService.getAccountByPersonalAccessToken(
|
|
|
|
apiToken,
|
|
|
|
);
|
2022-09-28 15:53:56 +02:00
|
|
|
req.user = user;
|
2023-01-18 17:08:07 +01:00
|
|
|
accountService.addPATSeen(apiToken);
|
2022-09-28 15:53:56 +02:00
|
|
|
}
|
|
|
|
} catch (error) {
|
2023-05-10 13:31:42 +02:00
|
|
|
if (error instanceof NotFoundError) {
|
|
|
|
logger.warn(
|
|
|
|
'Tried to use a PAT token for user that no longer existed',
|
|
|
|
error,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
logger.error(error);
|
|
|
|
}
|
2022-09-28 15:53:56 +02:00
|
|
|
}
|
|
|
|
next();
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default patMiddleware;
|