31 lines
1.0 KiB
JavaScript
31 lines
1.0 KiB
JavaScript
import { verifyJWT } from "../middleware/auth";
|
|
import { createErrorResponse, createSuccessResponse } from "../utils";
|
|
|
|
export async function onRequest(context) {
|
|
try {
|
|
// Verify JWT token
|
|
const authResult = await verifyJWT(context);
|
|
if (authResult) {
|
|
return authResult; // Return error response if authentication fails
|
|
}
|
|
|
|
// Get user information from context
|
|
const { user } = context;
|
|
|
|
// Fetch user profile from D1 database
|
|
const { results } = await context.env.DB.prepare("SELECT * FROM users WHERE id = ?").bind(user.userId).all();
|
|
if (!results || results.length === 0) {
|
|
// use 401 instead to redirect to login page
|
|
return createErrorResponse("User not found", 401);
|
|
}
|
|
const userProfile = results[0];
|
|
const { password, ...profile } = userProfile; // Exclude password from the profile
|
|
|
|
// Return the profile as a JSON response
|
|
return createSuccessResponse(profile, 200);
|
|
} catch (error) {
|
|
console.error("Error:", error);
|
|
return createErrorResponse("Internal Server Error", 500);
|
|
}
|
|
}
|