From 230df5548da664f8c13ef4e6ad8ae845d24844f8 Mon Sep 17 00:00:00 2001 From: Deepak Prabhakara Date: Sat, 8 Jan 2022 01:00:06 +0000 Subject: [PATCH] validate API key for config APIs (#58) --- lib/utils.ts | 16 ++++++++++++++++ npm/src/controller/utils.ts | 13 ------------- pages/api/oauth/userinfo.ts | 11 +---------- pages/api/v1/saml/config.ts | 12 ++++++++---- 4 files changed, 25 insertions(+), 27 deletions(-) create mode 100644 lib/utils.ts diff --git a/lib/utils.ts b/lib/utils.ts new file mode 100644 index 000000000..208d93ae7 --- /dev/null +++ b/lib/utils.ts @@ -0,0 +1,16 @@ +import { NextApiRequest } from 'next'; +import env from '@lib/env'; + +export const validateApiKey = (token) => { + return env.apiKeys.includes(token); +}; + +export const extractAuthToken = (req: NextApiRequest) => { + const authHeader = req.headers['authorization']; + const parts = (authHeader || '').split(' '); + if (parts.length > 1) { + return parts[1]; + } + + return null; +}; diff --git a/npm/src/controller/utils.ts b/npm/src/controller/utils.ts index 1ca12fbcc..e5fd971d8 100644 --- a/npm/src/controller/utils.ts +++ b/npm/src/controller/utils.ts @@ -1,16 +1,3 @@ -import { Request } from 'express'; - -export const extractAuthToken = (req: Request): string | null => { - const authHeader = req.get('authorization'); - const parts = (authHeader || '').split(' '); - - if (parts.length > 1) { - return parts[1]; - } - - return null; -}; - export enum IndexNames { EntityID = 'entityID', TenantProduct = 'tenantProduct', diff --git a/pages/api/oauth/userinfo.ts b/pages/api/oauth/userinfo.ts index 156ecd5d6..1000c59ce 100644 --- a/pages/api/oauth/userinfo.ts +++ b/pages/api/oauth/userinfo.ts @@ -1,16 +1,7 @@ import { NextApiRequest, NextApiResponse } from 'next'; import jackson from '@lib/jackson'; - -const extractAuthToken = (req: NextApiRequest) => { - const authHeader = req.headers['authorization']; - const parts = (authHeader || '').split(' '); - if (parts.length > 1) { - return parts[1]; - } - - return null; -}; +import { extractAuthToken } from '@lib/utils'; export default async function handler(req: NextApiRequest, res: NextApiResponse) { try { diff --git a/pages/api/v1/saml/config.ts b/pages/api/v1/saml/config.ts index 4abe59ed7..3f1bbd64b 100644 --- a/pages/api/v1/saml/config.ts +++ b/pages/api/v1/saml/config.ts @@ -1,12 +1,16 @@ import { NextApiRequest, NextApiResponse } from 'next'; import jackson from '@lib/jackson'; +import { extractAuthToken, validateApiKey } from '@lib/utils'; -export default async function handler( - req: NextApiRequest, - res: NextApiResponse -) { +export default async function handler(req: NextApiRequest, res: NextApiResponse) { try { + const apiKey = extractAuthToken(req); + if (!validateApiKey(apiKey)) { + res.status(401).json({ message: 'Unauthorized' }); + return; + } + const { apiController } = await jackson(); if (req.method === 'POST') { res.json(await apiController.config(req.body));