Skip to content

Commit

Permalink
feat: add config validation util.
Browse files Browse the repository at this point in the history
  • Loading branch information
maximilianmikus committed Dec 11, 2023
1 parent 4d0b413 commit f4b2659
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 23 deletions.
25 changes: 2 additions & 23 deletions src/runtime/server/lib/oauth/oidc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
/**
Expand Down Expand Up @@ -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<OAuthOidcConfig>) {
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
Expand Down
27 changes: 27 additions & 0 deletions src/runtime/server/utils/config.ts
Original file line number Diff line number Diff line change
@@ -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 }
}

0 comments on commit f4b2659

Please sign in to comment.