Skip to content

Commit f4b2659

Browse files
feat: add config validation util.
1 parent 4d0b413 commit f4b2659

File tree

2 files changed

+29
-23
lines changed

2 files changed

+29
-23
lines changed

src/runtime/server/lib/oauth/oidc.ts

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { defu } from 'defu'
66
import { useRuntimeConfig } from '#imports'
77
import type { OAuthConfig } from '#auth-utils'
88
import { type OAuthChecks, checks } from '../../utils/security'
9+
import { validateConfig } from '../../utils/config'
910

1011
export interface OAuthOidcConfig {
1112
/**
@@ -78,35 +79,13 @@ export interface OAuthOidcConfig {
7879
checks?: OAuthChecks[]
7980
}
8081

81-
function validateConfig(config: any) {
82-
const requiredConfigKeys = ['clientId', 'clientSecret', 'authorizationUrl', 'tokenUrl', 'userinfoUrl', 'redirectUri', 'responseType']
83-
const missingConfigKeys: string[] = []
84-
requiredConfigKeys.forEach(key => {
85-
if (!config[key]) {
86-
missingConfigKeys.push(key)
87-
}
88-
})
89-
if (missingConfigKeys.length) {
90-
const error = createError({
91-
statusCode: 500,
92-
message: `Missing config keys: ${missingConfigKeys.join(', ')}`
93-
})
94-
95-
return {
96-
valid: false,
97-
error
98-
}
99-
}
100-
return { valid: true }
101-
}
102-
10382
export function oidcEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthOidcConfig>) {
10483
return eventHandler(async (event: H3Event) => {
10584
// @ts-ignore
10685
config = defu(config, useRuntimeConfig(event).oauth?.oidc) as OAuthOidcConfig
10786
const { code } = getQuery(event)
10887

109-
const validationResult = validateConfig(config)
88+
const validationResult = validateConfig(config, ['clientId', 'clientSecret', 'authorizationUrl', 'tokenUrl', 'userinfoUrl', 'redirectUri', 'responseType'])
11089

11190
if (!validationResult.valid && validationResult.error) {
11291
if (!onError) throw validationResult.error

src/runtime/server/utils/config.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import type { H3Error } from 'h3'
2+
3+
export type configValidationResult = {
4+
valid: boolean,
5+
error?: H3Error
6+
}
7+
8+
export function validateConfig(config: any, requiredKeys: string[]): configValidationResult {
9+
const missingKeys: string[] = []
10+
requiredKeys.forEach(key => {
11+
if (!config[key]) {
12+
missingKeys.push(key)
13+
}
14+
})
15+
if (missingKeys.length) {
16+
const error = createError({
17+
statusCode: 500,
18+
message: `Missing config keys: ${missingKeys.join(', ')}. Please pass the required parameters either as env variables or as part of the config parameter.`
19+
})
20+
21+
return {
22+
valid: false,
23+
error
24+
}
25+
}
26+
return { valid: true }
27+
}

0 commit comments

Comments
 (0)