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 | 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 2x 2x 2x 1x 1x 1x | /**
* WebSocket $connect route.
*
* A browser WebSocket client can't set an Authorization header on the
* upgrade request, so the Cognito access token instead rides the connect
* URL's query string: `wss://.../?token=<jwt>`. Verified via
* shared/auth-helper.js's verifyJwt (the same JWKs signature-verification
* core REST endpoints with authorizationType NONE use), rather than
* duplicating that logic here.
*
* API Gateway rejects the WebSocket upgrade unless this returns a 2xx
* status code, so an invalid/missing token must be a non-2xx, not a normal
* JSON error body.
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb')
const { verifyJwt } = require('../shared/auth-helper')
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const CONNECTION_TTL_SECONDS = 24 * 60 * 60
exports.handler = async (event) => {
try {
const token = event.queryStringParameters?.token
const payload = await verifyJwt(token)
const userId = payload?.sub
if (!userId) {
return { statusCode: 401, body: 'Unauthorized' }
}
const now = new Date()
await docClient.send(
new PutCommand({
TableName: process.env.WEBSOCKET_CONNECTIONS_TABLE_NAME,
Item: {
connectionId: event.requestContext.connectionId,
userId,
connectedAt: now.toISOString(),
expiresAt: Math.floor(now.getTime() / 1000) + CONNECTION_TTL_SECONDS
}
})
)
return { statusCode: 200, body: 'Connected' }
} catch (error) {
console.error('[websocket/connect] Exception:', error.message, error.stack)
return { statusCode: 500, body: 'Failed to connect' }
}
}
|