/ server / api / external / user.get.ts
user.get.ts
 1  import { PrismaClient } from "@prisma/client";
 2  import { H3Event } from "h3";
 3  import { z } from "zod";
 4  import { handleApiError} from "~~/server/utils/logging";
 5  
 6  const prisma = new PrismaClient();
 7  
 8  const apiKeySchema = z.string().uuid();
 9  
10  export default defineEventHandler(async (event: H3Event) => {
11    try {
12      const authHeader = getHeader(event, "authorization");
13      if (!authHeader || !authHeader.startsWith("Bearer ")) {
14        throw handleApiError(401, "External User API: Missing or invalid API key format in header.", "API key is missing or improperly formatted.");
15      }
16  
17      const apiKey = authHeader.substring(7);
18      const validationResult = apiKeySchema.safeParse(apiKey);
19  
20      if (!validationResult.success) {
21        throw handleApiError(401, `External User API: Invalid API key format. Key prefix: ${apiKey.substring(0,4)}...`, "Invalid API key format.");
22      }
23  
24      const user = await prisma.user.findUnique({
25        where: { apiKey },
26        select: {
27          id: true,
28          email: true,
29          githubId: true,
30          githubUsername: true,
31          apiKey: true,
32          keystrokeTimeout: true,
33        },
34      });
35  
36      if (!user) {
37        throw handleApiError(404, `External User API: User not found for API key prefix: ${apiKey.substring(0,4)}...`, "User not found.");
38      }
39  
40      return user;
41    } catch (error: any) {
42      if (error && typeof error === "object" && error.statusCode) throw error;
43      const detailedMessage = error instanceof Error ? error.message : "An unknown error occurred fetching external user data.";
44      const apiKeyPrefix = getHeader(event, "authorization")?.substring(7,11) || "UNKNOWN";
45      throw handleApiError(500, `External User API: Failed to fetch user data. API Key prefix: ${apiKeyPrefix}... Error: ${detailedMessage}`, "Failed to fetch user data.");
46    }
47  });