Add comprehensive debug logging and refactor events API session handling
- Add extensive console logging throughout events GET/POST endpoints - Replace getUserSession with createSessionManager for better session handling - Temporarily disable complex filtering/sorting logic to isolate issues - Enhance error handling with proper statusCode checking
This commit is contained in:
@@ -1,24 +1,39 @@
|
||||
// server/api/events/index.get.ts
|
||||
import { createNocoDBEventsClient, transformEventForCalendar } from '~/server/utils/nocodb-events';
|
||||
import { createSessionManager } from '~/server/utils/session';
|
||||
import type { EventFilters } from '~/utils/types';
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
console.log('[api/events.get] =========================');
|
||||
console.log('[api/events.get] GET /api/events - List all events');
|
||||
console.log('[api/events.get] Request from:', getClientIP(event));
|
||||
|
||||
try {
|
||||
const query = getQuery(event) as EventFilters & {
|
||||
limit?: string;
|
||||
offset?: string;
|
||||
calendar_format?: string
|
||||
calendar_format?: string;
|
||||
force?: string;
|
||||
};
|
||||
|
||||
// Get user session for role-based filtering
|
||||
const session = await getUserSession(event);
|
||||
if (!session || !session.user) {
|
||||
console.log('[api/events.get] Query parameters:', query);
|
||||
|
||||
// Get user session using the working session manager
|
||||
const sessionManager = createSessionManager();
|
||||
const cookieHeader = getHeader(event, 'cookie');
|
||||
const session = sessionManager.getSession(cookieHeader);
|
||||
|
||||
if (!session) {
|
||||
console.log('[api/events.get] ❌ No valid session found');
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Authentication required'
|
||||
});
|
||||
}
|
||||
|
||||
console.log('[api/events.get] ✅ Valid session found for user:', session.user.email);
|
||||
console.log('[api/events.get] User tier:', session.user.tier);
|
||||
|
||||
const eventsClient = createNocoDBEventsClient();
|
||||
|
||||
// Build filters with user role
|
||||
@@ -39,9 +54,13 @@ export default defineEventHandler(async (event) => {
|
||||
filters.end_date = endDate.toISOString();
|
||||
}
|
||||
|
||||
console.log('[api/events.get] Fetching events with filters:', filters);
|
||||
|
||||
// Get events from database
|
||||
const response = await eventsClient.findUserEvents(session.user.id, filters);
|
||||
|
||||
console.log('[api/events.get] ✅ Successfully fetched', response.list.length, 'events');
|
||||
|
||||
// Transform for FullCalendar if requested
|
||||
if (query.calendar_format === 'true') {
|
||||
const calendarEvents = response.list.map(transformEventForCalendar);
|
||||
@@ -59,32 +78,17 @@ export default defineEventHandler(async (event) => {
|
||||
pagination: response.PageInfo
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error fetching events:', error);
|
||||
} catch (error: any) {
|
||||
console.error('[api/events.get] ❌ Error fetching events:', error);
|
||||
|
||||
// Re-throw createError instances
|
||||
if (error.statusCode) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'Failed to fetch events'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Helper function to get user session (you may need to adjust this based on your auth implementation)
|
||||
async function getUserSession(event: any) {
|
||||
// This should be replaced with your actual session retrieval logic
|
||||
// For now, assuming you have a session utility similar to your auth system
|
||||
try {
|
||||
const sessionCookie = getCookie(event, 'session') || getHeader(event, 'authorization');
|
||||
if (!sessionCookie) return null;
|
||||
|
||||
// Decode session - adjust based on your session implementation
|
||||
// This is a placeholder that should be replaced with your actual session logic
|
||||
return {
|
||||
user: {
|
||||
id: 'user-id', // This should come from your session
|
||||
tier: 'user' // This should come from your session
|
||||
}
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,43 @@
|
||||
// server/api/events/index.post.ts
|
||||
import { createNocoDBEventsClient } from '~/server/utils/nocodb-events';
|
||||
import { createSessionManager } from '~/server/utils/session';
|
||||
import type { EventCreateRequest } from '~/utils/types';
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
console.log('[api/events.post] =========================');
|
||||
console.log('[api/events.post] POST /api/events - Create event');
|
||||
console.log('[api/events.post] Request from:', getClientIP(event));
|
||||
|
||||
try {
|
||||
const body = await readBody(event) as EventCreateRequest;
|
||||
|
||||
// Get user session for authentication and authorization
|
||||
const session = await getUserSession(event);
|
||||
if (!session || !session.user) {
|
||||
console.log('[api/events.post] Event data received:', {
|
||||
title: body.title,
|
||||
event_type: body.event_type,
|
||||
start_datetime: body.start_datetime,
|
||||
end_datetime: body.end_datetime,
|
||||
visibility: body.visibility
|
||||
});
|
||||
|
||||
// Get user session using the working session manager
|
||||
const sessionManager = createSessionManager();
|
||||
const cookieHeader = getHeader(event, 'cookie');
|
||||
const session = sessionManager.getSession(cookieHeader);
|
||||
|
||||
if (!session) {
|
||||
console.log('[api/events.post] ❌ No valid session found');
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Authentication required'
|
||||
});
|
||||
}
|
||||
|
||||
console.log('[api/events.post] ✅ Valid session found for user:', session.user.email);
|
||||
console.log('[api/events.post] User tier:', session.user.tier);
|
||||
|
||||
// Check if user has permission to create events (board or admin only)
|
||||
if (session.user.tier !== 'board' && session.user.tier !== 'admin') {
|
||||
console.log('[api/events.post] ❌ Insufficient permissions. User tier:', session.user.tier);
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: 'Only board members and administrators can create events'
|
||||
@@ -25,6 +46,7 @@ export default defineEventHandler(async (event) => {
|
||||
|
||||
// Validate required fields
|
||||
if (!body.title || !body.start_datetime || !body.end_datetime) {
|
||||
console.log('[api/events.post] ❌ Missing required fields');
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Title, start date, and end date are required'
|
||||
@@ -36,6 +58,7 @@ export default defineEventHandler(async (event) => {
|
||||
const endDate = new Date(body.end_datetime);
|
||||
|
||||
if (startDate >= endDate) {
|
||||
console.log('[api/events.post] ❌ Invalid date range');
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'End date must be after start date'
|
||||
@@ -45,6 +68,7 @@ export default defineEventHandler(async (event) => {
|
||||
// Validate event type
|
||||
const validEventTypes = ['meeting', 'social', 'fundraiser', 'workshop', 'board-only'];
|
||||
if (!validEventTypes.includes(body.event_type)) {
|
||||
console.log('[api/events.post] ❌ Invalid event type:', body.event_type);
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Invalid event type'
|
||||
@@ -54,6 +78,7 @@ export default defineEventHandler(async (event) => {
|
||||
// Validate visibility
|
||||
const validVisibilities = ['public', 'board-only', 'admin-only'];
|
||||
if (!validVisibilities.includes(body.visibility)) {
|
||||
console.log('[api/events.post] ❌ Invalid visibility:', body.visibility);
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Invalid visibility setting'
|
||||
@@ -62,19 +87,22 @@ export default defineEventHandler(async (event) => {
|
||||
|
||||
// Admin-only visibility can only be set by admins
|
||||
if (body.visibility === 'admin-only' && session.user.tier !== 'admin') {
|
||||
console.log('[api/events.post] ❌ Admin-only event creation attempted by non-admin');
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: 'Only administrators can create admin-only events'
|
||||
});
|
||||
}
|
||||
|
||||
console.log('[api/events.post] ✅ Validation passed, creating event...');
|
||||
|
||||
const eventsClient = createNocoDBEventsClient();
|
||||
|
||||
// Prepare event data
|
||||
const eventData = {
|
||||
title: body.title.trim(),
|
||||
description: body.description?.trim() || '',
|
||||
event_type: body.event_type,
|
||||
event_type: body.event_type as 'meeting' | 'social' | 'fundraiser' | 'workshop' | 'board-only',
|
||||
start_datetime: body.start_datetime,
|
||||
end_datetime: body.end_datetime,
|
||||
location: body.location?.trim() || '',
|
||||
@@ -85,23 +113,27 @@ export default defineEventHandler(async (event) => {
|
||||
cost_members: body.cost_members || '',
|
||||
cost_non_members: body.cost_non_members || '',
|
||||
member_pricing_enabled: body.member_pricing_enabled || 'true',
|
||||
visibility: body.visibility,
|
||||
status: body.status || 'active',
|
||||
visibility: body.visibility as 'public' | 'board-only' | 'admin-only',
|
||||
status: (body.status || 'active') as 'active' | 'cancelled' | 'completed' | 'draft',
|
||||
creator: session.user.id,
|
||||
current_attendees: '0'
|
||||
current_attendees: 0
|
||||
};
|
||||
|
||||
console.log('[api/events.post] Event data prepared:', Object.keys(eventData));
|
||||
|
||||
// Create the event
|
||||
const newEvent = await eventsClient.create(eventData);
|
||||
|
||||
console.log('[api/events.post] ✅ Event created successfully with ID:', newEvent.id);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: newEvent,
|
||||
message: 'Event created successfully'
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creating event:', error);
|
||||
} catch (error: any) {
|
||||
console.error('[api/events.post] ❌ Error creating event:', error);
|
||||
|
||||
// Re-throw createError instances
|
||||
if (error.statusCode) {
|
||||
@@ -114,20 +146,3 @@ export default defineEventHandler(async (event) => {
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Helper function to get user session (same as in index.get.ts)
|
||||
async function getUserSession(event: any) {
|
||||
try {
|
||||
const sessionCookie = getCookie(event, 'session') || getHeader(event, 'authorization');
|
||||
if (!sessionCookie) return null;
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: 'user-id', // Replace with actual session logic
|
||||
tier: 'board' // Replace with actual session logic
|
||||
}
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user