File size: 1,391 Bytes
a6b6c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { Context, Next } from "hono";

function isPublicApiRoute(method: string, path: string) {
  if (path === "/api/webhook/instagram") return true;
  if (method === "GET" && path === "/api/instagram/connect") return true;
  if (method === "GET" && path === "/api/instagram/callback") return true;
  if (method === "POST" && path === "/api/user/delete") return true;
  if (method === "GET" && path === "/api/user/delete") return true;

  return false;
}

export async function apiAuth(c: Context, next: Next) {
  if (isPublicApiRoute(c.req.method, c.req.path)) {
    return next();
  }

  if (c.req.method === "POST" && c.req.path === "/api/automation/followups") {
    const cronSecret = process.env.AUTOMATION_CRON_SECRET;
    const providedCronSecret = c.req
      .header("authorization")
      ?.replace(/^Bearer\s+/i, "");

    if (cronSecret && providedCronSecret === cronSecret) {
      return next();
    }
  }

  const expectedKey = process.env.SERVER_API_KEY;
  if (!expectedKey) {
    if (process.env.NODE_ENV === "production") {
      return c.json({ error: "SERVER_API_KEY is not configured" }, 500);
    }

    return next();
  }

  const providedKey =
    c.req.header("x-server-api-key") ??
    c.req.header("authorization")?.replace(/^Bearer\s+/i, "");

  if (providedKey !== expectedKey) {
    return c.json({ error: "Unauthorized" }, 401);
  }

  return next();
}