-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathpat-middleware.ts
38 lines (35 loc) · 1.26 KB
/
pat-middleware.ts
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
import type { IUnleashConfig } from '../types';
import type { IAuthRequest } from '../routes/unleash-types';
import NotFoundError from '../error/notfound-error';
import type { AccountService } from '../services/account-service';
const patMiddleware = (
{ getLogger }: Pick<IUnleashConfig, 'getLogger'>,
{ accountService }: { accountService: AccountService },
): 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:')) {
const user =
await accountService.getAccountByPersonalAccessToken(
apiToken,
);
req.user = user;
accountService.addPATSeen(apiToken);
}
} catch (error) {
if (error instanceof NotFoundError) {
logger.warn(
'Tried to use a PAT token for user that no longer existed',
error,
);
} else {
logger.error(error);
}
}
next();
};
};
export default patMiddleware;