Update artifacts/api-server/src/lib/auth.ts
Browse files
artifacts/api-server/src/lib/auth.ts
CHANGED
|
@@ -1,45 +1,42 @@
|
|
| 1 |
import type { Request, Response, NextFunction } from "express";
|
| 2 |
-
import {
|
| 3 |
|
| 4 |
export interface AuthedRequest extends Request {
|
| 5 |
userId: string;
|
| 6 |
userEmail: string | null;
|
| 7 |
}
|
| 8 |
|
| 9 |
-
const
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
|
| 12 |
export async function requireAuth(
|
| 13 |
req: Request,
|
| 14 |
res: Response,
|
| 15 |
next: NextFunction,
|
| 16 |
): Promise<void> {
|
| 17 |
-
const
|
| 18 |
-
|
| 19 |
-
|
| 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 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 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 |
-
|
| 43 |
-
|
| 44 |
-
|
| 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 |
+
}
|