fix: add admin
This commit is contained in:
33
server/middleware/adminAuth.ts
Normal file
33
server/middleware/adminAuth.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
function getSecret(): string {
|
||||
return useRuntimeConfig().adminPassword || "changeme";
|
||||
}
|
||||
|
||||
export function signToken(payload: string): string {
|
||||
return createHmac("sha256", getSecret()).update(payload).digest("hex");
|
||||
}
|
||||
|
||||
export function verifyToken(payload: string, signature: string): boolean {
|
||||
const expected = signToken(payload);
|
||||
try {
|
||||
return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
const path = getRequestURL(event).pathname;
|
||||
if (!path.startsWith("/api/admin/") || path === "/api/admin/login") return;
|
||||
|
||||
const cookie = getCookie(event, "admin-session");
|
||||
if (!cookie) {
|
||||
throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
|
||||
}
|
||||
|
||||
const [payload, signature] = cookie.split(".");
|
||||
if (!payload || !signature || !verifyToken(payload, signature)) {
|
||||
throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
|
||||
}
|
||||
});
|
||||
19
server/middleware/requestLogger.ts
Normal file
19
server/middleware/requestLogger.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export default defineEventHandler((event) => {
|
||||
const path = getRequestURL(event).pathname;
|
||||
if (!path.startsWith("/api/v1/rates")) return;
|
||||
|
||||
const ip = getRequestIP(event, { xForwardedFor: true }) ?? "127.0.0.1";
|
||||
const method = event.method;
|
||||
const userAgent = getRequestHeader(event, "user-agent") ?? "";
|
||||
|
||||
event.node.res.on("finish", () => {
|
||||
logRequest({
|
||||
ip,
|
||||
path,
|
||||
method,
|
||||
statusCode: event.node.res.statusCode,
|
||||
userAgent,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user