All files / users update-preferences.js

100% Statements 74/74
100% Branches 59/59
100% Functions 2/2
100% Lines 73/73

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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 2591x 1x 1x 1x 1x 1x   1x 1x 1x               1x 34x   34x   34x 2x                     32x 32x   32x 32x 32x 32x   32x 3x                         29x 1x                         28x 10x 10x 8x                 2x       20x 1x                       19x   8x 13x     8x 2x                           17x 1x                       16x 16x 16x     16x   16x 6x 6x     16x 1x 1x     16x   2x 2x                   16x 7x             7x 7x   7x   3x 3x   4x 4x 4x       16x 16x 3x               16x 16x                         3x 2x                 1x     13x             13x                             1x 1x                          
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, UpdateCommand, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { S3Client } = require('@aws-sdk/client-s3')
const { userKeyGuard, deleteKeys } = require('../utils/s3Cleanup')
const { DM_POLICIES, getDmPolicy } = require('../utils/directMessages')
const { getWalkthrough, validateWalkthrough } = require('../utils/walkthrough')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const s3Client = new S3Client({ region: 'eu-central-1' })
 
/**
 * Update user preferences
 * PUT /v1/users/preferences
 *
 * @implements UC-DM-008.1, UC-ONBOARD-001.1, UC-ONBOARD-002.1, UC-ONBOARD-003.1
 */
exports.handler = async (event) => {
  try {
    // Extract user ID from Cognito JWT
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Unauthorized - Missing user ID' })
      }
    }
 
    // Parse request body
    const body = JSON.parse(event.body || '{}')
    const { languagePreferences, profilePicture, dmPolicy } = body
 
    const hasLanguagePreferences = Object.prototype.hasOwnProperty.call(body, 'languagePreferences')
    const hasProfilePicture = Object.prototype.hasOwnProperty.call(body, 'profilePicture')
    const hasDmPolicy = Object.prototype.hasOwnProperty.call(body, 'dmPolicy')
    const hasWalkthrough = Object.prototype.hasOwnProperty.call(body, 'walkthrough')
 
    if (!hasLanguagePreferences && !hasProfilePicture && !hasDmPolicy && !hasWalkthrough) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error:
            'Invalid input - provide languagePreferences, profilePicture, dmPolicy and/or walkthrough'
        })
      }
    }
 
    if (hasDmPolicy && !DM_POLICIES.includes(dmPolicy)) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: `Invalid dmPolicy - must be one of ${DM_POLICIES.join(', ')}`
        })
      }
    }
 
    let walkthrough
    if (hasWalkthrough) {
      const validation = validateWalkthrough(body.walkthrough)
      if (validation.error) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: validation.error })
        }
      }
      walkthrough = validation.value
    }
 
    // Validate language preferences when provided
    if (hasLanguagePreferences && !Array.isArray(languagePreferences)) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: 'Invalid input - languagePreferences must be an array'
        })
      }
    }
 
    if (hasLanguagePreferences) {
      // Validate array contains only valid language codes (2-letter strings)
      const validPrefs = languagePreferences.every(
        (lang) => typeof lang === 'string' && lang.length === 2
      )
 
      if (!validPrefs) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({
            error: 'Invalid language codes - must be 2-letter strings'
          })
        }
      }
    }
 
    // Validate profile picture key when provided (null clears the value)
    if (hasProfilePicture && profilePicture !== null && typeof profilePicture !== 'string') {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: 'Invalid profilePicture - must be a string or null'
        })
      }
    }
 
    const updateParts = ['updatedAt = :now']
    const removeParts = []
    const expressionAttributeValues = {
      ':now': new Date().toISOString()
    }
    const expressionAttributeNames = {}
 
    if (hasLanguagePreferences) {
      updateParts.push('languagePreferences = :prefs')
      expressionAttributeValues[':prefs'] = languagePreferences
    }
 
    if (hasDmPolicy) {
      updateParts.push('dmPolicy = :dmPolicy')
      expressionAttributeValues[':dmPolicy'] = dmPolicy
    }
 
    if (hasWalkthrough) {
      // Not snoozed is stored as an absent snoozedUntil rather than a null
      updateParts.push('walkthrough = :walkthrough')
      expressionAttributeValues[':walkthrough'] = {
        seenSteps: walkthrough.seenSteps,
        dismissed: walkthrough.dismissed,
        ...(walkthrough.snoozedUntil ? { snoozedUntil: walkthrough.snoozedUntil } : {})
      }
    }
 
    // The profile picture this request replaces or clears, deleted from S3 once
    // the row no longer points at it.
    let previousProfilePicture
    if (hasProfilePicture) {
      const currentUser = await docClient.send(
        new GetCommand({
          TableName: process.env.USERS_TABLE_NAME,
          Key: { id: userId },
          ProjectionExpression: 'profilePicture'
        })
      )
      const existingKey = currentUser.Item?.profilePicture
      if (existingKey && existingKey !== profilePicture) previousProfilePicture = existingKey
 
      if (profilePicture === null) {
        // Use REMOVE to delete the attribute (DynamoDB does not accept null in ExpressionAttributeValues)
        removeParts.push('#profilePicture')
        expressionAttributeNames['#profilePicture'] = 'profilePicture'
      } else {
        updateParts.push('#profilePicture = :profilePicture')
        expressionAttributeNames['#profilePicture'] = 'profilePicture'
        expressionAttributeValues[':profilePicture'] = profilePicture
      }
    }
 
    let updateExpression = `SET ${updateParts.join(', ')}`
    if (removeParts.length > 0) {
      updateExpression += ` REMOVE ${removeParts.join(', ')}`
    }
 
    // Update user preferences in DynamoDB. ConditionExpression guards against
    // UpdateCommand's implicit upsert: without it, a request for a userId with
    // no existing row (e.g. deleted user, in-flight request racing a signup)
    // silently creates a bare stub row with only id/updatedAt/languagePreferences.
    let result
    try {
      result = await docClient.send(
        new UpdateCommand({
          TableName: process.env.USERS_TABLE_NAME,
          Key: { id: userId },
          UpdateExpression: updateExpression,
          ConditionExpression: 'attribute_exists(id)',
          ExpressionAttributeNames:
            Object.keys(expressionAttributeNames).length > 0 ? expressionAttributeNames : undefined,
          ExpressionAttributeValues: expressionAttributeValues,
          ReturnValues: 'ALL_NEW'
        })
      )
    } catch (error) {
      if (error.name === 'ConditionalCheckFailedException') {
        return {
          statusCode: 404,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'User not found' })
        }
      }
      throw error
    }
 
    await deleteKeys(
      s3Client,
      process.env.ATTACHMENTS_BUCKET_NAME,
      [previousProfilePicture],
      userKeyGuard(userId)
    )
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        message: 'User preferences updated successfully',
        languagePreferences: result.Attributes?.languagePreferences || [],
        profilePicture: result.Attributes?.profilePicture || null,
        dmPolicy: getDmPolicy(result.Attributes),
        walkthrough: getWalkthrough(result.Attributes)
      })
    }
  } catch (error) {
    console.error('Error updating user preferences:', error)
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        error: 'Failed to update user preferences',
        details: error.message
      })
    }
  }
}