All files / users list.js

100% Statements 32/32
100% Branches 18/18
100% Functions 3/3
100% Lines 31/31

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 1101x 1x 1x 1x 1x 1x 1x   1x         1x 1x   1x 19x 19x 19x     19x 19x 19x 19x   19x 2x                     17x   17x 1x                         16x       3x                     14x             14x                           2x 1x           1x 1x                    
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { permissionChecker } = require('../utils/PermissionChecker')
const { parseListParams, InvalidListParamsError } = require('../utils/platformAdminList')
const { listPlatformDirectory } = require('../utils/platformAdminDirectory')
const { NAMESPACES, containsQuery } = require('../utils/directorySearchIndex')
 
const JSON_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
exports.handler = async (event) => {
  try {
    const search = event.queryStringParameters?.search || ''
    const nextToken = event.queryStringParameters?.nextToken
    // Clamped rather than rejected: this endpoint predates the cap and callers only
    // ever ask for a page (30).
    const requestedLimit = parseInt(event.queryStringParameters?.limit, 10)
    const limit = Number.isInteger(requestedLimit) ? Math.min(Math.max(requestedLimit, 1), 100) : 30
    const flowId = await getActiveFlowId(event)
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId || !flowId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    // Check if user has permission to list users
    const permissionCheck = await permissionChecker.hasPermission(userId, flowId, 'users:list')
 
    if (!permissionCheck.hasPermission) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Forbidden - Insufficient permissions' })
      }
    }
 
    // Members may only match on name/nickname (NAMESPACES.USER) — never email, which
    // this endpoint doesn't expose. No table Scan: a search is answered by the trigram
    // directory index, and an empty search browses newest-first by signup date.
    const { items, nextCursor, truncated } = await listPlatformDirectory(docClient, {
      subjectsTableName: process.env.USERS_TABLE_NAME,
      gsiPkValue: 'USER',
      namespaces: [NAMESPACES.USER],
      verify: (user, query) => containsQuery(query, [user.name, user.nickname]),
      list: parseListParams({
        queryStringParameters: {
          ...(search && { search }),
          limit: String(limit),
          ...(nextToken && { cursor: nextToken })
        }
      })
    })
 
    // Return limited user info (no sensitive data - email is never exposed here)
    const publicUsers = items.map((user) => ({
      id: user.id,
      nickname: user.nickname || null,
      name: user.name,
      status: user.status
    }))
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        items: publicUsers,
        nextToken: nextCursor,
        hasMore: nextCursor !== null,
        truncated
      })
    }
  } catch (error) {
    if (error instanceof InvalidListParamsError) {
      return {
        statusCode: 400,
        headers: JSON_HEADERS,
        body: JSON.stringify({ error: error.message })
      }
    }
    console.error('Error listing users:', error)
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Failed to list users' })
    }
  }
}