All files / users get.js

100% Statements 44/44
90% Branches 27/30
100% Functions 1/1
100% Lines 44/44

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                              1x 1x 1x 1x 1x   1x 1x   1x         1x 18x 18x 18x 1x             17x 17x 1x             16x             15x 1x             14x 14x 14x 12x           12x 12x 10x                                     14x 14x 14x 14x 14x 14x                       13x 13x 13x   1x       14x 14x 4x 4x   1x       14x                                   1x 1x              
/**
 * GET /v1/users/{userId}
 *
 * Public profile lookup for another user — the target of the "click a user
 * in the catalog / members page" Direct Message entry point. Returns the
 * same non-sensitive PublicUser projection users/list.js already exposes,
 * plus `canMessage` so the frontend knows whether to show a "Message"
 * button (see utils/directMessages.js: blocks, the user's "who can message
 * me" setting, and an existing conversation that can always be reopened),
 * `isBlockedByCurrentUser`, and the user's moderation `reputationScore`
 * (informative: it gates nothing — see docs/architecture/MODERATION.md).
 *
 * @implements UC-MOD-009.1, UC-DM-002.2, UC-DM-008.1, UC-DM-009.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { getBlockState, canStartConversation, findConversation } = require('../utils/directMessages')
const { getFollowerCounts, getFollowingCount } = require('../utils/userFollows')
const { getStats } = require('../utils/moderation/engine')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
exports.handler = async (event) => {
  try {
    const callerId = event.requestContext?.authorizer?.claims?.sub
    if (!callerId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    const userId = event.pathParameters?.userId
    if (!userId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing userId' })
      }
    }
 
    const result = await docClient.send(
      new GetCommand({
        TableName: process.env.USERS_TABLE_NAME,
        Key: { id: userId }
      })
    )
 
    if (!result.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'User not found' })
      }
    }
 
    let canMessage = false
    let isBlockedByCurrentUser = false
    if (callerId !== userId) {
      const blocks = await getBlockState(
        docClient,
        process.env.USER_BLOCKS_TABLE_NAME,
        callerId,
        userId
      )
      isBlockedByCurrentUser = blocks.blockedByUser
      if (!blocks.blockedByUser && !blocks.blockedByOther) {
        canMessage =
          !!(await findConversation(
            docClient,
            process.env.CONVERSATIONS_TABLE_NAME,
            callerId,
            userId
          )) ||
          (await canStartConversation(
            docClient,
            {
              userFollowsTableName: process.env.USER_FOLLOWS_TABLE_NAME,
              flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME
            },
            callerId,
            result.Item
          ))
      }
    }
 
    let followerCount = 0
    let followingCount = 0
    let isFollowedByCurrentUser = false
    Eif (process.env.USER_FOLLOWS_TABLE_NAME && process.env.USER_FOLLOWER_COUNT_TABLE_NAME) {
      try {
        const [followerCounts, following, existingFollow] = await Promise.all([
          getFollowerCounts(docClient, process.env.USER_FOLLOWER_COUNT_TABLE_NAME, [userId]),
          getFollowingCount(docClient, process.env.USER_FOLLOWS_TABLE_NAME, userId),
          callerId === userId
            ? Promise.resolve(null)
            : docClient.send(
                new GetCommand({
                  TableName: process.env.USER_FOLLOWS_TABLE_NAME,
                  Key: { followerId: callerId, followeeId: userId }
                })
              )
        ])
        followerCount = followerCounts.get(userId) ?? 0
        followingCount = following
        isFollowedByCurrentUser = callerId !== userId && !!existingFollow?.Item
      } catch (followErr) {
        console.error('[users/get] Error fetching follow data:', followErr)
      }
    }
 
    let reputationScore = 0
    if (process.env.MODERATOR_STATS_TABLE_NAME) {
      try {
        reputationScore = (await getStats(docClient, userId)).reputationScore
      } catch (statsErr) {
        console.error('[users/get] Error fetching moderation stats:', statsErr)
      }
    }
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({
        id: result.Item.id,
        nickname: result.Item.nickname || null,
        name: result.Item.name,
        status: result.Item.status,
        profilePicture: result.Item.profilePicture || null,
        canMessage,
        isBlockedByCurrentUser,
        followerCount,
        followingCount,
        isFollowedByCurrentUser,
        reputationScore
      })
    }
  } catch (error) {
    console.error('[users/get] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to fetch user' })
    }
  }
}