forked from Yara724/api
Tidied up the project
This commit is contained in:
58
src/main.ts
58
src/main.ts
@@ -1,8 +1,8 @@
|
||||
import { NestFactory } from "@nestjs/core";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
|
||||
import * as basicAuth from "express-basic-auth";
|
||||
import { AppModule } from "./app.module";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
||||
@@ -15,15 +15,46 @@ async function bootstrap() {
|
||||
allowedHeaders: "Content-Type, Authorization",
|
||||
});
|
||||
|
||||
app.use(
|
||||
["/docs"],
|
||||
basicAuth({
|
||||
challenge: true,
|
||||
users: {
|
||||
[process.env.SWAGGER_USER]: process.env.SWAGGER_PASSWORD,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const configService = app.get(ConfigService);
|
||||
|
||||
const isDevelopment = configService.get<string>("NODE_ENV") === "development";
|
||||
|
||||
if (isDevelopment) {
|
||||
app.use("/docs", (req, res, next) => {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
const challenge = () => {
|
||||
res.setHeader("WWW-Authenticate", 'Basic realm="Swagger"');
|
||||
res.status(401).send("Unauthorized");
|
||||
};
|
||||
|
||||
if (!authHeader?.startsWith("Basic ")) {
|
||||
return challenge();
|
||||
}
|
||||
|
||||
try {
|
||||
const base64 = authHeader.split(" ")[1];
|
||||
const [username, ...rest] = Buffer.from(base64, "base64")
|
||||
.toString("utf8")
|
||||
.split(":");
|
||||
const password = rest.join(":");
|
||||
|
||||
const expectedUser = configService.get<string>("SWAGGER_USER", "");
|
||||
const expectedPassword = configService.get<string>(
|
||||
"SWAGGER_PASSWORD",
|
||||
"",
|
||||
);
|
||||
|
||||
if (username !== expectedUser || password !== expectedPassword) {
|
||||
return challenge();
|
||||
}
|
||||
|
||||
next();
|
||||
} catch {
|
||||
return challenge();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle("yara724-backend")
|
||||
@@ -33,11 +64,15 @@ async function bootstrap() {
|
||||
.addServer("http://localhost:9001")
|
||||
.addBearerAuth()
|
||||
.build();
|
||||
|
||||
const docs = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup("/docs", app, docs, {
|
||||
|
||||
SwaggerModule.setup("docs", app, docs, {
|
||||
swaggerOptions: {
|
||||
persistAuthorization: true,
|
||||
docExpansion: "none",
|
||||
ui: isDevelopment ? true : false,
|
||||
raw: isDevelopment ? true : false,
|
||||
tagsSorter: (a: string, b: string) => {
|
||||
const priority: Record<string, number> = {
|
||||
user: 0,
|
||||
@@ -50,6 +85,7 @@ async function bootstrap() {
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await app.listen(process.env.PORT);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user