@@ -17,11 +17,13 @@ const defaultSecurityHandler = (
17
17
type SecuritySchemesMap = {
18
18
[ key : string ] : OpenAPIV3 . ReferenceObject | OpenAPIV3 . SecuritySchemeObject ;
19
19
} ;
20
+
20
21
interface SecurityHandlerResult {
21
22
success : boolean ;
22
23
status ?: number ;
23
24
error ?: string ;
24
25
}
26
+
25
27
export function security (
26
28
apiDoc : OpenAPIV3 . Document ,
27
29
securityHandlers : SecurityHandlers ,
@@ -62,50 +64,19 @@ export function security(
62
64
63
65
// TODO handle AND'd and OR'd security
64
66
// This assumes OR only! i.e. at least one security passed authentication
65
- let firstError : SecurityHandlerResult = null ;
66
- let success = false ;
67
-
68
- function checkErrorWithOr ( res ) {
69
- return res . forEach ( ( r ) => {
70
- if ( r . success ) {
71
- success = true ;
72
- } else if ( ! firstError ) {
73
- firstError = r ;
74
- }
75
- } ) ;
76
- }
77
-
78
- function checkErrorsWithAnd ( res ) {
79
- let allSuccess = false ;
80
-
81
- res . forEach ( ( r ) => {
82
- if ( ! r . success ) {
83
- allSuccess = false ;
84
- if ( ! firstError ) {
85
- firstError = r ;
86
- }
87
- } else if ( ! firstError ) {
88
- allSuccess = true ;
89
- }
90
- } ) ;
91
-
92
- if ( allSuccess ) {
93
- success = true ;
94
- }
95
- }
96
-
97
- results . forEach ( ( result ) => {
98
- if ( Array . isArray ( result ) && result . length > 1 ) {
99
- checkErrorsWithAnd ( result ) ;
100
- } else {
101
- checkErrorWithOr ( result ) ;
67
+ const success = results . some ( result => Array . isArray ( result ) ? ! result . some ( it => ! it . success ) : result . success ) ;
68
+ const errors = results . map ( result => {
69
+ if ( Array . isArray ( result ) ) {
70
+ return result . map ( it => it ) . filter ( it => ! it . success )
102
71
}
103
- } ) ;
72
+ return [ result ] . filter ( it => ! it . success )
73
+ } )
104
74
105
75
if ( success ) {
106
76
next ( ) ;
107
77
} else {
108
- throw firstError ;
78
+ const allErrors = errors . flatMap ( it => [ ...it ] ) ;
79
+ throw allErrors . find ( Boolean )
109
80
}
110
81
} catch ( e ) {
111
82
const message = e ?. error ?. message || 'unauthorized' ;
@@ -129,6 +100,7 @@ class SecuritySchemes {
129
100
private securitySchemes : SecuritySchemesMap ;
130
101
private securityHandlers : SecurityHandlers ;
131
102
private securities : OpenAPIV3 . SecurityRequirementObject [ ] ;
103
+
132
104
constructor (
133
105
securitySchemes : SecuritySchemesMap ,
134
106
securityHandlers : SecurityHandlers ,
@@ -213,6 +185,7 @@ class AuthValidator {
213
185
private scheme ;
214
186
private path : string ;
215
187
private scopes : string [ ] ;
188
+
216
189
constructor ( req : OpenApiRequest , scheme , scopes : string [ ] = [ ] ) {
217
190
const openapi = < OpenApiRequestMetadata > req . openapi ;
218
191
this . req = req ;
0 commit comments