🔒 add app access token middleware
Create a middleware app access token, so that all requests must include `access_token` in the header with a value equal to API_KEY in the .env file. If not, a `403 Forbidden` error will be returned.
This commit is contained in:
@ -1,10 +1,14 @@
|
|||||||
|
import { appAccessTokenMiddleware } from "./middleware/global/appAccessToken.middleware";
|
||||||
import { validateEnv } from "./utils/startups/validateEnv";
|
import { validateEnv } from "./utils/startups/validateEnv";
|
||||||
validateEnv();
|
validateEnv();
|
||||||
|
|
||||||
const { Elysia } = await import("elysia");
|
const { Elysia } = await import("elysia");
|
||||||
const { routes } = await import("./routes");
|
const { routes } = await import("./routes");
|
||||||
|
|
||||||
const app = new Elysia().use(routes).listen(process.env.APP_PORT || 3000);
|
const app = new Elysia()
|
||||||
|
.use(appAccessTokenMiddleware())
|
||||||
|
.use(routes)
|
||||||
|
.listen(process.env.APP_PORT || 3000);
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
|
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
|
||||||
|
|||||||
12
src/middleware/global/appAccessToken.middleware.ts
Normal file
12
src/middleware/global/appAccessToken.middleware.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
import Elysia, { Context } from "elysia";
|
||||||
|
import { returnErrorResponse } from "../../helpers/callback/httpResponse";
|
||||||
|
|
||||||
|
export const appAccessTokenMiddleware = () =>
|
||||||
|
new Elysia().onRequest(({ request, set }) => {
|
||||||
|
const headerToken = request.headers.get("access_token");
|
||||||
|
const storedToken = process.env.API_KEY;
|
||||||
|
|
||||||
|
if (headerToken !== storedToken) {
|
||||||
|
return returnErrorResponse(set, 403, "Unauthorized");
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user