All files / tenants create.js

100% Statements 31/31
95% Branches 19/20
100% Functions 2/2
100% Lines 30/30

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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 1481x 1x       1x 1x   1x 1x 1x   15x         1x 15x 15x 14x   14x 1x             13x 2x               11x                     10x 1x             9x 9x     9x                         9x               9x                           9x               9x                             9x                         8x           3x 3x              
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, PutCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const {
  CognitoIdentityProviderClient,
  AdminUpdateUserAttributesCommand
} = require('@aws-sdk/client-cognito-identity-provider')
const { randomUUID } = require('crypto')
 
const dynamoClient = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(dynamoClient)
const cognitoClient = new CognitoIdentityProviderClient({})
 
const getCorsHeaders = () => ({
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
})
 
exports.handler = async (event) => {
  try {
    const body = JSON.parse(event.body || '{}')
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Not authenticated' })
      }
    }
 
    if (!body.name || !body.slug) {
      return {
        statusCode: 400,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Missing required fields: name, slug' })
      }
    }
 
    // Verify slug is unique
    const existingTenant = await docClient.send(
      new QueryCommand({
        TableName: process.env.TENANTS_TABLE_NAME,
        IndexName: 'slugIndex',
        KeyConditionExpression: 'slug = :slug',
        ExpressionAttributeValues: {
          ':slug': body.slug
        }
      })
    )
 
    if (existingTenant.Items && existingTenant.Items.length > 0) {
      return {
        statusCode: 409,
        headers: getCorsHeaders(),
        body: JSON.stringify({ error: 'Slug already exists' })
      }
    }
 
    const tenantId = randomUUID()
    const now = new Date().toISOString()
 
    // Create tenant
    const tenant = {
      id: tenantId,
      name: body.name,
      slug: body.slug,
      ownerId: userId,
      joinPolicy: body.joinPolicy || 'invite-only',
      status: 'active',
      createdAt: now,
      defaultLanguage: body.defaultLanguage || 'en',
      enabledLanguages: body.enabledLanguages || ['en', 'fr'],
      settings: body.settings || {}
    }
 
    await docClient.send(
      new PutCommand({
        TableName: process.env.TENANTS_TABLE_NAME,
        Item: tenant
      })
    )
 
    // Create default Admin role
    const adminRole = {
      PK: `TENANT#${tenantId}`,
      SK: 'ROLE#admin',
      tenantId: tenantId,
      roleId: 'admin',
      name: 'Administrator',
      description: 'Full access to all tenant resources',
      permissions: ['*:*'],
      isSystemRole: true,
      createdBy: 'SYSTEM',
      createdAt: now,
      updatedAt: now
    }
 
    await docClient.send(
      new PutCommand({
        TableName: process.env.ROLES_TABLE_NAME,
        Item: adminRole
      })
    )
 
    // Create owner membership with Admin role
    await docClient.send(
      new PutCommand({
        TableName: process.env.MEMBERSHIPS_TABLE_NAME,
        Item: {
          userId: userId,
          tenantId: tenantId,
          roleIds: ['admin'], // Assign Admin role to creator
          status: 'active',
          invitedBy: userId,
          joinedAt: now
        }
      })
    )
 
    // Set as active tenant in Cognito
    await cognitoClient.send(
      new AdminUpdateUserAttributesCommand({
        UserPoolId: process.env.USER_POOL_ID,
        Username: userId,
        UserAttributes: [
          {
            Name: 'custom:tenantId',
            Value: tenantId
          }
        ]
      })
    )
 
    return {
      statusCode: 201,
      headers: getCorsHeaders(),
      body: JSON.stringify(tenant)
    }
  } catch (error) {
    console.error('Error:', error)
    return {
      statusCode: 500,
      headers: getCorsHeaders(),
      body: JSON.stringify({ error: 'Failed to create tenant' })
    }
  }
}