Skip to content

Commit 307cddd

Browse files
committed
throw provided exception example
1 parent ac16300 commit 307cddd

File tree

3 files changed

+74
-11
lines changed

3 files changed

+74
-11
lines changed

src/middlewares/openapi.security.ts

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -138,16 +138,10 @@ class SecuritySchemes {
138138
}
139139
return Promise.all(
140140
Object.keys(s).map(async (securityKey) => {
141-
var _a, _b, _c;
141+
142142
try {
143143
const scheme = this.securitySchemes[securityKey];
144-
const handler =
145-
(_b =
146-
(_a = this.securityHandlers) === null || _a === void 0
147-
? void 0
148-
: _a[securityKey]) !== null && _b !== void 0
149-
? _b
150-
: fallbackHandler;
144+
const handler = this.securityHandlers?.[securityKey] ?? fallbackHandler;
151145
const scopesTmp = s[securityKey];
152146
const scopes = Array.isArray(scopesTmp) ? scopesTmp : [];
153147
if (!scheme) {
@@ -180,7 +174,7 @@ class SecuritySchemes {
180174
} catch (e) {
181175
return {
182176
success: false,
183-
status: (_c = e.status) !== null && _c !== void 0 ? _c : 401,
177+
status: e.status ?? 401,
184178
error: e,
185179
};
186180
}

test/resources/security.yaml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ paths:
9090
"401":
9191
description: unauthorized
9292

93+
9394
/multi_auth:
9495
get:
9596
security:
@@ -127,6 +128,18 @@ paths:
127128
"401":
128129
description: unauthorized
129130

131+
/test_key:
132+
get:
133+
security:
134+
- testKey: []
135+
description: Test authentication
136+
responses:
137+
"200":
138+
description: Some html content
139+
content:
140+
text/html:
141+
schema:
142+
type: string
130143
components:
131144
securitySchemes:
132145
BasicAuth:
@@ -156,3 +169,7 @@ components:
156169
read: Grants read access
157170
write: Grants write access
158171
admin: Grants access to admin operations
172+
testKey:
173+
type: apiKey
174+
name: key
175+
in: query

test/security.handlers.spec.ts

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
OpenApiValidatorOpts,
88
ValidateSecurityOpts,
99
OpenAPIV3,
10-
SecurityHandlers,
10+
HttpError,
1111
} from '../src/framework/types';
1212
import { AppWithServer } from './common/app.common';
1313

@@ -16,13 +16,37 @@ import { AppWithServer } from './common/app.common';
1616
describe('security.handlers', () => {
1717
let app: AppWithServer;
1818
let basePath: string;
19+
20+
class MyForbiddenError extends HttpError {
21+
constructor(message: string) {
22+
super({
23+
status: 403,
24+
path: '/test_key',
25+
name: 'MyForbiddenError',
26+
message: message,
27+
});
28+
}
29+
}
30+
31+
class MyUserError extends Error {
32+
}
33+
1934
const eovConf: OpenApiValidatorOpts = {
2035
apiSpec: path.join('test', 'resources', 'security.yaml'),
2136
validateSecurity: {
2237
handlers: {
2338
ApiKeyAuth: (req, scopes, schema) => {
2439
throw Error('custom api key handler failed');
2540
},
41+
testKey: async (req, scopes, schema) => {
42+
let key = req.query.key;
43+
console.log('-------key');
44+
if (key !== "ok") {
45+
throw new MyForbiddenError("Wrong key value");
46+
}
47+
48+
return true;
49+
},
2650
},
2751
},
2852
};
@@ -44,8 +68,30 @@ describe('security.handlers', () => {
4468
.get(`/api_key_or_anonymous`, (req, res) =>{
4569
res.json({ logged_in: true })
4670
})
47-
.get('/no_security', (req, res) => {res.json({ logged_in: true })}),
71+
.get('/no_security', (req, res) => {res.json({ logged_in: true })})
72+
.get("/test_key", function(req, res, next) {
73+
if (req.query.key === "ok") {
74+
console.log('-------key ok');
75+
throw new MyUserError("Everything is fine");
76+
} else {
77+
console.log('-------key wrong');
78+
throw new MyForbiddenError("Wrong key value");
79+
}
80+
}),
4881
);
82+
app.use((err, req, res, next) => {
83+
if (err instanceof MyUserError) {
84+
// OK
85+
res.status(200);
86+
res.send(`<h1>Error matches to MyUserError</h1>`);
87+
} else if (err instanceof MyForbiddenError) {
88+
// FAIL: YOU NEVER GET HERE
89+
res.status(403);
90+
res.send(`<h1>Error matches to MyForbiddenError</h1>`);
91+
} else {
92+
res.send(`<h1>Unknown error</h1>` + JSON.stringify(err));
93+
}
94+
});
4995
});
5096

5197
after(() => {
@@ -55,6 +101,12 @@ describe('security.handlers', () => {
55101
it('should return 200 if no security', async () =>
56102
request(app).get(`${basePath}/no_security`).expect(200));
57103

104+
it('should return 200 if test_key handler returns true', async () =>
105+
request(app).get(`${basePath}/test_key?key=ok`).expect(200));
106+
107+
it('should return 403 if test_key handler throws exception', async () =>
108+
request(app).get(`${basePath}/test_key?key=wrong`).expect(403));
109+
58110
it('should return 401 if apikey handler throws exception', async () =>
59111
request(app)
60112
.get(`${basePath}/api_key`)

0 commit comments

Comments
 (0)