mirror of
https://github.com/apricote/Listory.git
synced 2026-02-07 02:07:03 +00:00
feat: add optional basic auth for metrics endpoint
This commit is contained in:
parent
a6097204c7
commit
879c6a62e2
7 changed files with 92 additions and 3 deletions
36
src/metrics/metrics-auth.middleware.ts
Normal file
36
src/metrics/metrics-auth.middleware.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import {
|
||||
Injectable,
|
||||
NestMiddleware,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { IncomingMessage } from "http";
|
||||
|
||||
@Injectable()
|
||||
export class MetricsAuthMiddleware implements NestMiddleware {
|
||||
private readonly expectedHeaderValue: string;
|
||||
|
||||
constructor(config: ConfigService) {
|
||||
const username = config.get<string>("PROMETHEUS_BASIC_AUTH_USERNAME");
|
||||
const password = config.get<string>("PROMETHEUS_BASIC_AUTH_PASSWORD");
|
||||
|
||||
this.expectedHeaderValue = MetricsAuthMiddleware.buildHeaderValue(
|
||||
username,
|
||||
password
|
||||
);
|
||||
}
|
||||
|
||||
private static buildHeaderValue(username: string, password: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
|
||||
}
|
||||
|
||||
use(req: IncomingMessage, res: any, next: () => void) {
|
||||
const header = req.headers?.authorization;
|
||||
|
||||
if (header !== this.expectedHeaderValue) {
|
||||
throw new UnauthorizedException("MetricsBasicAuthNotMatching");
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue