All files / membership-requests request.js

100% Statements 65/65
90.62% Branches 29/32
100% Functions 2/2
100% Lines 57/57

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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170                                  2x         2x         2x 2x           2x 2x 2x         2x   2x       18x 47x 47x 5x   13x     2x 30x 30x 30x     29x 29x   1x     28x 28x 20x 20x   20x   19x 19x 19x 1x   18x 18x   13x                           13x 12x 12x 11x   10x 10x 10x   9x 9x                   9x 9x                                                           4x 4x 4x 4x 1x   3x 2x     1x     5x 5x   5x   1x 1x      
// @implements UC-SPACE-004.1, UC-SPACE-007.1, UC-SPACE-020.1
/**
 * POST /v1/spaces/{slug}/join — ask to join a flow from its public space.
 *
 * Body: `{ answers: { [fieldId]: value }, consent: true }`. The answers are
 * validated like an item creation's (mandatory, lengths, types, options) but
 * only stored on the request: the membership item is created on approval
 * (decide.js), when the flow pays for it.
 *
 * One request per user and flow (the table's key): a pending or banned row
 * blocks a new one, a refused or approved one (the user left since) is
 * replaced. The flow's pending count is capped in the same transaction.
 *
 * Image and file answers name the caller's drafts; they are copied under the
 * request's own prefix (utils/membershipRequestFiles.js), and the drafts
 * deleted once the request is written.
 */
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const {
  validateMandatoryFields,
  validateFieldConstraints,
  validateFieldTypes
} = require('../items/field-validation')
const { MAX_ITEM_SIZE_BYTES } = require('../utils/constants')
const {
  loadJoinableFlow,
  joinFormFields,
  pickAnswers,
  MAX_PENDING_REQUESTS
} = require('../utils/spaceJoin')
const { respond, spaceNotFound, statusKey } = require('./shared')
const { emailApprovers } = require('../utils/membershipRequestEmails')
const {
  promoteDraftAnswers,
  deleteRequestKeys,
  deleteDraftKeys
} = require('../utils/membershipRequestFiles')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
/** Validates the answers against the fields the form shows; first error or null */
function answersError(fields, answers) {
  for (const check of [validateMandatoryFields, validateFieldConstraints, validateFieldTypes]) {
    const result = check(fields, answers)
    if (!result.valid)
      return { error: result.error || 'MANDATORY_FIELD_MISSING', fieldId: result.fieldId }
  }
  return null
}
 
exports.handler = async (event) => {
  try {
    const userId = event.requestContext?.authorizer?.claims?.sub
    if (!userId) return respond(401, { error: 'Not authenticated' })
 
    let body
    try {
      body = JSON.parse(event.body || '{}')
    } catch {
      return respond(400, { error: 'Invalid JSON body' })
    }
 
    const joinable = await loadJoinableFlow(docClient, event.pathParameters?.slug)
    if (!joinable) return spaceNotFound()
    const { flow, entity } = joinable
    const flowId = flow.id
 
    if (body.consent !== true) return respond(400, { error: 'CONSENT_REQUIRED' })
 
    const fields = joinFormFields(entity, flow.space.join.userFieldId)
    const answers = pickAnswers(fields, body.answers)
    if (Buffer.byteLength(JSON.stringify(answers)) > MAX_ITEM_SIZE_BYTES) {
      return respond(400, { error: 'ITEM_TOO_LARGE', maxBytes: MAX_ITEM_SIZE_BYTES })
    }
    const invalid = answersError(fields, answers)
    if (invalid) return respond(400, invalid)
 
    const [membershipResult, existingResult] = await Promise.all([
      docClient.send(
        new GetCommand({
          TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
          Key: { userId, flowId }
        })
      ),
      docClient.send(
        new GetCommand({
          TableName: process.env.MEMBERSHIP_REQUESTS_TABLE_NAME,
          Key: { flowId, userId }
        })
      )
    ])
    if (membershipResult.Item?.status === 'active') return respond(409, { error: 'ALREADY_MEMBER' })
    const existing = existingResult.Item
    if (existing?.status === 'banned') return respond(403, { error: 'REQUEST_NOT_ALLOWED' })
    if (existing?.status === 'pending') return respond(409, { error: 'REQUEST_ALREADY_PENDING' })
 
    const bucket = process.env.ATTACHMENTS_BUCKET_NAME
    const promoted = await promoteDraftAnswers({ bucket, fields, answers, flowId, userId })
    if (promoted.error) return respond(400, { error: promoted.error, fieldId: promoted.fieldId })
 
    const now = new Date().toISOString()
    const request = {
      flowId,
      userId,
      status: 'pending',
      statusCreatedAt: statusKey('pending', now),
      answers: promoted.answers,
      consents: { flowDataProcessing: now },
      createdAt: now
    }
 
    try {
      await docClient.send(
        new TransactWriteCommand({
          TransactItems: [
            {
              // Re-checked here: a concurrent request or ban wins over this one
              Put: {
                TableName: process.env.MEMBERSHIP_REQUESTS_TABLE_NAME,
                Item: request,
                ConditionExpression:
                  'attribute_not_exists(userId) OR #status IN (:refused, :approved)',
                ExpressionAttributeNames: { '#status': 'status' },
                ExpressionAttributeValues: { ':refused': 'refused', ':approved': 'approved' }
              }
            },
            {
              Update: {
                TableName: process.env.FLOWS_TABLE_NAME,
                Key: { id: flowId },
                UpdateExpression:
                  'SET pendingRequestCount = if_not_exists(pendingRequestCount, :zero) + :one',
                ConditionExpression:
                  'attribute_not_exists(pendingRequestCount) OR pendingRequestCount < :max',
                ExpressionAttributeValues: { ':zero': 0, ':one': 1, ':max': MAX_PENDING_REQUESTS }
              }
            }
          ]
        })
      )
    } catch (error) {
      // The request isn't written: its copies of the files go too
      await deleteRequestKeys(bucket, flowId, userId, promoted.copiedKeys)
      Eif (error.name === 'TransactionCanceledException') {
        const [requestReason, flowReason] = error.CancellationReasons || []
        if (flowReason?.Code === 'ConditionalCheckFailed') {
          return respond(409, { error: 'TOO_MANY_PENDING_REQUESTS' })
        }
        if (requestReason?.Code === 'ConditionalCheckFailed') {
          return respond(409, { error: 'REQUEST_ALREADY_PENDING' })
        }
      }
      throw error
    }
 
    await deleteDraftKeys(bucket, userId, promoted.draftKeys)
    await emailApprovers({ docClient, flow, requesterId: userId })
 
    return respond(201, { status: 'pending', createdAt: now })
  } catch (error) {
    console.error('Error creating membership request:', error)
    return respond(500, { error: 'Failed to send membership request' })
  }
}