diff --git a/amplify/functions/LambdaEncryptKeys/handler.ts b/amplify/functions/LambdaEncryptKeys/handler.ts index 75cb311c..bde6c295 100644 --- a/amplify/functions/LambdaEncryptKeys/handler.ts +++ b/amplify/functions/LambdaEncryptKeys/handler.ts @@ -4,7 +4,7 @@ import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtim import { env } from '$amplify/env/apiKeyManager' import { type Schema } from '../../data/resource' import crypto from 'crypto' - +import { getCorsHeaders } from '../shared/cors' const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig(env) Amplify.configure(resourceConfig, libraryOptions) @@ -44,6 +44,16 @@ function decrypt(encryptedText: string): string { } export const handler = async (event: any) => { + const origin = event.headers?.origin || event.headers?.Origin + + // Manejar peticiones OPTIONS (preflight CORS) + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } try { const { storeId, @@ -61,20 +71,14 @@ export const handler = async (event: any) => { return { statusCode: 200, body: JSON.stringify({ success: true, decryptedKey }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error al descifrar la clave:', error) return { statusCode: 400, body: JSON.stringify({ success: false, message: 'Error al descifrar la clave' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } @@ -84,10 +88,7 @@ export const handler = async (event: any) => { return { statusCode: 400, body: JSON.stringify({ success: false, message: 'Faltan parámetros requeridos' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -97,10 +98,7 @@ export const handler = async (event: any) => { return { statusCode: 200, body: JSON.stringify({ success: true, encryptedKey }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -113,10 +111,7 @@ export const handler = async (event: any) => { return { statusCode: 404, body: JSON.stringify({ success: false, message: 'Tienda no encontrada' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -196,10 +191,7 @@ export const handler = async (event: any) => { return { statusCode: 400, body: JSON.stringify({ success: false, message: 'Tipo de clave API no soportado' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -212,20 +204,14 @@ export const handler = async (event: any) => { return { statusCode: 200, body: JSON.stringify({ success: true, encryptedKey }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error en apiKeyManager:', error) return { statusCode: 500, body: JSON.stringify({ success: false, message: 'Error interno del servidor' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } diff --git a/amplify/functions/cancelPlan/handler.ts b/amplify/functions/cancelPlan/handler.ts index a37c095d..285d9061 100644 --- a/amplify/functions/cancelPlan/handler.ts +++ b/amplify/functions/cancelPlan/handler.ts @@ -1,6 +1,7 @@ import axios from 'axios' import { Amplify } from 'aws-amplify' import { generateClient } from 'aws-amplify/data' +import { getCorsHeaders } from '../shared/cors' import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime' import { env } from '$amplify/env/hookPlan' import { type Schema } from '../../data/resource' @@ -12,20 +13,24 @@ Amplify.configure(resourceConfig, libraryOptions) // Inicializar el cliente para DynamoDB (Amplify Data) const clientSchema = generateClient() -// Definir cabeceras CORS para testing -const corsHeaders = { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Headers': '*', -} - export const handler = async (event: any) => { + const origin = event.headers?.origin || event.headers?.Origin + + // Manejar peticiones OPTIONS (preflight CORS) + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } try { // 1. Extraer parámetros necesarios const { preapproval_id, user_id } = JSON.parse(event.body) if (!preapproval_id || !user_id) { return { statusCode: 400, - headers: corsHeaders, + headers: getCorsHeaders(origin), body: JSON.stringify({ message: 'Faltan parámetros' }), } } @@ -65,9 +70,9 @@ export const handler = async (event: any) => { if (response.status !== 200 && response.status !== 400) { return { statusCode: response.status, - headers: corsHeaders, + headers: getCorsHeaders(origin), body: JSON.stringify({ - message: data.message || 'Error al cancelar la suscripción', + message: data.message || 'Error at cancel plan', }), } } @@ -77,9 +82,9 @@ export const handler = async (event: any) => { if (!endDate) { return { statusCode: 500, - headers: corsHeaders, + headers: getCorsHeaders(origin), body: JSON.stringify({ - message: 'No se pudo obtener la fecha de finalización', + message: 'Error at get end date', }), } } @@ -101,19 +106,19 @@ export const handler = async (event: any) => { return { statusCode: 200, - headers: corsHeaders, + headers: getCorsHeaders(origin), body: JSON.stringify({ - message: 'Suscripción cancelada, cambio pendiente', + message: 'Plan cancelled, pending change', endDate, }), } } catch (error: any) { - console.error('❌ Error en la función Lambda:', error) + console.error('❌ Error at cancel plan:', error) return { statusCode: 500, - headers: corsHeaders, + headers: getCorsHeaders(origin), body: JSON.stringify({ - message: 'Error interno', + message: 'Internal error', error: error instanceof Error ? error.message : 'Unknown error', }), } diff --git a/amplify/functions/checkStoreDomain/handler.ts b/amplify/functions/checkStoreDomain/handler.ts index 28415fbc..1577d55a 100644 --- a/amplify/functions/checkStoreDomain/handler.ts +++ b/amplify/functions/checkStoreDomain/handler.ts @@ -2,6 +2,7 @@ import { Amplify } from 'aws-amplify' import { generateClient } from 'aws-amplify/data' import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime' import { env } from '$amplify/env/checkStoreDomain' +import { getCorsHeaders } from '../shared/cors' import { type Schema } from '../../data/resource' const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig(env) @@ -10,16 +11,22 @@ Amplify.configure(resourceConfig, libraryOptions) const clientSchema = generateClient() export const handler = async (event: any) => { + const origin = event.headers?.origin || event.headers?.Origin const domainName = event.queryStringParameters?.domainName + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } + if (!domainName) { return { statusCode: 400, + headers: getCorsHeaders(origin), body: JSON.stringify({ message: 'Domain name is required' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, } } @@ -34,20 +41,14 @@ export const handler = async (event: any) => { available: !(stores && stores.length > 0), exists: stores && stores.length > 0, }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error checking domain availability:', error) return { statusCode: 500, body: JSON.stringify({ message: 'Error checking domain availability' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } diff --git a/amplify/functions/checkStoreName/handler.ts b/amplify/functions/checkStoreName/handler.ts index 3ef0a3fe..b88b104f 100644 --- a/amplify/functions/checkStoreName/handler.ts +++ b/amplify/functions/checkStoreName/handler.ts @@ -2,6 +2,7 @@ import { Amplify } from 'aws-amplify' import { generateClient } from 'aws-amplify/data' import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime' import { env } from '$amplify/env/checkStoreName' +import { getCorsHeaders } from '../shared/cors' import { type Schema } from '../../data/resource' // Configurar Amplify para acceso a datos @@ -12,16 +13,14 @@ Amplify.configure(resourceConfig, libraryOptions) const clientSchema = generateClient() export const handler = async (event: any) => { + const origin = event.headers?.origin || event.headers?.Origin const storeName = event.queryStringParameters?.storeName if (!storeName) { return { statusCode: 400, body: JSON.stringify({ message: 'Store name is required' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -33,20 +32,14 @@ export const handler = async (event: any) => { return { statusCode: 200, body: JSON.stringify({ exists: stores && stores.length > 0 }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error checking store name:', error) return { statusCode: 500, body: JSON.stringify({ message: 'Error checking store name' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } diff --git a/amplify/functions/createSubscription/handler.ts b/amplify/functions/createSubscription/handler.ts index df76da00..26c8a2ad 100644 --- a/amplify/functions/createSubscription/handler.ts +++ b/amplify/functions/createSubscription/handler.ts @@ -1,9 +1,21 @@ import { APIGatewayProxyHandler } from 'aws-lambda' +import { getCorsHeaders } from '../shared/cors' import { env } from '$amplify/env/createSubscription' const MERCADOPAGO_API_URL = 'https://api.mercadopago.com/preapproval' export const handler: APIGatewayProxyHandler = async event => { + const origin = event.headers?.origin || event.headers?.Origin + + // Manejar peticiones OPTIONS (preflight CORS) + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } + try { const body = JSON.parse(event.body || '{}') const { userId, plan } = body @@ -38,10 +50,7 @@ export const handler: APIGatewayProxyHandler = async event => { return { statusCode: 200, - headers: { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Headers': '*', - }, + headers: getCorsHeaders(origin), body: JSON.stringify({ checkoutUrl: subscription.init_point, }), @@ -51,10 +60,7 @@ export const handler: APIGatewayProxyHandler = async event => { return { statusCode: 500, - headers: { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Headers': '*', - }, + headers: getCorsHeaders(origin), body: JSON.stringify({ error: 'Error creando suscripción', details: error instanceof Error ? error.message : 'Error desconocido', diff --git a/amplify/functions/getStoreCollections/handler.ts b/amplify/functions/getStoreCollections/handler.ts index 1de2fd83..cca637c7 100644 --- a/amplify/functions/getStoreCollections/handler.ts +++ b/amplify/functions/getStoreCollections/handler.ts @@ -2,6 +2,7 @@ import { Amplify } from 'aws-amplify' import { generateClient } from 'aws-amplify/data' import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime' import { env } from '$amplify/env/getStoreCollections' +import { getCorsHeaders } from '../shared/cors' import { type Schema } from '../../data/resource' let clientSchema: ReturnType> | null = null @@ -16,7 +17,16 @@ const initializeClient = async () => { } export const handler = async (event: any) => { - // Obtener parámetros de la consulta + const origin = event.headers?.origin || event.headers?.Origin + + // Manejar peticiones OPTIONS (preflight CORS) + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } const storeId = event.queryStringParameters?.storeId const collectionId = event.queryStringParameters?.collectionId const slug = event.queryStringParameters?.slug @@ -26,10 +36,7 @@ export const handler = async (event: any) => { return { statusCode: 400, body: JSON.stringify({ message: 'Store ID is required' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -44,10 +51,7 @@ export const handler = async (event: any) => { return { statusCode: 404, body: JSON.stringify({ message: 'Collection not found' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -71,10 +75,7 @@ export const handler = async (event: any) => { products: products || [], }, }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -92,10 +93,7 @@ export const handler = async (event: any) => { return { statusCode: 404, body: JSON.stringify({ message: 'Collection not found' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -117,10 +115,7 @@ export const handler = async (event: any) => { products: products || [], }, }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -137,20 +132,14 @@ export const handler = async (event: any) => { body: JSON.stringify({ collections: collections || [], }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error fetching collections data:', error) return { statusCode: 500, body: JSON.stringify({ message: 'Error fetching collections data' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } diff --git a/amplify/functions/getStoreData/handler.ts b/amplify/functions/getStoreData/handler.ts index 4c8a1978..9f60f06f 100644 --- a/amplify/functions/getStoreData/handler.ts +++ b/amplify/functions/getStoreData/handler.ts @@ -3,7 +3,7 @@ import { generateClient } from 'aws-amplify/data' import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime' import { env } from '$amplify/env/getStoreData' import { type Schema } from '../../data/resource' - +import { getCorsHeaders } from '../shared/cors' let clientSchema: ReturnType> | null = null const initializeClient = async () => { @@ -15,16 +15,23 @@ const initializeClient = async () => { return clientSchema } export const handler = async (event: any) => { + const origin = event.headers?.origin || event.headers?.Origin const storeName = event.queryStringParameters?.storeName + // Manejar peticiones OPTIONS (preflight CORS) + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } + if (!storeName) { return { statusCode: 400, body: JSON.stringify({ message: 'Store ID is required' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -38,10 +45,7 @@ export const handler = async (event: any) => { return { statusCode: 404, body: JSON.stringify({ message: 'Store not found' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -50,20 +54,14 @@ export const handler = async (event: any) => { body: JSON.stringify({ store: store, }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error fetching store data:', error) return { statusCode: 500, body: JSON.stringify({ message: 'Error fetching store data' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } diff --git a/amplify/functions/getStoreProducts/handler.ts b/amplify/functions/getStoreProducts/handler.ts index bbf50bdb..9b91b303 100644 --- a/amplify/functions/getStoreProducts/handler.ts +++ b/amplify/functions/getStoreProducts/handler.ts @@ -3,7 +3,7 @@ import { generateClient } from 'aws-amplify/data' import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime' import { env } from '$amplify/env/getStoreProducts' import { type Schema } from '../../data/resource' - +import { getCorsHeaders } from '../shared/cors' let clientSchema: ReturnType> | null = null const initializeClient = async () => { @@ -16,16 +16,23 @@ const initializeClient = async () => { } export const handler = async (event: any) => { + const origin = event.headers?.origin || event.headers?.Origin const storeId = event.queryStringParameters?.storeId + // Manejar peticiones OPTIONS (preflight CORS) + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } + if (!storeId) { return { statusCode: 400, body: JSON.stringify({ message: 'Store ID is required' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -47,20 +54,14 @@ export const handler = async (event: any) => { body: JSON.stringify({ products: products, }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error fetching store products:', error) return { statusCode: 500, body: JSON.stringify({ message: 'Error fetching store products' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } diff --git a/amplify/functions/planManagement/handler.ts b/amplify/functions/planManagement/handler.ts index e1fa9575..31f9fa98 100644 --- a/amplify/functions/planManagement/handler.ts +++ b/amplify/functions/planManagement/handler.ts @@ -1,6 +1,7 @@ import axios from 'axios' import { APIGatewayProxyHandler } from 'aws-lambda' import { env } from '$amplify/env/planManagement' +import { getCorsHeaders } from '../shared/cors' /** * Función auxiliar que calcula la fecha de finalización exactamente un mes después de la fecha de inicio. @@ -13,13 +14,16 @@ function calcularEndDate(startDate: Date): Date { return endDate } -// Objeto de cabeceras CORS para permitir todos los orígenes -const corsHeaders = { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Headers': '*', -} - export const handler: APIGatewayProxyHandler = async event => { + const origin = event.headers?.origin || event.headers?.Origin + + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } try { // 1. Extraer parámetros del body de la solicitud. // Se espera recibir: @@ -34,7 +38,7 @@ export const handler: APIGatewayProxyHandler = async event => { if (!subscriptionId || !newAmount || !currencyId || !newPlanName) { return { statusCode: 400, - headers: corsHeaders, + headers: getCorsHeaders(origin), body: JSON.stringify({ message: 'Faltan parámetros requeridos: subscriptionId, newAmount, currencyId y newPlanName.', @@ -89,7 +93,7 @@ export const handler: APIGatewayProxyHandler = async event => { // 6. Retornar respuesta exitosa con la URL de confirmación para que el cliente pueda redirigir al usuario. return { statusCode: 200, - headers: corsHeaders, + headers: getCorsHeaders(origin), body: JSON.stringify({ message: 'La suscripción se actualizó exitosamente. Confirme el pago en la URL proporcionada.', @@ -101,7 +105,7 @@ export const handler: APIGatewayProxyHandler = async event => { console.error('❌ Error actualizando la suscripción:', error) return { statusCode: 500, - headers: corsHeaders, + headers: getCorsHeaders(origin), body: JSON.stringify({ message: 'Error actualizando la suscripción.', error: error instanceof Error ? error.message : 'Unknown error', diff --git a/amplify/functions/shared/cors.ts b/amplify/functions/shared/cors.ts new file mode 100644 index 00000000..a318b181 --- /dev/null +++ b/amplify/functions/shared/cors.ts @@ -0,0 +1,33 @@ +const exactOrigins: string[] = ['https://www.fasttify.com', 'http://localhost:3000'] + +const wildcardRegexes: RegExp[] = [/\.fasttify\.com$/] + +/** + * Verifica si el origen es válido + */ +function isAllowedOrigin(origin: string | undefined): boolean { + if (!origin) return false + + try { + const url = new URL(origin) + const hostname = url.hostname + + return exactOrigins.includes(origin) || wildcardRegexes.some(regex => regex.test(hostname)) + } catch { + return false + } +} + +/** + * Devuelve los headers CORS adecuados para una función Lambda + */ +export function getCorsHeaders(origin?: string): Record { + const isAllowed = isAllowedOrigin(origin) + + return { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': isAllowed ? origin! : 'null', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization', + 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', + } +} diff --git a/amplify/functions/storeImages/handler.ts b/amplify/functions/storeImages/handler.ts index 2c4f5a33..2d78788b 100644 --- a/amplify/functions/storeImages/handler.ts +++ b/amplify/functions/storeImages/handler.ts @@ -5,6 +5,7 @@ import { DeleteObjectCommand, } from '@aws-sdk/client-s3' import { env } from '$amplify/env/storeImages' +import { getCorsHeaders } from '../shared/cors' const s3Client = new S3Client() @@ -46,6 +47,15 @@ if ( } export const handler = async (event: any) => { + const origin = event.headers?.origin || event.headers?.Origin + + if (event.httpMethod === 'OPTIONS') { + return { + statusCode: 200, + headers: getCorsHeaders(origin), + body: '', + } + } try { const body = event.body ? JSON.parse(event.body) : {} const { action, storeId } = body @@ -54,29 +64,23 @@ export const handler = async (event: any) => { return { statusCode: 400, body: JSON.stringify({ message: 'Store ID is required' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } // Manejar diferentes acciones switch (action) { case 'list': - return await listImages(storeId, body.limit, body.prefix, body.continuationToken) + return await listImages(storeId, origin, body.limit, body.prefix, body.continuationToken) case 'upload': - return await uploadImage(storeId, body.filename, body.contentType, body.fileContent) + return await uploadImage(storeId, origin, body.filename, body.contentType, body.fileContent) case 'delete': - return await deleteImage(body.key) + return await deleteImage(body.key, origin) default: return { statusCode: 400, body: JSON.stringify({ message: 'Invalid action' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } catch (error) { @@ -84,10 +88,7 @@ export const handler = async (event: any) => { return { statusCode: 500, body: JSON.stringify({ message: 'Error processing request' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } @@ -95,6 +96,7 @@ export const handler = async (event: any) => { // Función para listar imágenes async function listImages( storeId: string, + origin: string | undefined, limit: number = 18, prefix: string = '', continuationToken?: string @@ -117,10 +119,7 @@ async function listImages( return { statusCode: 200, body: JSON.stringify({ images: [] }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } @@ -173,20 +172,14 @@ async function listImages( images: validImages, nextContinuationToken: listResponse.NextContinuationToken, }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error listing images:', error) return { statusCode: 500, body: JSON.stringify({ message: 'Error listing images' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } @@ -194,6 +187,7 @@ async function listImages( // Función para subir una imagen async function uploadImage( storeId: string, + origin: string | undefined, filename: string, contentType: string, fileContent: string @@ -238,26 +232,20 @@ async function uploadImage( return { statusCode: 200, body: JSON.stringify({ image }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error uploading image:', error) return { statusCode: 500, body: JSON.stringify({ message: 'Error uploading image' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } } // Función para eliminar una imagen -async function deleteImage(key: string) { +async function deleteImage(key: string, origin: string | undefined) { try { // Eliminar el objeto de S3 const deleteCommand = new DeleteObjectCommand({ @@ -270,20 +258,14 @@ async function deleteImage(key: string) { return { statusCode: 200, body: JSON.stringify({ success: true }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } catch (error) { console.error('Error deleting image:', error) return { statusCode: 500, body: JSON.stringify({ message: 'Error deleting image' }), - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - }, + headers: getCorsHeaders(origin), } } }