sare26 commited on
Commit
01abfc5
·
verified ·
1 Parent(s): 5483279

Update artifacts/api-server/src/lib/auth.ts

Browse files
Files changed (1) hide show
  1. artifacts/api-server/src/lib/auth.ts +23 -26
artifacts/api-server/src/lib/auth.ts CHANGED
@@ -1,45 +1,42 @@
1
  import type { Request, Response, NextFunction } from "express";
2
- import { getAuth, clerkClient } from "@clerk/express";
3
 
4
  export interface AuthedRequest extends Request {
5
  userId: string;
6
  userEmail: string | null;
7
  }
8
 
9
- const emailCache = new Map<string, { email: string | null; ts: number }>();
10
- const CACHE_TTL_MS = 15 * 60 * 1000;
 
 
11
 
12
  export async function requireAuth(
13
  req: Request,
14
  res: Response,
15
  next: NextFunction,
16
  ): Promise<void> {
17
- const auth = getAuth(req);
18
- const claimUserId =
19
- typeof auth?.sessionClaims?.["userId"] === "string"
20
- ? (auth.sessionClaims["userId"] as string)
21
- : null;
22
- const userId: string | null = claimUserId ?? auth?.userId ?? null;
23
- if (!userId) {
24
  res.status(401).json({ error: "Unauthorized" });
25
  return;
26
  }
27
 
28
- let email: string | null = null;
29
- const cached = emailCache.get(userId);
30
- if (cached && Date.now() - cached.ts < CACHE_TTL_MS) {
31
- email = cached.email;
32
- } else {
33
- try {
34
- const user = await clerkClient.users.getUser(userId);
35
- email = user.primaryEmailAddress?.emailAddress ?? null;
36
- } catch (err) {
37
- req.log.warn({ err }, "Failed to fetch user from Clerk");
38
  }
39
- emailCache.set(userId, { email, ts: Date.now() });
40
- }
41
 
42
- (req as AuthedRequest).userId = userId;
43
- (req as AuthedRequest).userEmail = email;
44
- next();
45
- }
 
 
 
 
1
  import type { Request, Response, NextFunction } from "express";
2
+ import { createClient } from "@supabase/supabase-js";
3
 
4
  export interface AuthedRequest extends Request {
5
  userId: string;
6
  userEmail: string | null;
7
  }
8
 
9
+ const supabase = createClient(
10
+ process.env.SUPABASE_URL || "",
11
+ process.env.SUPABASE_SERVICE_ROLE_KEY || ""
12
+ );
13
 
14
  export async function requireAuth(
15
  req: Request,
16
  res: Response,
17
  next: NextFunction,
18
  ): Promise<void> {
19
+ const authHeader = req.headers.authorization;
20
+
21
+ if (!authHeader?.startsWith("Bearer ")) {
 
 
 
 
22
  res.status(401).json({ error: "Unauthorized" });
23
  return;
24
  }
25
 
26
+ const token = authHeader.split(" ")[1];
27
+
28
+ try {
29
+ const { data: { user }, error } = await supabase.auth.getUser(token);
30
+
31
+ if (error || !user) {
32
+ res.status(401).json({ error: "Unauthorized" });
33
+ return;
 
 
34
  }
 
 
35
 
36
+ (req as AuthedRequest).userId = user.id;
37
+ (req as AuthedRequest).userEmail = user.email ?? null;
38
+ next();
39
+ } catch (err) {
40
+ res.status(401).json({ error: "Unauthorized" });
41
+ }
42
+ }