Files
web-antrean/server/api/users/sync.post.ts
T
2025-12-16 10:42:45 +07:00

45 lines
1.3 KiB
TypeScript

// server/api/users/sync.post.ts
// Auto-save/update user data when they first login
// This endpoint will be called automatically when user logs in
export default defineEventHandler(async (event) => {
console.log("🔄 User sync endpoint called");
const sessionCookie = getCookie(event, "user_session");
if (!sessionCookie) {
throw createError({
statusCode: 401,
statusMessage: "No session cookie found",
});
}
try {
const session = JSON.parse(sessionCookie);
const isExpired = Date.now() > session.expiresAt;
if (isExpired) {
deleteCookie(event, "user_session");
throw createError({
statusCode: 401,
statusMessage: "Session expired",
});
}
// Use the shared sync utility
// Use session createdAt as loginTime, or current time if not available
const { syncUserFromTokens } = await import('~/server/utils/userSync');
const loginTime = session.createdAt || Date.now();
const result = syncUserFromTokens(session.idToken, session.accessToken, loginTime);
return result;
} catch (error: any) {
console.error("❌ Error syncing user:", error);
throw createError({
statusCode: 500,
statusMessage: error.message || "Failed to sync user data",
});
}
});