All files / flows get.js

100% Statements 26/26
100% Branches 12/12
100% Functions 1/1
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 881x 1x   1x 1x   1x 1x   1x               1x 7x 7x 7x   7x 1x             6x 1x               5x             4x 1x               3x 3x 2x             2x 1x               2x           1x 1x              
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
 
const client = new DynamoDBClient({})
const ddb = DynamoDBDocumentClient.from(client)
 
const FLOWS_TABLE = process.env.FLOWS_TABLE_NAME
const MEMBERSHIPS_TABLE = process.env.FLOW_MEMBERSHIPS_TABLE_NAME
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers':
    'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token',
  'Access-Control-Allow-Methods': 'OPTIONS,GET,PUT,POST,DELETE'
}
 
exports.handler = async (event) => {
  try {
    const flowId = event.pathParameters?.flowId
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Not authenticated' })
      }
    }
 
    if (!flowId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Flow ID is required' })
      }
    }
 
    // Fetch the flow
    const flowResult = await ddb.send(
      new GetCommand({
        TableName: FLOWS_TABLE,
        Key: { id: flowId }
      })
    )
 
    if (!flowResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Flow not found' })
      }
    }
 
    // Verify the user is a member of this flow (or is the owner)
    const flow = flowResult.Item
    if (flow.ownerId !== userId) {
      const membershipResult = await ddb.send(
        new GetCommand({
          TableName: MEMBERSHIPS_TABLE,
          Key: { userId, flowId }
        })
      )
 
      if (!membershipResult.Item || membershipResult.Item.status !== 'active') {
        return {
          statusCode: 403,
          headers: CORS_HEADERS,
          body: JSON.stringify({ error: 'Access denied' })
        }
      }
    }
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify(flow)
    }
  } catch (error) {
    console.error('Error fetching flow:', error)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Internal server error' })
    }
  }
}