All files / auth get-my-tenants.js

100% Statements 27/27
100% Branches 14/14
100% Functions 6/6
100% Lines 24/24

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 88 89 90 91 92 93 941x 1x   1x 1x   15x         1x 15x 15x   15x 1x               14x                             13x   13x 4x               12x 9x       12x           8x     8x 13x 11x                         8x           2x 2x              
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const getCorsHeaders = () => ({
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
})
 
exports.handler = async (event) => {
  try {
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Not authenticated' })
      }
    }
 
    // Query all memberships for this user
    const membershipsResult = await docClient.send(
      new QueryCommand({
        TableName: process.env.MEMBERSHIPS_TABLE_NAME,
        KeyConditionExpression: 'userId = :userId',
        FilterExpression: '#status = :status',
        ExpressionAttributeNames: {
          '#status': 'status'
        },
        ExpressionAttributeValues: {
          ':userId': userId,
          ':status': 'active'
        }
      })
    )
 
    const memberships = membershipsResult.Items || []
 
    if (memberships.length === 0) {
      return {
        statusCode: 200,
        headers: getCorsHeaders(),
        body: JSON.stringify([])
      }
    }
 
    // Batch get tenant details
    const tenantIds = memberships.map((m) => m.tenantId)
    const tenantsResult = await docClient.send(
      new BatchGetCommand({
        RequestItems: {
          [process.env.TENANTS_TABLE_NAME]: {
            Keys: tenantIds.map((id) => ({ id }))
          }
        }
      })
    )
 
    const tenants = tenantsResult.Responses?.[process.env.TENANTS_TABLE_NAME] || []
 
    // Merge tenant info with membership info
    const result = memberships.map((membership) => {
      const tenant = tenants.find((t) => t.id === membership.tenantId)
      return {
        tenantId: membership.tenantId,
        tenantName: tenant?.name || 'Unknown',
        tenantSlug: tenant?.slug,
        roleIds: membership.roleIds,
        status: membership.status,
        joinedAt: membership.joinedAt,
        isOwner: tenant?.ownerId === userId,
        defaultLanguage: tenant?.defaultLanguage || 'en',
        enabledLanguages: tenant?.enabledLanguages || ['en', 'fr']
      }
    })
 
    return {
      statusCode: 200,
      headers: getCorsHeaders(),
      body: JSON.stringify(result)
    }
  } catch (error) {
    console.error('Error:', error)
    return {
      statusCode: 500,
      headers: getCorsHeaders(),
      body: JSON.stringify({ error: 'Failed to fetch tenants' })
    }
  }
}