oneuptime/CommonServer/Middleware/ClusterKeyAuthorization.ts

51 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-11-08 15:24:58 +00:00
import { ClusterKey as ONEUPTIME_SECRET } from '../Config';
2022-04-03 20:54:06 +00:00
import {
ExpressRequest,
ExpressResponse,
NextFunction,
2022-04-10 21:04:51 +00:00
} from '../Utils/Express';
2022-04-03 20:54:06 +00:00
2022-05-10 19:26:44 +00:00
import Response from '../Utils/Response';
2022-04-10 21:57:14 +00:00
import BadDataException from 'Common/Types/Exception/BadDataException';
2022-04-22 14:33:21 +00:00
import ObjectID from 'Common/Types/ObjectID';
2022-04-03 20:54:06 +00:00
export default class ClusterKeyAuthorization {
2022-05-09 20:30:55 +00:00
public static async isAuthorizedServiceMiddleware(
2022-04-03 20:54:06 +00:00
req: ExpressRequest,
res: ExpressResponse,
next: NextFunction
2022-04-13 15:28:22 +00:00
): Promise<void> {
2022-04-22 14:33:21 +00:00
let clusterKey: ObjectID;
2022-04-03 20:54:06 +00:00
2022-04-20 21:08:52 +00:00
if (req.params && req.params['clusterKey']) {
2022-04-22 14:33:21 +00:00
clusterKey = new ObjectID(req.params['clusterKey']);
2022-04-20 21:08:52 +00:00
} else if (req.query && req.query['clusterKey']) {
2022-04-22 14:33:21 +00:00
clusterKey = new ObjectID(req.query['clusterKey'] as string);
} else if (req.headers && req.headers['clusterkey']) {
2022-04-15 22:14:01 +00:00
// Header keys are automatically transformed to lowercase
2022-04-22 14:33:21 +00:00
clusterKey = new ObjectID(req.headers['clusterkey'] as string);
2022-04-03 20:54:06 +00:00
} else if (req.body && req.body.clusterKey) {
2022-04-22 14:33:21 +00:00
clusterKey = new ObjectID(req.body.clusterKey);
2022-04-03 20:54:06 +00:00
} else {
2022-05-10 19:26:44 +00:00
return Response.sendErrorResponse(
2022-04-03 20:54:06 +00:00
req,
res,
new BadDataException('Cluster key not found.')
);
}
2022-11-10 20:50:39 +00:00
const isAuthorized: boolean =
clusterKey.toString() === ONEUPTIME_SECRET.toString();
2022-04-03 20:54:06 +00:00
if (!isAuthorized) {
2022-05-10 19:26:44 +00:00
return Response.sendErrorResponse(
2022-04-03 20:54:06 +00:00
req,
res,
new BadDataException('Invalid cluster key provided')
);
}
return next();
}
}