From f4b26595342da3a48f53f0af1eea41c725864bc4 Mon Sep 17 00:00:00 2001 From: Maximilian Mikus Date: Thu, 30 Nov 2023 10:05:48 +0100 Subject: [PATCH] feat: add config validation util. --- src/runtime/server/lib/oauth/oidc.ts | 25 ++----------------------- src/runtime/server/utils/config.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 23 deletions(-) create mode 100644 src/runtime/server/utils/config.ts diff --git a/src/runtime/server/lib/oauth/oidc.ts b/src/runtime/server/lib/oauth/oidc.ts index 16ea3a1e..425202a6 100644 --- a/src/runtime/server/lib/oauth/oidc.ts +++ b/src/runtime/server/lib/oauth/oidc.ts @@ -6,6 +6,7 @@ import { defu } from 'defu' import { useRuntimeConfig } from '#imports' import type { OAuthConfig } from '#auth-utils' import { type OAuthChecks, checks } from '../../utils/security' +import { validateConfig } from '../../utils/config' export interface OAuthOidcConfig { /** @@ -78,35 +79,13 @@ export interface OAuthOidcConfig { checks?: OAuthChecks[] } -function validateConfig(config: any) { - const requiredConfigKeys = ['clientId', 'clientSecret', 'authorizationUrl', 'tokenUrl', 'userinfoUrl', 'redirectUri', 'responseType'] - const missingConfigKeys: string[] = [] - requiredConfigKeys.forEach(key => { - if (!config[key]) { - missingConfigKeys.push(key) - } - }) - if (missingConfigKeys.length) { - const error = createError({ - statusCode: 500, - message: `Missing config keys: ${missingConfigKeys.join(', ')}` - }) - - return { - valid: false, - error - } - } - return { valid: true } -} - export function oidcEventHandler({ config, onSuccess, onError }: OAuthConfig) { return eventHandler(async (event: H3Event) => { // @ts-ignore config = defu(config, useRuntimeConfig(event).oauth?.oidc) as OAuthOidcConfig const { code } = getQuery(event) - const validationResult = validateConfig(config) + const validationResult = validateConfig(config, ['clientId', 'clientSecret', 'authorizationUrl', 'tokenUrl', 'userinfoUrl', 'redirectUri', 'responseType']) if (!validationResult.valid && validationResult.error) { if (!onError) throw validationResult.error diff --git a/src/runtime/server/utils/config.ts b/src/runtime/server/utils/config.ts new file mode 100644 index 00000000..1c8d3845 --- /dev/null +++ b/src/runtime/server/utils/config.ts @@ -0,0 +1,27 @@ +import type { H3Error } from 'h3' + +export type configValidationResult = { + valid: boolean, + error?: H3Error +} + +export function validateConfig(config: any, requiredKeys: string[]): configValidationResult { + const missingKeys: string[] = [] + requiredKeys.forEach(key => { + if (!config[key]) { + missingKeys.push(key) + } + }) + if (missingKeys.length) { + const error = createError({ + statusCode: 500, + message: `Missing config keys: ${missingKeys.join(', ')}. Please pass the required parameters either as env variables or as part of the config parameter.` + }) + + return { + valid: false, + error + } + } + return { valid: true } +}