-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathretrieve-session-by-access-token.ts
More file actions
53 lines (44 loc) · 1.82 KB
/
retrieve-session-by-access-token.ts
File metadata and controls
53 lines (44 loc) · 1.82 KB
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
import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb";
import { AccessTokenIndexSessionItem } from "../../../common/src/types/access-token-index-session-item";
import { logger } from "../../../common/src/util/logger";
import { CriError } from "../../../common/src/errors/cri-error";
import { safeStringifyError } from "../../../common/src/util/stringify-error";
import { unmarshall } from "@aws-sdk/util-dynamodb";
import { withRetry } from "../../../common/src/util/retry";
export async function retrieveSessionIdByAccessToken(
sessionTableName: string,
dynamoClient: DynamoDBClient,
accessToken: string
): Promise<string> {
try {
async function sendQueryCommand() {
const command = new QueryCommand({
TableName: sessionTableName,
IndexName: "access-token-index",
KeyConditionExpression: "accessToken = :value",
ExpressionAttributeValues: {
":value": {
S: accessToken,
},
},
});
const result = await dynamoClient.send(command);
if (result.Count === 0 || !result.Items) {
throw new CriError(400, `No session entry found for the given access token`);
}
const retrievedRecords = result.Items.map((v) => unmarshall(v)) as AccessTokenIndexSessionItem[];
if (retrievedRecords.length > 1) {
throw new CriError(500, `Found ${retrievedRecords.length} session records but was only expecting 1.`);
}
return retrievedRecords[0].sessionId;
}
return await withRetry(sendQueryCommand, logger, {
maxRetries: 3,
baseDelay: 300,
});
} catch (error) {
if (error instanceof CriError) throw error;
logger.error(`Caught unexpected session retrieval error: ${safeStringifyError(error)}`);
throw new CriError(500, "Unexpected error getting session information");
}
}