This repository has been archived on 2024-06-14. You can view files and clone it, but cannot push or open issues or pull requests.
oauth2-provider/src/middleware.ts

50 lines
1.6 KiB
TypeScript

import { Request } from 'express';
import { AccessDenied } from './model/error';
import wrap from './utils/wrap';
export const middleware = wrap(async function (req: Request, res, next) {
req.oauth2.logger.debug('Parsing bearer token');
let token = null;
// Look for token in header
if (req.headers.authorization) {
const pieces = req.headers.authorization.split(' ', 2);
// Check authorization header
if (!pieces || pieces.length !== 2) {
throw new AccessDenied('Wrong authorization header');
}
// Only bearer auth is supported
if (pieces[0].toLowerCase() !== 'bearer') {
throw new AccessDenied('Unsupported authorization method in header');
}
token = pieces[1];
req.oauth2.logger.debug(
'Bearer token parsed from authorization header:',
token
);
} else if (req.query?.access_token) {
token = req.query.access_token;
req.oauth2.logger.debug('Bearer token parsed from query params:', token);
} else if (req.body?.access_token) {
token = req.body.access_token;
req.oauth2.logger.debug('Bearer token parsed from body params:', token);
} else {
throw new AccessDenied('Bearer token not found');
}
// Try to fetch access token
const object = await req.oauth2.model.accessToken.fetchByToken(token);
if (!object) {
throw new AccessDenied('Token not found or has expired');
} else if (!req.oauth2.model.accessToken.checkTTL(object)) {
throw new AccessDenied('Token is expired');
} else {
res.locals.accessToken = object;
req.oauth2.logger.debug('AccessToken fetched', object);
next();
}
});