Skip to content

Commit

Permalink
refactor: tweak the auth middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
SeanCassiere committed Jun 24, 2024
1 parent ee4b688 commit 131ddc3
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 23 deletions.
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Hono } from "hono";
import { cors } from "hono/cors";
import { compress } from "hono/compress";
import { csrf } from "hono/csrf";
import { etag } from "hono/etag";
import { secureHeaders } from "hono/secure-headers";
Expand All @@ -21,6 +22,7 @@ const packageJson = getPackageInfo();

const app = new Hono<ServerContext>();
app.use(cors({ origin: "*" }));
app.use(compress());
app.use(csrf());
app.use(etag());
app.use(logger());
Expand Down Expand Up @@ -60,7 +62,7 @@ app.get("/", (c) => {
});

if (env.FREEZE_DB_WRITES) {
console.warn(" ⚠️ ⚠️ ⚠️ ⚠️\n Database writes are currently frozen\n ⚠️ ⚠️ ⚠️ ⚠️\n");
console.warn("\n🚨 Database writes are currently frozen!!!\n");
}

transformOpenapiYmlDoc("v2", [openapiYmlVersioner(packageJson.version)]);
Expand Down
8 changes: 4 additions & 4 deletions src/routers/v2/logging/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { and, eq, lt } from "drizzle-orm";
import { db } from "@/config/db";
import { env } from "@/config/env";
import { logs as logsTable } from "@/config/db/schema";
import { parseSearchParams, serviceValidation } from "@/utils/server-helpers";
import { parseSearchParams, v2_serviceValidation } from "@/utils/server-helpers";
import { ENDPOINT_MESSAGES } from "@/utils/messages";
import { createDbId } from "@/utils/db";
import type { ServerContext } from "@/types/hono";
Expand All @@ -17,7 +17,7 @@ const app = new Hono<ServerContext>();
* @public
* Get all log entries
*/
app.get("/", serviceValidation, async (c) => {
app.get("/", v2_serviceValidation, async (c) => {
const service = c.var.service!;
const serviceId = service.id;

Expand Down Expand Up @@ -53,7 +53,7 @@ app.get("/", serviceValidation, async (c) => {
* @public
* Create a log entry
*/
app.post("/", serviceValidation, async (c) => {
app.post("/", v2_serviceValidation, async (c) => {
const service = c.var.service!;
const serviceId = service.id;

Expand Down Expand Up @@ -106,7 +106,7 @@ app.post("/", serviceValidation, async (c) => {
* @public
* Cleans log for a service for a specific number of months
*/
app.delete("/purge", serviceValidation, async (c) => {
app.delete("/purge", v2_serviceValidation, async (c) => {
if (env.FREEZE_DB_WRITES) {
c.status(503);
return c.json({ success: false, message: ENDPOINT_MESSAGES.DBWritesFrozen });
Expand Down
12 changes: 6 additions & 6 deletions src/routers/v2/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Hono } from "hono";

import { db } from "@/config/db";
import { createDbId } from "@/utils/db";
import { adminServiceValidation, parseSearchParams } from "@/utils/server-helpers";
import { v2_serviceValidation, adminServiceValidation, parseSearchParams } from "@/utils/server-helpers";
import { services as servicesTable } from "@/config/db/schema";
import type { ServerContext } from "@/types/hono";

Expand All @@ -22,7 +22,7 @@ const app = new Hono<ServerContext>();
* @private
* Get all services, only accessible by admins
*/
app.get("/", adminServiceValidation, async (c) => {
app.get("/", v2_serviceValidation, adminServiceValidation, async (c) => {
const searchQuery = parseSearchParams(c.req.url);
const searchResult = getServiceFiltersSchema.safeParse(searchQuery);

Expand All @@ -46,7 +46,7 @@ app.get("/", adminServiceValidation, async (c) => {
* @private
* Create a new service, only accessible by admins
*/
app.post("/", adminServiceValidation, async (c) => {
app.post("/", v2_serviceValidation, adminServiceValidation, async (c) => {
const body = await c.req.json();
const bodyResult = createServiceInputSchema.safeParse(body);

Expand Down Expand Up @@ -84,7 +84,7 @@ app.post("/", adminServiceValidation, async (c) => {
* @private
* Get a service by its ID, only accessible by admins
*/
app.get("/:service_id", adminServiceValidation, async (c) => {
app.get("/:service_id", v2_serviceValidation, adminServiceValidation, async (c) => {
const serviceId = c.req.param("service_id");

const service = await db.query.services.findFirst({
Expand All @@ -103,7 +103,7 @@ app.get("/:service_id", adminServiceValidation, async (c) => {
* @private
* Disable a service, only accessible by admins
*/
app.delete("/:service_id", adminServiceValidation, async (c) => {
app.delete("/:service_id", v2_serviceValidation, adminServiceValidation, async (c) => {
const reqServiceId = c.var.service!.id;
const serviceId = c.req.param("service_id");

Expand All @@ -122,7 +122,7 @@ app.delete("/:service_id", adminServiceValidation, async (c) => {
* @private
* Enable a service, only accessible by admins
*/
app.post("/:service_id/enable", adminServiceValidation, async (c) => {
app.post("/:service_id/enable", v2_serviceValidation, adminServiceValidation, async (c) => {
const serviceId = c.req.param("service_id");

await db.update(servicesTable).set({ isActive: true }).where(eq(servicesTable.id, serviceId)).execute();
Expand Down
22 changes: 10 additions & 12 deletions src/utils/server-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { createFactory } from "hono/factory";
import type { Context } from "hono";

import { db } from "@/config/db";
import { ENDPOINT_MESSAGES } from "./messages";
import { env } from "@/config/env";
import type { ServerContext } from "@/types/hono";

import { ENDPOINT_MESSAGES } from "./messages";

/**
* Takes a URL and returns an object with the query string parameters, multiple of the same key will be an array
Expand Down Expand Up @@ -51,7 +53,7 @@ const factory = createFactory();
/**
* Middleware to validate that a service ID is provided and that the service exists
*/
export const serviceValidation = factory.createMiddleware(async (c, next) => {
export const v2_serviceValidation = factory.createMiddleware(async (c, next) => {
const serviceId = getServiceId(c);

if (!serviceId) {
Expand All @@ -74,24 +76,20 @@ export const serviceValidation = factory.createMiddleware(async (c, next) => {
* Middleware to validate that a service ID is provided and that the service exists and is an admin service
*/
export const adminServiceValidation = factory.createMiddleware(async (c, next) => {
const serviceId = getServiceId(c);

if (!serviceId) {
c.status(401);
return c.json({ success: false, message: ENDPOINT_MESSAGES.ServiceIdHeaderNotProvided });
}

const service = await getService(serviceId, { mustBeAdmin: true });
const service = c.var.service as ServerContext["Variables"]["service"];

if (!service) {
c.status(403);
return c.json({ success: false, message: ENDPOINT_MESSAGES.ServiceDoesNotExistOrDoesNotHaveNecessaryRights });
}

c.set("service", service);
await next();
});

export function getUserServerUrl() {
/**
* Get the url of the server for the user
* @returns The URL of the server for the user
*/
export function getUserServerUrl(): string {
return env.NODE_ENV === "production" ? env.SERVER_URI : `http://localhost:${env.PORT}`;
}

0 comments on commit 131ddc3

Please sign in to comment.