-
Notifications
You must be signed in to change notification settings - Fork 70
/
authenticate-swagger.middleware.ts
88 lines (82 loc) · 2.6 KB
/
authenticate-swagger.middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright (c) 2023 Sourcefuse Technologies
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {
Context,
globalInterceptor,
inject,
InvocationResult,
Provider,
ValueOrPromise,
} from '@loopback/core';
import {Request, RequestContext} from '@loopback/rest';
import {
RestExplorerBindings,
RestExplorerConfig,
} from '@loopback/rest-explorer';
import {MiddlewareContext, Middleware} from '@loopback/express';
import {SwaggerAuthenticationBindings} from '../keys';
import {HttpAuthenticationVerifier} from '../types';
import {STATUS_CODE} from '../../../enums';
@globalInterceptor('auth', {tags: {name: 'AuthenticateSwaggerMiddleware'}})
export class AuthenticateSwaggerMiddlewareInterceptor
implements Provider<Middleware>
{
constructor(
@inject(SwaggerAuthenticationBindings.VERIFIER)
private readonly verifier: HttpAuthenticationVerifier,
@inject(RestExplorerBindings.CONFIG)
private readonly config: RestExplorerConfig,
) {}
value() {
return this.intercept.bind(this);
}
async intercept(
context: MiddlewareContext,
next: () => ValueOrPromise<InvocationResult>,
) {
let request, response;
if (this.isRequestContext(context.parent)) {
request = context.parent.request;
response = context.parent.response;
}
if (request && response && this.isOpenAPISpecRequest(request)) {
const {username, password} = this.decodeHeader(request);
const verified = this.verifier(username, password);
if (!verified) {
response
.status(STATUS_CODE.UNAUTHORISED)
.setHeader('WWW-Authenticate', 'Basic realm="Node"');
response.end('Unauthorized');
return null;
}
}
return next();
}
private decodeHeader(request: Request) {
const header = request.headers.authorization ?? ''; // get the auth header
const token = header.split(/\s+/).pop() ?? ''; // and the encoded auth token
const auth = Buffer.from(token, 'base64').toString(); // convert from base64
const parts = auth.split(/:/); // split on colon
const username = parts.shift(); // username is first
const password = parts.join(':');
return {
username,
password,
};
}
private isOpenAPISpecRequest(request: Request) {
const swaggerUrl = `${this.config.path}/openapi.json`;
if (request.url.includes(swaggerUrl)) {
return true;
}
return false;
}
private isRequestContext(context?: Context): context is RequestContext {
return !!(
(context as RequestContext).request &&
(context as RequestContext).response
);
}
}